You are on page 1of 17

PYTHON BASICS

LAB ASSIGNMENT

Admin Office House of G-TEC, Calicut-02., India. | Corp. Office Peace Centre, Singapore – 228149
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

PROGRAM NO:1

AIM: Find the Simple Interest by accepting principal amount, number of years and rate of
interest. Print the formatted output.
Program:
p=int(input("Enter the principle amount:\n"))
n=int(input("Enter number of years:\n"))
r=int(input("Enter the interest rate:\n"))
print("Principle amount:",p)
print("Number of years:",n)
print("Interest rate: ",r)
i=int((p*n*r)/100)
print("Simple interest is ",i)

PROGRAM NO:2

AIM: Accept a string ‘Open Source Lab’ from the keyboard and perform the following
operations

a) Length of the string


b) Take substring ’source’ in the string
c) Repeat the string 3 times
d) Print the characters of a string in the vertical and horizontal fashion
e) Character in the 4th position
f) Extract 4 characters starting at index 6
g) Print all the characters except the last two
h) Append another string ‘Programs’ to the existing string
i) Change the letter ’e’ to ‘&’
j) Split the string using the letter ’o’
k) Join the string using ‘#’ symbol
l) Count the no of spaces, alphabets, digits
m) Justified the string (left and right)
n) Change the case of the string

Page 1 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

Program:
str=input("Enter a string 'Open Source Lab': ")
#1 Length of the string
l=len(str)
print("\nLength of the string is: ",l)
#2 Take substring source in the string
list1=str[5:11]
print("\nSubstring is: ",list1)
#3 Repeat the string 3 times
s=str*3
print("\nRepeat string in 3 times:",s)
#4 Print the characters of a string in the vertical and horizontal fashion
print("Vertical:")
for i in str:
print(i)
print("\nHorizontal:")
print(" ".join(str))
#5 Character in the 4th position
print("\nCharacter in the 4th position:",str[3])
#6 Extract 4 characters starting at index 6
print("\n4 characters starting at index 6:",str[6:10])
#7 Print all the characters except the last two
print("\nAll the characters except the last two:",str[0:-2])
#8 Append another string Programs to the existing string
print("\nAppend another string Programs to the existing string is:",str+" Programs")
#9 Change the letter "e" to "&"
print("After Change the letter 'e' to '&' :",str.replace("e","&"))
#10 Split the string using the letter "o"
print("After Split the string using the letter 'o' :",str.split('o'))
#11 Join the string using "#" symbol
print("After Join operation:",'#'.join(str))

Page 2 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

#12 Count the no of spaces, alphabets, digits


digit=0
letter=0
space=0
other=0
for i in str:
if i.isalpha():
letter=letter+1
elif i.isdigit():
digit=digit+1
elif i.isspace():
space=space+1
else:
other=other+1
print("Number of digits:",digit,"\n Number of alphabets:",letter,"\n Number of
spaces:",space)
#13 Justified the string (left and right)
print("Left Justified:")
j1=str.ljust(20)
print(j1)
print("Right Justified:")
j2=str.rjust(50)
print(j2)
#14 Change the case of the string
print("Upper case:",str.upper())
print("Lower case:",str.lower()

PROGRAM NO:3

AIM: Accept two numbers and perform basic arithmetic operations (+, -, *, integer div, float
div, exponent).

Page 3 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

Program:
num1=float(input("enter first number:"))
num2=float(input("enter second number:"))
print("sum of %d and %d is %d" %(num1,num2,num1+num2))
print("difference of %d and %d is %d" %(num1,num2,num1-num2))
print("product of %d and %d is %d" %(num1,num2,num1*num2))
print("integer division of %d and %d is %d" %(num1,num2,num1/num2))
print("float division of %d and %d is %f" %(num1,num2,num1/num2))
print("exponent of %d and %d is %d" %(num1,num2,num1**num2))

PROGRAM NO:4

AIM: Create a list 'Fruits' containing elements 'apple, 30, orange, 40' and perform the following
operations
a) Add the items 'grape, apple, 50’ to the list.
b) Find the lowest index in list that ''apple’ appears.
c) Find the total number of occurrences of item 'apple' in the list.
d) Remove the last item added into the list.
e) Remove ‘30’ from the list.
f) Sort the list in ascending and descending order.
g) Using append and extend functions, create copies of the list.
h) Give both the index and values of the above list in a loop.
i) Print the alternate elements of the list starting from the second element.
Program:
fruits=['apple',30,'orange',40]
print("Fruit list is ",fruits)
# Add the items grape, apple, 50 to the list.
f=['grape','apple', 50]
fruits.extend(f)
print("New fruits: ",fruits)
# Find the lowest index in list that apple appears.
print("Lowest index of apple: ",fruits.index('apple'))
# Find the total number of occurrences of item apple in the list.
print("Total number of occurrences of item apple: ",fruits.count('apple'))
#Remove the last item added into the list.

