Python Programming
Python Programming
PYTHON
PROGRAMMING
LAB FILE
Submitted To:-
Dr. Ranjana Rajnish
Submitted By:-
Salil Dixit
B.Sc.(IT)
6th semester
A7304918014
1|Page
Index
S. No. Experiment Page Date
No.
01 Start the Python interpreter and type 5
help(‘print’) to get information about the
print statement.
02 If you run a 10-kilometer race in 43 minutes 6
30 seconds, calculate your average time per
mile and your average speed in miles per
hour using Python
Calculator. (Hint: there are 1.61 kilometers in
a mile).
03 Write a function to calculate the square of 7
first n natural numbers.
04 Write a function that draws a grid 8-9
05 Write a function that takes four parameters— 10
a, b, c and n—and then checks to see if
Fermat’s theorem, an + bn = cn, holds. If n is
greater than 2 and it
turns out to be true then the program should
print, “Holy smokes, Fermat was
wrong!” Otherwise the program should print,
“No, that doesn’t work.”
06 Write a function that takes a string argument 11
and returns true if it is a palindrome and False
otherwise.
07 A number, a, is a power of b if it is divisible 12
by b and a/b is a power of b. Write a function
that takes parameters a and b and returns True
if a is a power
of b.
08 Write a recursive function to calculate the 13
factorial of a given number.
2|Page
09 Write a function that takes a string as a 14
parameter. Calculate the length of a string
without using len function. Print the length
concatenated with the
string and aligned towards the extreme right
of the output screen.
10 ROT13 is a weak form of encryption that 15
involves “rotating” each letter in a word by
13 places. To rotate a letter means to shift it
through the alphabet,
wrapping around to the beginning if
necessary, so ’A’ shifted by 3 is ’D’ and ’Z’
shifted by 1 is ’A’. Write a function that takes
a string and an integer
as parameters, and then returns a new string
that contains the letters from the original
string “rotated” by the given amount. Use the
built-in functions
ord, which converts a character to a numeric
code, and chr, which converts numeric codes
to characters.
11 Write a function that takes a nested list of 16
integers and add up the elements from all
of the nested lists.
12 Write a function called middle that takes a list 17
and returns a new list that contains all but the
first and last elements. So middle ([1, 2, 3, 4])
should return
[2, 3].
13 Write a program to print the keys of the 18
dictionary and their values in an alphabetical
order.
14 Write a function that takes any number of 19
arguments and returns their sum.
15 Write a program that reads words.txt and 20
prints only the words with more than
20characters (not counting white space).
3|Page
Experiment 1
Start the Python interpreter and type help(‘print’) to get information about the print statement.
help('print')
Experiment 2
If you run a 10-kilometer race in 43 minutes 30 seconds, calculate your average time per mile
and your average speed in miles per hour using Python
Calculator. (Hint: there are 1.61 kilometers in a mile).
distKm = 10.0
distMi = (distKm * (1.0 / 1.61))
seconds = ((43.0 * 60.0) + 30.0)
hours = (43.5 / 60.0)
def timePerMile(distMi, seconds):
print (seconds / distMi, 'seconds per mile')
def avgSpeed(distMi, hours):
4|Page
print (distMi / hours, 'miles per hour')
timePerMile(distMi, seconds)
avgSpeed(distMi, hours)
Experiment 3
Write a function to calculate the square of first n natural numbers.
def squaresum(n) :
sm = 0
for i in range(1, n+1) :
sm = sm + (i * i)
return sm
n = int(input("Enter a number"))
print(squaresum(n))
5|Page
Experiment 4
Write a function that draws a grid like the following:
+ - - - -+ - - - -+
| | |
| | |
| | |
| | |
+ - - - -+ - - - -+
| | |
| | |
| | |
| | |
+ - - - -+ - - - -+
def do_Func(f, val, iter):
i=0
while i < iter:
f(val)
i=i+1
def printer(val):
print (val)
6|Page
colCell = '+ - - - - + - - - - +'
rowCell = '| | |'
do_Func(printer, colCell, 1)
do_Func(printer, rowCell, 4)
do_Func(printer, colCell, 1)
do_Func(printer, rowCell, 4)
do_Func(printer,colCell,1)
Experiment 5
7|Page
Write a function that takes four parameters—a, b, c and n—and then checks to see if Fermat’s
theorem, an + bn = cn, holds. If n is greater than 2 and it
turns out to be true then the program should print, “Holy smokes, Fermat was
wrong!” Otherwise the program should print, “No, that doesn’t work.”
def check_fermat(a, b, c, n):
if n > 2 and (a**n + b**n == c**n):
print("Holy smokes, Fermat was wrong!")
else:
print("No, that doesn’t work.")
def check_numbers():
a = int(input("Choose a number for a: "))
b = int(input("Choose a number for b: "))
c = int(input("Choose a number for c: "))
n = int(input("Choose a number for n: "))
return check_fermat(a, b, c, n)
check_numbers()
Experiment 6
Write a function that takes a string argument and returns true if it is a palindrome and False
otherwise.
def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("True")
else:
print("False")
8|Page
Experiment 7
A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function that
takes parameters a and b and returns True if a is a power
of b.
def is_power(a, b):
if a < b:
return False
if a == b:
return True
else:
return is_power(a / b, b)
a = int(input("Choose a number : "))
b = int(input("Choose a number : "))
print(is_power(a,b))
9|Page
Experiment 8
Write a recursive function to calculate the factorial of a given number.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
a = int(input("Choose a number for factorial : "))
if a == 0:
print("The factorial of 0 is 1")
if a > 0:
print("The factorial of", a, "is", recur_factorial(a))
Experiment 9
Write a function that takes a string as a parameter. Calculate the length of a string without
using len function. Print the length concatenated with the
string and aligned towards the extreme right of the output screen.
str1 = input("Enter a string: ")
10 | P a g e
counter = 0
for s in str1:
counter = counter+1
print("Length of the input string is:")
a=str(counter)
print (a.center(375), "\n")
Experiment 10
ROT13 is a weak form of encryption that involves “rotating” each letter in a word by 13 places.
To rotate a letter means to shift it through the alphabet,
wrapping around to the beginning if necessary, so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is
’A’. Write a function that takes a string and an integer
as parameters, and then returns a new string that contains the letters from the original string
“rotated” by the given amount. Use the built-in functions
ord, which converts a character to a numeric code, and chr, which converts numeric codes to
characters.
11 | P a g e
def normalize(x, low, high):
while x > high:
x -= 26
while x < low:
x += 26
return x
def rotate_word(word, amount):
new_word = ''
for letter in word:
if letter.isupper():
new_word += chr(normalize(ord(letter) + amount, 65, 90))
elif not letter.isalpha():
new_word += letter
else:
new_word += chr(normalize(ord(letter) + amount, 97, 122))
return new_word
print (rotate_word("Thas is a test. Don't try this @ home!", 13))
12 | P a g e
Experiment 11
Write a function that takes a nested list of integers and add up the elements from all of the nested
lists.
def sum1(lst):
total = 0
for element in lst:
if (type(element) == type([])):
total = total + sum1(element)
else:
total = total + element
return total
print( "Sum is:",sum1([[1,2],[3,4]]))
13 | P a g e
Experiment 12
Write a function called middle that takes a list and returns a new list that contains all but the first
and last elements. So middle ([1, 2, 3, 4]) should return
[2, 3].
def middle(lst):
new = lst[1:]
del new[-1]
return new
my_list = [1, 2, 3, 4]
print(middle(my_list))
14 | P a g e
Experiment 13
Write a program to print the keys of the dictionary and their values in an alphabetical order.
dict ={
"L1":[87, 34, 56, 12],
"L2":[23, 00, 30, 10],
"L3":[1, 6, 2, 9],
"L4":[40, 34, 21, 67]
}
print("\nBefore Sorting: ")
for x in dict.items():
print(x)
print("\nAfter Sorting: ")
for i, j in dict.items():
sorted_dict ={i:sorted(j)}
print(sorted_dict)
15 | P a g e
Experiment 14
Write a function that takes any number of arguments and returns their sum.
def sum_all(*args):
return sum(args)
print (sum_all(1, 2, 3))
print (sum_all(1, 2, 3, 4, 5))
print (sum_all(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
Experiment 15
Write a program that reads words.txt and prints only the words with more than 20characters (not
counting white space).
def test():
fin = open('words.txt')
count = 0
word = fin.readline()
x = len(word)
for i in word:
if i == ' ':
count = count + 1
y = x - count
if y >= 20:
print (word)
16 | P a g e
return word
else:
print ('words have only', y, 'char')
test()
17 | P a g e