Python Practical

 1. Write the program for the following: 

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

username=input("Please enter your name")
userage=input("Please enter your age")

def age100(userage):

   turn=100-userage+2017

   return turn


turn = age100(userage)

message= 'Hello %s, your age is %d and you will turn 100 in the year %d' %(username,userage, turn)
print(message)

b. Enter the number from the user and depending on whether the number is even or odd, print out an appropriate message to the user. 

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.")

c. Write a program to generate the Fibonacci series.

a=int(input("Enter the first number of the series "))
b=int(input("Enter the second number of the series "))
n=int(input("Enter the number of terms needed "))
print(a,b,end=" ")
while(n-2):
    c=a+b
    a=b
    b=c
    print(c,end=" ")

    n=n-1

d. Write a function that reverses the user-defined value. 

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)

e. Write a function to check the input value is Armstrong and also write the function for Palindrome.

def isArmstrong(n):
#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()

f. Write a recursive function to print the factorial for a given number.

def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1)

def main():
n = int(input("Enter number to find Factorial : "))

fact = factorial(n)

print("%d! = %d" % (n, fact) )


main()

 2. Write the program for the following: 

a. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.

def isVowel(s):
if len(s)!=1:
print("Only String of length 1 is allowed")
return None

if s in "aeiou":
return True
else:
return False

def main():
s = input("Enter Char (Length 1) : ")

isV = isVowel(s)

if isV==True:
print("%s is a vowel" % s)
elif isV==False:
print("%s is not a vowel" % s)


main()

b. Define a function that computes the length of a given list or string.

def main():
s = input("Input a String : ")

length = len(s)

print("Length of string '%s' is %d " % (s, length))


main()

c. Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For example, histogram([4, 9, 7]) should print the following: 
**** 
********* 
*******

def histogram(l):
# str multipled by any integer repeats the str that many times
for i in l:
print("*" * i)

def main():
count = int(input("Enter count of numbers : "))

# create empty list (array)
l = list()

while count>0:
n = int(input("Enter number : "))
# list.append method appends the elemnt in last of list
l.append(n)

count -= 1

print("You Entered List :")
print(l)

histogram(l)


main()

 3. Write the program for the following: 

a. A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not.

def isPangram(s):
for alphabet in "abcdefghijklmnopqrstuvwxyz":
# if any alphabet is not present in string then return False
if alphabet not in s:
return False

# if loop completes then return True
return True


def main():
s = input("Enter a string to check pangram : ")

if isPangram(s):
print("String '%s' is Pangram" % s)
else:
print("String '%s' is not Pangram" % s)


main()

b. Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5

def main():
count = int(input("Enter Number of elements : "))

# create empty list a
a = list()

#taking all elements from user
while count > 0:
elem = int(input("Enter Number : "))
a.append(elem)
count -= 1

#iterate over list 'a' using for loop
for i in a:
if i < 5:
print(i)


main()

 4. Write the program for the following: 

a. Write a program that takes two lists and returns True if they have at least one common member.

def input_list(count):
a = list()
while count != 0:
elem = int(input("Enter Number : "))
a.append(elem)
count -= 1

return a

def check(list1,  list2):
#iterate over list1 and checking elements in list2
for i in list1:
if i in list2:
return True
return False

def main():
count1 = int(input("Enter Count for list 1: "))
list1 = input_list(count1)

count2 = int(input("Enter Count for list 2: "))
list2 = input_list(count2)

if check(list1, list2):
print("Both List have at least 1 common element")
else:
print("List dont have any common element")

main()

b. Write a Python program to print a specified list after removing the 0th, 2nd, 4th and 5th elements.

def input_list(count):

a = list()
while count != 0:
elem = int(input("Enter Number : "))
a.append(elem)
count -= 1

return a

def main():
count = int(input("Enter Count for list : "))

if count<6:
print("Enter Count greater than or equal to 6")
else:
l = input_list(count)
print("inputed List : ")
print(l)

del l[0]
# after removing 0th element, index of 2nd element will be 1
del l[1]

# after removing 0th, 1st element, index of 4th element will be 2
del l[2]
# after removing 0th, 1st, 4th element, index of 5th element will be 2
del l[2]

print("After removing 0th, 2nd, 4th and 5th Element")
print(l)

main()

c. Write a Python program to clone or copy a list.

def input_list(count):
#function to take list from user as input 
a = list()
while count != 0:
elem = int(input("Enter Number : "))
a.append(elem)
count -= 1

return a

def copy(l):
#new empty list
n = list()

#iterate over list and append elements in new list
for i in l:
n.append(i)
return n

def main():
count = int(input("Enter Count for list : "))
l = input_list(count)

new = copy(l)

print("Old List : ")
print(l)

print ("New list : ")
print(new)

main()

 5. Write the program for the following: 

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

def main():
# sample dictionary
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 0:-10}

# as dictionary doesn't preserve order of elements,
# hence convert dictionary into list of tuples

data = d.items()

#sorting data on the basis of value
data_ascending = sorted(data, key=lambda x: x[1])

#for sorting in descending order, add param reverse=True in sorted function
data_descending = sorted(data, key=lambda x: x[1], reverse=True)
print("Sorted Data (Ascending) : ")
print(data_ascending)
print("Sorted Data (Descending) : ")
print(data_descending)

main()

b. Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

def main():
#initialize sample dictionaries
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50, 6:60}

#new empty dictionary
dic = {}

#.update() method merges the dictionary into one
dic.update(dic1)
dic.update(dic2)
dic.update(dic3)

print("New Merged Dictionary : ")
print(dic)

main()

c. Write a Python program to sum all the items in a dictionary. 

def main():
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

#sum initialy 0
s = 0
#iterating over dictionary to find sum of values 
for key, value in d.items():
s = s + value

print("Sum of Values of Dictionary is : %d" % s)

main()

 6. Write the program for the following: 

a. Write a Python program to read an entire text file. 

def main():
#opening file in read mode
f = open("sample_text.txt", "r")

#f.read() method reads the complete text file
file_content = f.read()

print(file_content)

#close the file
f.close()


main()

b. Write a Python program to append text to a file and display the text. 

def main():
#opening file in append mode
f = open("sample_text.txt", "a")
f.write("Some more text")
f.close()

#opening file in read mode
f = open("sample_text.txt", "r")
file_content = f.read()
f.close()

print(file_content)


main()

c. Write a Python program to read last n lines of a file. 

def main():
#opening file in read mode
f = open("sample_text.txt", "r")
file_content_lines = f.readlines()

#assume last 4 lines to be read
n = 4

#starts from last line, go till n lines, in reverse order
last_n_lines = file_content_lines[-1:-n-1:-1]

print(last_n_lines)

f.close()


main()

 7. Write the program for the following: 

a. Design a class that store the information of student and display the same.

class Student():
def __init__(self,name):
self.name = name
a = Student("Sam")

print a.name

b. Implement the concept of inheritance using python.

class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]

    def inputSides(self):
        self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

    def dispSides(self):
        for i in range(self.n):

            print("Side",i+1,"is",self.sides[i])