Page 4 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

fruits.pop()
print("List after removing the last item is: ",fruits)
# Remove 30 from the list.
fruits.remove(30)
print("List after removing 30 is: ",fruits)
# Sort the list in ascending and descending order.
fruits2=[str(x) for x in fruits]
fruits2.sort()
print("List in ascending order is: ", fruits2)
fruits2.sort(reverse=True)
print("List in descending order is: ",fruits2)
# Using append and extend functions, create copies of the list.
f1=[]
f1.append('apple')
f1.append(30)
f1.append('orange')
f1.append(40)
print("Copy of fruits list using append function is: ",f1)
f1=[]
f2=['apple',30,'orange',40]
f1.extend(f2)
print("Copy of fruits list using extend function is: ",f2)
# Give both the index and values of the above list in a loop.
fruits=['apple',30,'orange',40]
print("Fruits= ",fruits)
l=len(fruits)
for i in range (l):
print("Index= ",i,)
print("Value= ",fruits[i])
# Print the alternate elements of the list starting from the second element.
f3=['apple',30,'orange',40]
print("Alternate elements of the list fruits is: ",f3[1::2])

Page 5 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

PROGRAM NO:5

AIM: Create a tuple from the given sequence of elements perl, c, cpp, java, php, python.
a) Display only the elements cpp, java, php.
b) Find the number of elements in the tuple.
c) Find the largest and smallest element.
d) Repeat the tuple elements two times.
e) Compare the tuple with another tuple (cpp, dc).
f) Add (cpp, dc) as a nested elemet.
g) Delete the tuple elements.
Program:
tuple1=('perl', 'c', 'cpp', 'java', 'php', 'python')
print('tuple1')
# Display only the elements cpp, java, php.
print('Elements are : ', tuple1[2:5])
# Find the number of elements in the tuple.
print('Length of tuple',len(tuple1))
# Find the largest and smallest element.
print('Largest ampong tuple; ',max(tuple1))
print('smallest among tuple: ',min(tuple1))
# Repeat the tuple elements two times.
print('Repeatation: ',tuple1 * 2)
# Compare the tuple with another tuple (cpp, dc).
tuple2=('cpp','dc')
x= (tuple1>tuple2)-(tuple1<tuple2)
if x == 0:
print('tuples are same')
else :
print('tuples are not same')
# Add (cpp, dc) as a nested elemet.
tuple1=(tuple1,('cpp','dc'))
print('tuple1')
# Delete the tuple elements.
del tuple1
print("tuple deleted")

Page 6 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

PROGRAM NO:6

AIM: Create two sets s1 and s2 consisting of elements s1=1, 44, 53, 21 and s2=2, 44, 54, 21,
36, 89 and perform all the set operations.
i. Intersection
ii. Union
iii. Difference
iv. Symmetric Difference
Program:
s1=set([1,44,53,21])
s2=set([2,44,54,21,36,89])
print('Given sets are as follows ')
print('S1: ',s1)
print('S2: ',s2)
#Intersection
print('Intersection of S1 and S2 is ', s1 & s2)
#Union
print('Union of S1 and S2 is ', s1 | s2)
#Difference
print('Difference of S1 and S2 is ', s1 - s2)
#Symmetric Difference
print('Symmetric of S1 and S2 is ', s1 ^ s2)

PROGRAM NO: 7
AIM: Create a hash table /associative array – Dictionary that contains at least 5 words and
word meanings.
a) Display all the words.
b) Display all word meanings.
c) Display all key value pairs in a neat format with the help of the built in function
d) Use all dictionary built in functions.
e) Update the dictionary by adding the word ‘compute-calculate’
f) Delete the item with key value “compute”
g) Delete all the items of the dictionary with the help of a built in function.
h) Delete the entire dictionary
Page 7 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

