0% found this document useful (0 votes)
10 views8 pages

Python Codes

The document contains various Python code examples for string manipulation, list operations, and dictionary handling. It includes programs for checking character types, palindrome detection, vowel replacement, and employee salary management. Additionally, it demonstrates how to count character occurrences and convert numbers to words.

Uploaded by

abhinavchettri90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views8 pages

Python Codes

The document contains various Python code examples for string manipulation, list operations, and dictionary handling. It includes programs for checking character types, palindrome detection, vowel replacement, and employee salary management. Additionally, it demonstrates how to count character occurrences and convert numbers to words.

Uploaded by

abhinavchettri90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

PYTHON CODES

STRING:

1) Write a program for checking whether the given character is uppercase ,lowercase,
digit ,special symbol or white space.
def check(ch):

if (ch >= 'A' and ch <= 'Z'):

print(ch,"is an UpperCase character");

elif (ch >= 'a' and ch <= 'z'):

print(ch,"is an LowerCase character");

elif (ch >= '0' and ch <= '9'):

print(ch,"is not an alphabetic character");

else:

print("The Given Character ", ch, "is a Special Character")

2) Write a program to check whether the given String is a palindrome or not


string=input("Enter string:")

if(string==string[::-1]):

print("The string is a palindrome")

else:

print("The string isn't a palindrome")

3) Write a program which replaces all vowels in the string with ’*’
my_string = input('ENter your String : ')

my_char = input('ENter your character : ')

vowels = ['a','e','i','o','u','A','E','I','O','U']
new_string = ''

for i in my_string:

if i in vowels:

new_string +=my_char

else:

new_string += i

print(new_string)

4) Write a program to display the last word of the string accepted from user.
def lastWord(string):

newstring = “”

length = len(string

for i in range(length-1, 0, -1)

if(string[i] == " "):

return newstring[::-1]

else:

newstring = newstring + string[i]

5) Write a program to accept a string and display the with second


alphabet of each word in upper case.
s=input("enter a string: ")
l=s.split()
print(l)
for i in l:
j=i[1].upper()
print(j)
print()

LIST MANIPULATION:
1) Write a program to find Sum and average of all numbers in the list
a = [10,20,30,40,50]
totalSum = sum(a)
average = totalSum / len(a)
print("Sum of the list:", totalSum)
print("Average of the list:", average)

2) Write a program to find Sum of odd and even numbers in a List


number_list = [1, 2, 3, 4, 5, 6]

def calculate_odd_even():
odd_number = 0
even_number = 0
for i in number_list:
if i % 2 == 0:
even_number = even_number + i
else:
odd_number = odd_number + i

return (odd_number, even_number)

my_tuple = calculate_odd_even()
print(my_tuple)

3) Write a program to Count number of positive and negative numbers


a = [10, -20, 30, -40, 50, -60, 0]

# Count positive numbers


pos = len([n for n in a if n > 0])

# Count negative numbers


neg = len([n for n in a if n < 0])

print(pos)
print(neg)

4) Write a program to Add 2 to even numbers and subtract 1 from odd


numbers.
l=int(input("enter a list:"))
for i in l:
if i%2==0:
l.append[i+2]
print(l)
else:
l.append[i-1]
print(l)

5) Write a program to find the average of the list of the numbers


entered through keyboard
a = [2, 4, 6, 8, 10]
avg = sum(a) / len(a)
print(avg)

6) Write a program to get a list of numbers from the user and Multiply even indexed numbers
in a list by 2
l=int(input("enter a list:"))
for i in l:
if i%2==0:
i=i*2
print(i,'')
7) Write a program to display number of names which starts with letter ‘A’ in the list of names
n=int(input("enter a list:"))
for i in n:
if n[i[0]=='A'
print("letter starting with letter 'A':")

8) Write a program to display number of 5 lettered city names in the list of city names
d=dict()

print("Enter 5 state names with capital.")

for i in range(5):

s=input("Enter State: ")

c=input("Enter Capital: ")

print()

d[s]=c

x=input("Now, enter a state name: ")

if x in d.keys():

print("Found.")

print(f"Capital of {x} is {d[x]}")

else:

print("Not Found.")

9) Write a program in python which display only those names from the list which have ‘i’ as
second last character. like L = [“Amit”, “Suman”, “Sumit”, “Montu” , “Anil”]

Output :

Amit

Sumit

L = ["Amit", "Suman", "Sumit", "Montu", "Anil"]

result = [name for name in L if len(name) > 1 and name[-2] == 'i']

for name in result:


print(name)

