0% found this document useful (0 votes)
40 views15 pages

Practical

The document contains 14 programming problems with solutions in Python. Each problem introduces a practical task related to Python programming concepts like variables, conditionals, loops, functions, lists, dictionaries etc. For each problem, the document provides the problem statement, sample code to solve the problem, and an explanation of the solution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views15 pages

Practical

The document contains 14 programming problems with solutions in Python. Each problem introduces a practical task related to Python programming concepts like variables, conditionals, loops, functions, lists, dictionaries etc. For each problem, the document provides the problem statement, sample code to solve the problem, and an explanation of the solution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Practical List Python

Proposed practicals

Practical Create a program that asks the user to enter their name and their age. Print out a
No. 1 message addressed to them that tells them the year that they will turn 100 years old.

Solution: from datetime import datetime


name = input('Enter your name? \n')
age = int(input('How old are you? \n'))
hundred = int((100-age) + datetime.now().year)
print ('Hello %s. You are %s years old. You will be 100 years old in %s.' % (name,
age, hundred))
Practical Enter the number from the user and depending on whether the number is even or odd,
No. 2 print out an appropriate message to the user.
Solution: num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")
Practical Write a program to generate the Fibonacci series.
No. 3
Solution: # Program to display the Fibonacci sequence up to n-th term where n is provided by
the user

# change this value for a different result


nterms = 10

# uncomment to take input from the user


#nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Practical Write a function that reverses the user defined value.
No. 4
Solution: # Python Program to Reverse a Number using While loop

Number = int(input("Please Enter any Number: "))


Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10

print("\n Reverse of entered number is = %d" %Reverse)


Practical Write a function to check the input value is Armstrong and also write the function for
No. 5 Palindrome.
Solution def myarmstrong():
1 num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
def mypalindrome():
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
Solution def isArmstrong(n):
2 #armstrong number is a number whose sum of cube of digits is the same
number
# 1^3 + 5^3 + 3^3 = 153

copy = n

#sum initially 0
s=0

while n!=0:
last_digit = n % 10
# ** operator is use to find power
s = s + (last_digit ** 3)
n = n // 10
if s==copy:
return True
else:
return False

def isPalindrome(s):
rev = s[::-1]
if rev==s:
return True
else:
return False

def main():
#input number to check armstrong number
n = int(input("Enter number to check armstrong : "))

if isArmstrong(n):
print("%d is Armstrong number" % n)
else:
print("%d is not Armstrong number" % n)

#input string to check palindrome


s = input("Enter string to check palindrome : ")

if isPalindrome(s):
print("%s is Palindrome" % s)
else:
print("%s is not Palindrome" % s)

main()
Practical Write a recursive function to print the factorial for a given number
No. 6
Solution: def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)

# Change this value for a different result


num = 7

# uncomment to take input from the user


#num = int(input("Enter a number: "))

# check is the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
Practical Write a function that takes a character (i.e. a string of length 1) and returns True if it is a
No. 7 vowel, False otherwise.
Solution: def is_vowel(char):
vowels = ('a', 'e', 'i', 'o', 'u')
if char not in vowels:
return False
return True
Practical Define a function that computes the length of a given list or string
No. 8
Solution: def mystrlen():
1 str = input("Enter a string: ")
# counter variable to count the character in a string
counter = 0
for s in str:
counter = counter+1
print("Length of the input string is:", counter)
mystrlen()
Solution: def mystrlen():
2 str = input("Enter a string: ")
# using len() function to find length of str
print("Length of the input string is:", len(str))
mystrlen()
Practical Write a program that takes two lists and returns True if they have at least
No. 9 one common member.
Solution: def common_data(list1, list2):
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))
Practical Write a Python program to print a specified list after removing the 0th, 2nd,
No. 10 4th and 5th elements.
Solution: lists= ['Apple','Banana','Kivi','Greps','Blackberries','Cherries','JACKFRUIT']
lists= [x for (i,x) in enumerate(lists) if i not in (0,2,4,5)]
print (lists)
Practical Write a Python program to clone or copy a list
No. 11
Solution: original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)

Practical Write a Python script to sort (ascending and descending) a dictionary by value
No. 12

Solution: import operator


d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(0),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)
Practical Write a Python script to concatenate following dictionaries to create a new one.
No. 13 dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Solution: dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)
Practical Write a Python program to sum all the items in a dictionary
No. 14

Solution: d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values()))

You might also like