Program:
animal={"A":"Ant","B":"Bee","C":"Cat","D":"Dog","E":"Eagle"}
# Display all the words.
print("The words are: ",animal.keys())
# Display all word meanings.
print("The meanings are: ",animal.values())
print("A :",animal["A"])
print("B :",animal["B"])
print("C :",animal["C"])
print("D :",animal["D"])
print("E :",animal["E"])
# Display all key value pairs in a neat format with the help of the built in function.
print("Using built-in function key-value pairs: ")
print(animal.items())
# Use all dictionary built in functions.
animal1={"A":"Ant","F":"Fox"}
print("Using built-in function ")
print("The length is: ",len(animal))
print("Printable string representation of a dictionary: ",str(animal))
print("The type is: ", type(animal))
print("Copy of dictionary: ",animal.copy())
print("Clearing dictionary elements: ",animal1.clear())
print("Creates new dictionary with new values")
seq=(1,2,3,4,5)
print(animal.fromkeys(seq,"Ant"))
print("Value of C is: ",animal.get("Cat"))
print("Check whether D is present or not: ")
if "D" in animal:
print("yes the value is",animal.get('D'))
else:
print("not present")

Page 8 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

print("Dictionary items: ",animal.items())


print("List of keys: ",animal.keys())
print("Adding the new key: ",animal.setdefault("F","Fox"))
animal2={"G":"Goat"}
print("After updating ")
animal.update(animal2)
print(animal)
#Update the dictionary by adding the word "compute-calculate"
new={"compute":"calculate"}
print("after adding compute ",animal.update(new))
print(animal)
# Delete the item with key value "compute"
print("After deleting compute: ",animal.pop("compute"))
#h)Delete all the items of the dictionary with the help of a built in function.
print("Clearing all elements in dictionary: ",animal.clear())
# Delete the entire dictionary
print("Deleting dictionary ")
del animal

PROGRAM NO: 8

AIM: Programs using Functions


a) To find the maximum number from a list.
Program:
list1=[]
n=int(input("enter the limit:"))
for i in range(1, n+1):
number1=int(input("enter numbers: "))
list1.append(number1)
print("maximum number from the list is ", max(list1))

b) To find the sum of digits of a number.


Program:
Number = int(input("Please Enter any Number: "))
Page 9 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

Sum = 0
while(Number > 0):
Reminder = Number % 10
Sum = Sum + Reminder
Number = Number //10
print("\n Sum of the digits of Given Number = %d" %Sum)
c) To create multiplication tables of more than one number.
Program:
def multable(num):
print("Multiplication table of %d" % (num))
for i in range(1,11):
print(i ," * ", num ," = ",(i*num))
x=int(input("enter number of tables: "))
i=1
while (i<=x):
n=int(input("Enter a number: "))
multable(n)
i=i+1

d) To check whether the given number is Armstrong or not (max 5-digit no).
Program:
def armstrong(n):
s=0
while n>0:
r=int(n%10)
s=int(s+(r*r*r))
n=int(n/10)
return s
n=int(input("enter a number:"))
t=n
s=armstrong(n)
if t==s:

Page 10 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

print("%d is armstrong" %(t))


else:
print("%d is not armstrong" %(t))

e) To find the Factorial of a number.


Program:
def fact(n):
f=1
while n>0:
f=f*n
n=n-1
return f
n=int(input("Enter a number : "))
f=fact(n)
print("factorial of %d is : %d" %(n,f))

f) To find the Fibonacci sequence up to a limit.


Program:
def fibo(l):
a=-1
b=1
while(l>0):
c=int(a+b)
print(c)
a=b
b=c
l=l-1
return
l=int(input("enter the limit : "))
print("fibonacci series is : ")
fibo(l)

Page 11 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

g) To check whether the given number is palindrome or not.


Program:
def palin(n):
s=0
while n>0:
r=int(n%10)
s=int(s*10+r)
n=int(n/10)
return s
n=int(input("enter a number:"))
t=n
s=palin(n)
if t==s:
print("%d is palindrome" %(t))
else:
print("%d is not palindrome" %(t))

