Python Fundamentals programs
1 WAP to accept 10 numbers and find the maximum value entered by the user. It should
display the maximum number after accepting 10 values.
lar=0
print('Enter 10 numbers')
for i in range(1,11):
n=int(input())
if i==1:
lar=n # store the first number
elif n>lar: # compare the previous stored number with the latest entered number
lar=n
print('Largest Number =',lar)
2 WAP to accept a number and print the reverse that number.
Ans:
num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))
3 WAP to display sum of even number up to number n entered by the user.
num = int(input('Enter a number: '))
sum = 0
i=0
while i <= num:
if i % 2 == 0:
print(i)
sum+=i
i+=1
print("Sum of all the even numbers is",sum)
Output: Enter a number 10
0
2
4
6
8
10
sum of all even numbers is 30
4 WAP to take two numbers and print if the first number is fully divided by second number
or not.
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print(x % y and "Not Fully Divisible" or "Fully Divisible")
5 WAP to calculate BMI of a person after inputting its weight in kgs and height in meters
and then display the nutritional status as per following table.
Nutritional status WHO criteria BMI cut off
Underweight <18.5
Normal 18.5-24.9
Overweight 25-29.9
Obese >=30
weightkg=float(input(“Enter the weight in kg”))
heightmeter=float input(“Enter the height in meters:”))
bmi=weightkg/(heightmeter*heightmeter)
print(“BMI is:”,bmi)
if bmi<18.5:
print(“Underweight”)
elif bmi<25:
print(“Normal”)
elif bmi<30:
print(“Overweight”)
else:
print(“obsess”)
String Programs
6 Write a program to check whether the string is a palindrome or not.
str=input("enter the string")
s=len(str)
p=s-1
index=0
while(index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
print("string is not a palindrome")
else:
print("string is a palindrome")
7 Write a program that reads a line, then counts words and displays how many words are
there in the line.
line = input("Enter a line: ")
line = line.lower()
words = line.split()
count = words.count('is')
print("The word 'is' appears", count, "times.")
8 WAP to remove vowels from string.
Ans:
letter="hello world"
letter1=" "
for i in letter:
if i not in ('a','e','i','o','u'):
letter1+=i
print(letter1)
Ans 2:
Str1=input(“Enter a string”)
Str2=” “
For i in range(len(str1)):
If str1[i] not in ‘aeiouAEIOU’:
Str2=str2+str2[i]
Print(“original string”,str1)
Print(“Removed vowels”,str2)
9 WAP that reads a string and displays the longest substring of the given string.
Ans:
str1=input(“enter a string”)
word=str1.split()
maxlength=0
maxword=” “
for i in word:
x=len(i)
if x>maxlength and i.isalpha()==True:
print(i)
maxlength=x
maxword=i
print(“substring with maximum length is:,maxword)
10 Write a program which consider any string and count no of repeated words or string in given
sentence.
Exmaple: what are you doing? How are you learning?
you present 2 times.
Ans:
count = 0
my_string = input("Enter a string")
str=my_string.split()
print(str)
my_char = input("Enter string to check")
for word in str:
if word== my_char:
count += 1
print(count)
11 WAP that asks the user for a string and a character c and then it prints out the location of each
character c in the string s.
s=input("Enter some text")
c=input("enter character")
#print(s,"character",c,"found at these locations",end=" ")
for i in range(len(s)):
if s[i]==c:
print(i,end=" ")
Output:
Enter some texthello
enter characterl
23
12 WAP to input a line of text and prints its each word in a separate line. Also print the count of
words in the line.
s=input(“Enter a line of text”)
count=0
for word in s.split():
print(word)
count+=1
print(“Total words:”,count)
13 Write a program to input the ‘abcd224’.Calculate the sum of digits and the character should be
printed as it is.
s=input("Enter the string")
sum=0
s1=""
#s1=""
for i in s:
if i.isdigit():
sum+=int(i)
elif i.isalpha():
s1+=i
print(s1)
print(sum)
Output:
Enter the stringabc213
abc
6
14 WAP to input a string and print each individual word of it along with its length.
strg=input(“Enter a string”)
strlst=strg.split()
for word in stlst:
print(word,”(“,len(word),”)
15 Write a program to input a line of text and print the biggest word (length wise) from it.
str = input("Enter a string: ")
words = str.split()
longWord = ''
for w in words :
if len(w) > len(longWord) :
longWord = w
print("Longest Word =", longWord)
List programs
16 s=['W','e','a','r', ' ' ,'a', ' ' , 'M','a','s','k']
length=len(s)
for i in range(length):
print("The element ",s[i], "is at indexes ",i, "and" ,(i-length))
17 find the element in the list which can be
#divided by 7 and multiplied by 7 else multiplied by 4
'''L=[16,49,21,20,15] #elements in the list
length=len(L) #length=5
for x in range(0,length): #0,5 x=3,x=4
if L[x]%7==0: #L[1]= 49%7 -True, 21%7- True,
L[x]=L[x]*7 #49*7= ,21*7=
else:
L[x]=L[x]*4 #16*4=64, 20,15
print ("Elements are ", L)'''
18 WAP to seperate the string and integer
'''wtemp=['mon','tue',23,45,'wed',24]
#ln=len(wtemp)
#print(ln)
days=[]
degrees=[]
for i in wtemp:
print(i)
if i.isdigit():
degress.append(i)
else:
days.append(i)
print(days)
19 WAP to append the inputted numbers which is divided by 10 and 5 in L1 and divided by 2 in L2.
L1=[]
L2=[]
for i in range(10):
k=int(input("Enter any number"))
if k%10==0 and k%5==0:
L1.append(k)
elif k%2==0:
L2.append(k)
print("The list of number divided by 5 and 10",L1)
print("The list of number divided by 2",L2)
20 WAP to find the element index and element position in the inputted list.
mylist=[]
print("Enter 5 elements")
for i in range(5):
value=int(input("Enter the numbers"))
mylist.append(value)
ele=int(input("Enter the element to search"))
for i in range(5):
if ele==mylist[i]:
print("element found at index:",i)
print("Element found at position:",i+1)
21 WAP to calculate the mean of a given list of numbers.
lst=eval(input(“Enter list”))
length=len(lst)
mean=sum=0
for I in range(0,length):
sum+=lst[i]
mean=sum/length
print(“given list is”,lst)
print(“The mean value is”,mean)
22 WAP to input a list of numbers and swap elements at the even location with the elements at the
off location.
val=eval(input(“Enter the list:”))
print(“original list”,val)
s=len(val)
if s%2!=0:
s=s-1
for I in range(0,s,2):
print(I,i+1)
val[i],val[i+1]=val[i+1],val[i]
print(“list after swapping”,val)
23 WAP to input a list and an elements and remove all occurences of the given element from the
list.
lst=eval(input("enter a list"))
item=int(input("Enter the element to be removed"))
c=lst.count(item)
print(c)
if c==0:
print(item,"not in the list")
else:
while item in lst:
i=lst.remove(item)
print("List after removing",lst)
Tuple programs
24 WAP to enter the email id and split to user name and domain
n=int(input("Enter how many email id:"))
t1=()
un=()
dom=()
for i in range(n):
em=input("Enter email id")
t1=t1+(em,)
for i in t1:
a=i.split('@')
un=un+(a[0],)
dom=dom+(a[1],)
print("Original email id:",t1)
print("Username:",un)
print("domain name are",dom)
25 Write a Python program that creates a tuple storing
#first 9 terms of Fibonacci series.
lst = [0,1]
a=0
b=1
c=0
for i in range(7):
c=a+b
a=b
b=c
lst.append(c)
tup = tuple(lst)
print("9 terms of Fibonacci series are:", tup)
26 Write a program that interactively creates a nested tuple to
store the marks in three subjects for five students, i.e., tuple will look somewhat like :
marks( (45, 45, 40), (35, 40, 38), (36, 30, 38), (25, 27, 20), (10, 15, 20) )
num_of_students = 5
tup = ()
for i in range(num_of_students):
print("Enter the marks of student", i + 1)
m1 = int(input("Enter marks in first subject: "))
m2 = int(input("Enter marks in second subject: "))
m3 = int(input("Enter marks in third subject: "))
tup = tup + ((m1, m2, m3),)
print()
print("Nested tuple of student data is:", tup)
27 WAP to Count frequencies of all elements given in tuple and print in the form of dictionary
my_tuple = (1, 2, 3, 2, 4, 2, 5)
frequency = Counter(my_tuple)
print("Frequency of all elements:")
for element, count in frequency.items():
print("{element}: {count}")
28 WAP secondlargest(t) which takes a input as tuple and returns the second largest element in the
tuple.
t=(23,45,34,66,77,67,70)
maxvalue=max(t)
length=len(t)
secmax=0
for a in range(length):
if secmax<t[a]<maxvalue:
secmax=t[a]
print("Second largest value is:",secmax)
29 WAP to check if a tuple contains any duplicate elements.
tup=eval(input(“Enter a tuple”))
for e in tup:
if tup.count(e)>1:
print(“contains duplicate elements”)
break
Dictionary programs
30 Write a Python program to create a dictionary from a string.
#Note: Track the count of the letters from the string.
#Sample string : 'w3resource'
#Expected output : {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
'''st = input("Enter a string: ")
dic = {}
#creates an empty dictionary
for ch in st:
if ch in dic:
#if next character is already in the dictionary
dic[ch] += 1
else:
#if ch appears for the first time
dic[ch] = 1
#Printing the count of characters in the string
print(dic)'''
31 write a program in ptyhon to remove
#the duplicate values form the dcitionary
#original dictionary={1:"aman",2:"Suman",3:"Aman"}
#new dictionary={1:"aman",2:"Suman"}
d1={1:"Aman",2:"Suman",3:"Aman"}
nd1={}
#s=d1.values() #elements giving in the list of tuples
for k,v in d1.items():
print(k,v)
if v not in nd1.values():
nd1[k]=v
print(nd1)
32 find the maximum and minimum element in the dictionary
dic = {"A":12,"B":13,"C":9,"D":89,"E":34,"F":17,"G":65,"H":36,"I":25,"J":11}
lst=list()
ic = {"A": 12, "B": 13, "C": 9, "D": 89, "E": 34,
for a in dic.values(): "F": 17, "G": 65, "H": 36, "I": 25, "J": 11}
print(a) lst = list()
for i in ic.values(): # Corrected `dic` to `ic`
lst.append(a) print(i)
lst.sort() lst.append(i)
lst.sort()
print(lst) print(lst)
print(lst[-1]) print(lst[-1]) # Largest value
print(lst[-2]) # Second largest value
print(lst[-2])
33 WAP to create the name with their salary
'''rec=int(input("enter the total no of records:"))
i=1
emp=dict()
while i<=rec:
name=input("enter the name of the employee")
salary=int(input("enter the salary"))
emp[name]=salary
i=i+1
print("\nEmployee\t Salary")
for k in emp:
print(k,':',emp[k])'''
34 WAP to show the frequency of each character in the input string "programming"
str=input("enter a string") #input
dict1={} #empty dictionary
for ch in str: #storing in ch
if ch in dict1: #checking the condition
dict1[ch]+=1 #starts counting
else:
dict1[ch]=1 #appears one time
for key in dict1: #display the output the form of dictionary
print(key,':',dict1[key])
35 A dictionary D1 has values in the form of list of numbers. Write a program to create a new
dictionary D2 having same keys as D1 but values as the sum of the list elements
ex:
D1={‘A’:[1,2,3],’B’,[4,5,6]}
then
D2={‘A’:6,’B’:15}
Ans:
D1 = eval(input("Enter a dictionary D1: "))
print("D1 =", D1)
D2 = {}
for key in D1:
num = sum(D1[key])
D2[key] = num
print(D2)