10) Write a program in python which swap the alternate members of list (assuming that even
number of elements in the list). like as shown below:
Original List : L = [23, 45, 67, 29, 12, 1]
After Swaping : L = [45,23, 29, 69, 1, 12]
a = [23,45,67,29,12,1]
a[0], a[2], a[4], a[1], a[3], a[5] = a[1], a[3], a[5], a[0], a[2], a[4]
print(a)

DICTIONARY:
1. Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is the
decimal number and the value is the corresponding number in words. Perform the
following operations on this dictionary:
(a) Display the keys
(b) Display the values
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9

Program Code:

ODD = {1: 'one', 3: 'three', 5: 'five', 7: 'seven', 9: 'nine'}


keys = ODD.keys()
print("Keys:", keys)
# Output: Keys: dict_keys([1, 3, 5, 7, 9])
values = ODD.values()
print("Values:", values)
# Output: Values: dict_values(['one', 'three', 'five', 'seven', 'nine'])
items = ODD.items()
print("Items:", items)
# Output: Items: dict_items([(1, 'one'), (3, 'three'), (5, 'five'), (7, 'seven'), (9, 'nine')])
length = len(ODD)
print("Length:", length)
# Output: Length: 5
is_seven_present = 7 in ODD
print("Is 7 present?", is_seven_present)
# Output: Is 7 present? True
is_two_present = 2 in ODD
print("Is 2 present?", is_two_present)
# Output: Is 2 present? False
value_nine = ODD.get(9)
print("Value corresponding to key 9:", value_nine)
# Output: Value corresponding to key 9: nine
ODD.pop(9, None)
print("Dictionary after deleting key 9:", ODD)
# Output: Dictionary after deleting key 9: {1: 'one', 3: 'three', 5: 'five', 7: 'seven'}

2. Write a program to enter names of employees and their salaries as input and store them in a
dictionary.

Program Code:
employees = {}
num_employees = int(input("Enter the number of employees: "))
for i in range(num_employees):
name = input("Enter employee name: ")
salary = float(input("Enter employee salary: "))
employees[name] = salary
print("Employee salaries:", employees)

Executable output:
Enter the number of employees: 3
Enter employee name: Aviral
Enter employee salary: 56900
Enter employee name: Abhinav
Enter employee salary: 69000
Enter employee name: Amarnath
Enter employee salary: 55000
Employee salaries: {'Aviral': 56900.0, 'Abhinav': 69000.0, 'Amarnath': 55000.0}

3. Write a program to count the number of times a character appears in a given string.

Program Code:

def count_character_occurrences(input_string):

char_count = {}

for char in input_string:

if char in char_count:

char_count[char] += 1
else:

char_count[char] = 1

return char_count

input_string = input("Enter a string: ")

char_count = count_character_occurrences(input_string)

print("Character count:", char_count)

Executable Output: Enter a string:


Enter a string: Anglo African war
Character count: {'A': 2, 'n': 2, 'g': 1, 'l': 1, 'o': 1, ' ': 2, 'a': 2, 'f': 1, 'r': 2, 'i': 1, 'c': 1, 'w': 1}

4. Write a function to convert a number entered by the user into its corresponding number in
words. For example, if the input is 876 then the output should be ‘Eight Seven Six’.

Program Code:

def number_to_words(number):
digit_to_word = {'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four', '5': 'Five', '6': 'Six',
'7': 'Seven', '8': 'Eight', '9': 'Nine'}
number_str = str(number)
words = [digit_to_word[digit] for digit in number_str]
result = ' '.join(words)
return result
input_number = input("Enter a number: ")
output = number_to_words(input_number)
print("The number in words is:", output)

Executable Output:

Enter a number: 969


The number in words is: Nine Six Nine
OR
Enter a number: 7890
The number in words is: Seven Eight Nine Zero

5. Write a program to display the name of all the employees whose salary is more than
25000 from the following dictionary. emp={1:(“Amit”,25000),2:(“Suman”,30000),3:
(“Ravi”,36000)}
Format of data is given below :
{Empid : (Empname, EmpSalary)}
Program Code:

emp = {1: ("Amit", 25000), 2: ("Suman", 30000), 3: ("Ravi", 36000)}


def display_high_salary_employees(employee_dict, threshold):
high_salary_employees = [name for empid, (name, salary) in employee_dict.items() if
salary > threshold]
return high_salary_employees
threshold = 25000
result = display_high_salary_employees(emp, threshold)
print("Employees with salary more than 25000:", result)

Output:

Employees with salary more than 25000: ['Suman', 'Ravi']

You might also like