h) To find the sum of all prime numbers up to 100(use ‘while’ keyword)


Program:
def prime(n):
i=2
s=0
while i<n:
flag=0
j=1
while j<=i:
if i % j==0:
flag=flag+1
j=j+1
if flag==2:
s=s+i
i=i+1
return s
s=prime(100)
print("sum of all prime numbers up to 100 is %d " %(s))

Page 12 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

i) Accept maximum and minimum limit as arguments and create a list of numbers
containing multiples of 3 and not ending with 5 or 6.
Program:
def multi(mn,mx):
l=[]
for i in range(mn,mx+1):
if(i%3==0):
rem=int(i%10)
if(rem!=5 and rem!=6):
l.append(i)
print(" the list is \n",l)
a=int(input("enter minimum limit : "))
b=int(input("enter maximum limit : "))
multi(a,b)

j) To implement binary search


Program:
def binary(n,ls):
l=len(ls)
i=0
j=0
t=0
for i in range(0,n-1):
for j in range(0,n-i-1):
if(ls[j]>ls[j+1]):
t=ls[j+1]
ls[j+1]=ls[j]
ls[j]=t
print "Sorted list is : ",ls
num=input("Enter the element to be searched: ")
beg=0

Page 13 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

end=n-1
while beg<=end:
mid=(beg+end)/2
if num<ls[mid]:
beg=mid-1
elif num>ls[mid]:
end=mid+1
else:
print "%d is present in the sorted list" %(num)
break
if(num<ls[0] or num>ls[n-1]):
print "The searched element is not present in the list "
return
ls=list()
n=input("Enter the limit of list: ")
for i in range(1,n+1):
a=input("Enter the element: ")
ls.append(a)
binary(n,ls)
PROGRAM NO: 9

AIM: To input a line of text. Write functions which takes text as argument and
a) Calculate how many words starts with letter ‘t’.
b) Calculate how many words ends with the letter ‘s’.
c) Calculate how many 6 letters words are appearing.
d) Calculates how many words are there in the given text.
e) Replace the word “student” of “hello student, welcome to ucc, student give your
details” with the name accepted from the user.
f) Display the number of vowels in the entered string.
PROGRAM NO:10

AIM: To handle ‘division by zero’ exception.


Program:
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))

Page 14 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

try:
res=a/b
print("Result : %d/%d = %d" %(a,b,res))
except ZeroDivisionError:
print("Error : Division by zero")
PROGRAM NO:11

AIM: To create a user defined exception for handling the occurrence of a particular letter in an
entered string.
Program:
To convert the temperature in Celsius to Fahrenheit. If the value entered is not a number, then
raise an exception.
def temp_convert(var):
try:
var=int(var)
fnht=9.0/5.0*var+32
print("In Fahrenheit: ",fnht)
except ValueError:
print("The argument does not contain numbers ")
print("Error message: ")
clus=input("Enter the temperature in celsius: ")
temp_convert(clus)
PROGRAM NO:12

Aim: To evaluate a quadratic equation and find its roots. Catch any exceptions that can be
caught.
Program:
import math
def quadratic():
print("This program finds the real solutions to a quadratic\n")
try:
a=int(input("Enter the coefficients of a:"))
b=int(input("Enter the coefficients of b:"))
c=int(input("Enter the coefficients of c:"))

Page 15 of 16
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
PYTHON BASICS - LAB ASSIGNMENT

d=int(b**2-4*a*c)
if d==0:
x= int((-b+math.sqrt(b**2-4*a*c))/(2*a))
print("This equation has one solutions:",x)
else:
x1= int((-b+math.sqrt(b**2-4*a*c))/(2*a))
x2= int((-b-math.sqrt(b**2-4*a*c))/(2*a))
print("This equation has two solutions:",x1,"or",x2)
except ValueError:
print("\nNo real roots")
quadratic()
13. Create a class queue and implement queue operations (Creation, Insertion, Deletion, &
Display queues). Handle the exceptions, if any.

14. To define a class stack that implements stack operations. The function push can throw only
one exception i.e. FULL if stack is full and the function pop can throw only one exception i.e.
EMPTY if stack is empty. Also handle unexpected exception if any.

15. To create a file that stores the details of books in a Library. Perform different file operations
writing, reading, appending.

Page 16 of 16

You might also like