SlideShare una empresa de Scribd logo
1 de 50
Descargar para leer sin conexión
Exercise 1 - Basics
AIM:
a) Running instructions in interactive interpreter and a python script.
Algorithm for running instructions in Interactive interpreter:
Step 1: Start
Step 2: Open terminal in Linux/Unix OS or open IDLE.
Step 3: start an interactive Python session by selecting "Python (command line)", "IDLE", or
similar program from the task bar / app menu
Step 4: The >>> is Python's way of telling you that you are in interactive mode.
Step 5: In interactive mode what you type is immediately run. Try typing 1+1 in. Python will
respond with 2. Interactive mode allows you to test out and see what Python will do. If you
ever feel the need to play with new Python statements, go into interactive mode and try them
out.
Step 6: stop
[root@localhost ~]# python3
Python 3.5.3 (default, May 11 2017, 09:10:41)
[GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Welcome to the world of Python!!!")
Welcome to the world of Python!!!
>>> 10+7
17
>>> 50+40-35
55
>>> 12*10
120
>>> 96/12
8.0
>>> (-30*4)+500
380
>>> 5*3.0
15.0
>>> 78//5
15
>>> 78%5
3
>>> 5**3
125
>>> "Hello"
'Hello'
>>> 'Hello'
'Hello'
>>> '''Hello'''
'Hello'
>>> print("what's your name")
what's your name
>>> print("The boy replies, "My name is John."")
The boy replies, "My name is John."
>>> print("Today is 15th August. n India became 
independent on this day")
Today is 15th August.
India became independent on this day
>>> print("I have studied many programming languages. 
... But my best favorite langugae is Python.")
I have studied many programming languages. But my best favorite langugae is Python.
>>> print(R"What's your name")
What's your name
>>> print('Beautiful Weather' '.....' 'Seems it would rain')
Beautiful Weather.....Seems it would rain
>>> a=10
>>> b=20
>>> print(a+b)
30
>>> print(a,b)
10 20
>>> a>b
False
>>> a<b
True
>>> a==b
False
>>> a!=b
True
>>> type(a)
<class 'int'>
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help(int)
Help on class int in module builtins:
class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| self != 0
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
>>>
Press ctrl+d to exit from pyhon interpreter
Algorithm for running Python Srcipt:
Step 1: Start
Step 2: Open an editor
Step 3: Write the instructions
Step 4: Save it as a file with the filename having the extension .py
Step 5: Run the interpreter with command python program_name.py or uses IDLE to run the
programs.
Step 6: Stop
AIM:
b) Write a program to purposefully raise indentation error and correct it.
Whitespace at the beginning of the line is called indentation. These whitespaces or
the indentation are very important in python. In a python program, the leading whitespace
including spaces and tabs at the beginning of the logical line determines the indentation level
of that logical line. In python, indentation is used to associate the group statements.
Program to exhibit indentation error
[root@localhost ~]# vi try.py
Age=21
Print(“You can vote”)
[root@localhost ~]# python3 try.py
File "try.py", line 2
print("You can vote")
^
IndentationError: unexpected indent
The level of indentation groups statements to form a block of statements. This means
that statements in a block must have the same indentation level. Python very strictly checks
the indentation level and gives an error if indentation is not correct.
Like other programming languages python does not use curly braces to indicate
blocks of code for class, function definitions or flow of control statements. It uses only
indentation to form a block. All statements inside a block should be at the same indentation
level.
The above example is corrected as below to get output
[root@localhost ~]# vi try.py
Age=21
Print(“You can vote”)
[root@localhost ~]# python3 try.py
You can vote
Exercise 2 - Operations
AIM:
a) Write a program to compute distance between two points taking input from the user
(Pythagorean Theorem).
Algorithm:
Step 1: Start
Step 2: import the math module.
Step 3: Read x1,y1,x2,y2
Step 4: compute distance between two points using Pythagorean Theorem.
Step 5: print distance
Step 6: stop
Program:
import math
x1=int(input("Enter x1 value:"))
y1=int(input("Enter y1 value:"))
x2=int(input("Enter x2 value:"))
y2=int(input("Enter y2 value:"))
distance=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance=",distance)
Output:
[root@localhost python] python3 2a.py
Enter x1 value:3
Enter y1 value:4
Enter x2 value:5
Enter y2 value:6
Distance= 2.8284271247461903
AIM:
b) Write a program add.py that takes 2 numbers as command line arguments and
prints its sum.
Algorithm:
Step 1: Start
Step 2: import the sys module.
Step 3: read command line arguments to variables a,b
Step 4: compute sum = int(a) + int(b)
Step 5: print sum
Step 6: stop
Program:
import sys
a=sys.argv[1]
b=sys.argv[2]
sum=int(a)+int(b)
print("Sum=",sum)
print("Length of argv=",len(sys.argv))
Output:
[root@localhost python]# python3 2b.py 45 67
Sum= 112
Length of argv= 3
Exercise - 3 Control Flow
AIM:
a) Write a Program for checking whether the given number is a even number or not.
Algorithm:
Step 1: Start
Step 2: read n value.
Step 3: if n is divisible by 2 goto step 4 else goto step 5
Step 4: print n is even
Step 5: print n is odd
Step 6: stop
Program:
n=int(input("enter any one number:"))
if(n%2==0):
print(n,"is even")
else:
print(n,"is odd")
Output:
[root@localhost python] vi 3a.py
[root@localhost python] python3 3a.py
enter any one number:64
64 is even
[root@localhost python] python3 3a.py
enter any one number:66
66 is even
[root@localhost python] python3 3a.py
enter any one number:45
45 is odd
AIM:
b) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, - - - - -- -- ---1/10
AIM:
b) Write a program add.py that takes 2 numbers as command line arguments and
prints its sum.
Algorithm:
Step 1: Start
Step 2: import the sys module.
Step 3: read command line arguments to variables a,b
Step 4: compute sum = int(a) + int(b)
Step 5: print sum
Step 6: stop
Program:
import sys
a=sys.argv[1]
b=sys.argv[2]
sum=int(a)+int(b)
print("Sum=",sum)
print("Length of argv=",len(sys.argv))
Output:
[root@localhost python]# python3 2b.py 45 67
Sum= 112
Length of argv= 3
Exercise - 3 Control Flow
AIM:
a) Write a Program for checking whether the given number is a even number or not.
Algorithm:
Step 1: Start
Step 2: read n value.
Step 3: if n is divisible by 2 goto step 4 else goto step 5
Step 4: print n is even
Step 5: print n is odd
Step 6: stop
Program:
n=int(input("enter any one number:"))
if(n%2==0):
print(n,"is even")
else:
print(n,"is odd")
Output:
[root@localhost python] vi 3a.py
[root@localhost python] python3 3a.py
enter any one number:64
64 is even
[root@localhost python] python3 3a.py
enter any one number:66
66 is even
[root@localhost python] python3 3a.py
enter any one number:45
45 is odd
AIM:
b) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, - - - - -- -- ---1/10
Algorithm:
Step 1: Start
Step 2: read a string
Step 3: split the string using split() method and store it in variable list1
Step 4: print list1
Step 5: join the string using join() method and store it in sj
Step 6: print sj
Step 7: stop
Program:
str=input("Enter a string:")
print("string after spliting:")
list1=str.split()
print(list1)
print("string after join:")
sj=' '.join(l)
print(sj)
Output:
[root@localhost python]# python3 5b.py
Enter a string::python programming lab in first sem first year
string after spliting:
[':python', 'programming', 'lab', 'in', 'first', 'sem', 'first', 'year']
string after join:
:python programming lab in first sem first year
Exercise - 6 DS - Continued
AIM:
a) Write a program combine lists that combines these lists into a dictionary.
Algorithm:
Step 1: Start
Step 2: initialize list1 and list2
Step 3: add one list elements to another list by using concatenation (+) operator
Step 4: combine two lists using zip() method and store it in variable rev
Step 5: convert rev into dictionary by using dict() method and print it
Step 6: stop
Program:
list1=[1,2,3]
list2=['one','two','three']
l3=list1+list2
print('combination of two lists:',l3)
rev=zip(list1,list2)
print(dict(rev))
Output:
[root@localhost python]# vi 6a.py
[root@localhost python]# python3 6a.py
combination of two lists: [1, 2, 3, 'one', 'two', 'three']
{1: 'one', 2: 'two', 3: 'three'}
AIM:
b) Write a program to count frequency of characters in a given file. Can you use
character frequency to tell whether the given file is a Python program file, C program
file or a text file?
Algorithm:
Step 1: Start
Step 2: read filename
Step 3: open file in read mode
Step 4: find the index position of ‘.’ Using index() method
Step 5: get the extension of file using [:] operator
Step 6: if the file extension is ‘py’ then go to step 8 otherwise go to step 9
Step 7: Print ‘The given file is a python file’
Step 8: if the file extension is ‘c’ then go to step 10 otherwise go to step 11
Step 9: print ‘The given file is a C file’
Step 10: if the file extension is ‘txt’ then go to step 12 otherwise go to step 13
Step 11: print ‘The given file is a text file’
Step 12: read file contents by using read() method and store in variable str
Step 13: close the file
Step 14: initialize dict = {}
Step 15: repeat the step 16 for char in str
Step 16: add dict[char] = str.count(char)
Step 17: print dict
Step 18: stop
Program:
fname=input("enter file name:")
f=open(fname,'r')
index=fname.index('.')
ext=fname[index+1:]
if(ext=='py'):
print('The given file is a python file')
elif(ext=='c'):
print('The given file is a C file')
elif(ext=='txt'):
print('The given file is a text file')
str=f.read()
print(str)
f.close()
dict={}
for ch in s:
dict[ch]=s.count(ch)
print(dict)
Output:
[root@localhost python]# python3 6b.py
enter file name:6a.py
The given file is a python file
l1=[1,2,3]
l2=['one','two','three']
l3=l1+l2
print('combination of two lists:',l3)
rev=zip(l1,l2)
print(dict(rev))
{' ': 3, 'i': 7, 'l': 9, ':': 1, 'w': 2, 'c': 2, 'z': 1, 's': 2, 'd': 1, 'o': 6, 'a': 1, '+': 1, 'h': 1, 'e': 5, 't': 8, 'b': 1,
'3': 3, ')': 4, 'n': 5, '2': 4, 'v': 2, ']': 2, 'f': 1, "'": 8, '[': 2, '(': 4, 'p': 3, 'n': 6, '=': 4, 'r': 5, 'm': 1, '1':
4, ',': 6}
[root@localhost python]# vi sample.txt
[root@localhost python]# python3 6b.py
enter file name:sample.txt
The given file is a text file
sdfasdjkfkasdf
sdafasdfsd
sdgvsdfgsd
fgsdgsdgsd
sdfsd
fsdgfsdfg
sdgvfgvsdfgsd
gvsdfgsdf
f
sdfsd
fsdfv
{'k': 2, 's': 24, 'n': 11, 'j': 1, 'v': 5, 'd': 24, 'f': 19, 'g': 12, 'a': 4}
[root@localhost python]# python3 6b.py
enter file name:sample.c
The given file is a C file
dafdas
adf
dfasf
adfsd
fds
{'s': 4, 'a': 5, 'f': 6, 'd': 7, 'n': 5}
Exercise - 7 Files
AIM:
a) Write a program to print each line of a file in reverse order.
Algorithm:
Step 1: Start
Step 2: read filename
Step 3: open file in read mode
Step 4: read lines in a file by using readlines() method and store them in str
Step 5: initialize lines = []
Step 6: repeat steps 7, 8 and 9 for each line in str
Step 7: replace ‘n’ with ‘’ in each line
Step 8: reverse the line
Step 9: append the reversed line to lines
Step 10: close the file
Step 11: repeat step 12 for each line in lines
Step 12: print line
Step 13: stop
Program:
f=open("sample.txt","r")
str=f.readlines()
lines=[]
for line in str:
line=line.replace('n','')
reverse=line[::-1]
lines.append(reverse)
f.close()
for line in lines:
print(line)
Output:
[root@localhost python]# vi 7a.py
[root@localhost python]# python3 7a.py
fdsakfkjdsafds
dsfdsafads
dsgfdsvgds
dsgdsgdsgf
dsfds
gfdsfgdsf
AIM:
b) Write a program to compute the number of characters, words and lines in a file.
Algorithm:
Step 1: Start
Step 2: open file in read mode
Step 3: read contents of file using read() method into variable str
Step 4: close the file
Step 5: print str
Step 6: compute lines = str.count('n')
Step 7: compute words = str.count(' ')+lines
Step 8: compute chars = len(str)-words
Step 9: print lines, words, chars
Step 10: stop
Program:
f=open("sample.txt",'r')
str=f.read()
f.close()
print(str)
words=0;chars=0;lines=0
lines=str.count('n')
words=str.count(' ')+lines
chars=len(str)-words
print("number of lines:",lines)
print("number of words:",words)
print("number of characters:",chars)
Output:
[root@localhost python]# vi 7b.py
[root@localhost python]# python3 7b.py
sdfasdjkfkasdf
sdafasdfsd
sdgvsdfgsd
fgsdgsdgsd
sdfsd
fsdgfsdfg
sdgvfgvsdfgsd
gvsdfgsdf
f
sdfsd
fsdfv
number of lines: 11
number of lines: 11
number of words: 11
number of characters: 91
Exercise - 8 Functions
AIM:
a) Write a function ball collides that takes two balls as parameters and computes if they
are colliding. Your function should return a Boolean representing whether or not the
balls are colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius
If (distance between two balls centers) <= (sum of their radius) then (they are colliding).
Algorithm:
Step 1: Start
Step 2: read t1, t2 as tuple data structure
Step 3: call function ball_collide by passing t1 and t2
Step 4: compute the distance between two balls in calling function
Step 5: compare distance with sum of radius
Step 6: Return the value from the calling function to the called function
Step 7: print the return value in called function
Step 8: stop
Program:
import math
def ball_collide(b1,b2):
dx=int(b2[0])-int(b1[0])
dy=int(b2[1])-int(b1[1])
dist=math.sqrt(dx**2+dy**2)
if dist<=(int(b1[2])+int(b2[2])):
return True
else:
return False
t1=tuple(input("Enter the x,y points and radius of ball 1:").split(','))
t2=tuple(input("Enter the x,y points and radius of ball 2:").split(','))
print(ball_collide(t1,t2))
Output:
[root@localhost python]# vi 8a.py
[root@localhost python]# python3 8a.py
Enter the x,y points and radius of ball 1:2,3,4
Enter the x,y points and radius of ball 2:5,6,7
True
AIM:
b) Find mean, median, mode for the given set of numbers in a list.
Algorithm:
Step 1: Start
Step 2: read the size of the list
Step 3: read the elements of the list
Step 4: print list elements
Step 5: call the function mean with the list elements passed to it.
Step 6: In the calling function compute the mean and return it.
Step 7: print mean
Step 8: call the function median with the list elements passed to it.
Step 9: In the calling function compute median and return it.
Step 10: print median
Step 11: call the function mode with the list elements passed to it.
Step 12: In the calling function compute the mode and return it.
Step 13: print mode
Step 14: stop
Program:
def mean(l):
return(sum(l)/len(l))
def median(l):
l.sort()
i=len(l)-1
if(len(l)%2==0):
return(l[i//2]+l[(i+1)//2])
else:
return(l[i//2])
def mode(l):
m=max([l.count(a)for a in l])
l=[x for x in l if l.count(x)==m]
l=list(set(l))
if m>1 and len(l)==1:
return(l[0])
else:
return None
l1=[]
n=int(input("Enter number of elements to be inserted in a list:"))
for i in range(n):
print("Enter element",i+1,":")
num=int(input())
l1.append(num)
print(l1)
print("Mean of list of numbers:",mean(l1))
print("Median of list of numbers:",median(l1))
print("Mode of list of numbers:",mode(l1))
Output:
[root@localhost ~]# vi 8b.py
[root@localhost ~]# python3 8b.py
Enter number of elements to be inserted in a list:6
Enter element 1 :
1
Enter element 2 :
2
Enter element 3 :
3
Enter element 4 :
4
Enter element 5 :
5
Enter element 6 :
6
[1, 2, 3, 4, 5, 6]
Mean of list of numbers: 3.5
Median of list of numbers: 7
Mode of list of numbers: None
Exercise - 9 Functions - Continued
AIM:
a) Write a function nearly equal to test whether two strings are nearly equal. Two
strings a and b are nearly equal when a can be generated by a single mutation on b.
Algorithm:
Step 1: Start
Step 2: call the function nearly_equal with two strings
Step 3: call the function mutate with word1 from the calling function
Step 4: generate list of strings by adding new character to word1 and store them as a list in
variable inserting
Step 5: generate list of strings by deleting each character from word1 and store them as a list
in the variable deleting.
Step 6: generate list of strings by replacing each character in word1 and store them as a list in
the variable replacing.
Step 7: generate list of strings by swapping characters in word1 and store them as a list in the
variable swapping
Step 8: concatenate all the four lists and store them in all
Step 9: return the list all to the called function
Step 10: Return the value from the calling function to the called function by checking word2
is in all list or not
Step 11: Print the value.
Step 12: stop
Program:
import string
def mutate(word):
inserting=[word[:i]+x+word[i:] for i in range(len(word)) for x in
list(string.ascii_lowercase)]
deleting=[word[:i]+word[i+1:] for i in range(len(word))]
replacing=[word[:i]+x+word[i+1:] for i in range(len(word)) for x in
list(string.ascii_lowercase)]
swapping=[word[:i]+word[i+1]+word[i]+word[i+2:] for i in range(len(word)-1)]
all=inserting+deleting+replacing+swapping
return all
def nearly_equal(word1,word2):
return True if word2 in mutate(word1) else False
print(nearly_equal('python','perl'))
print(nearly_equal('perl','pearl'))
print(nearly_equal('python','jython'))
print(nearly_equal('man','woman'))
Output:
[root@localhost ~]# vi 9a.py
[root@localhost ~]# python3 9a.py
False
True
True
False
AIM:
b) Write a function dups to find all duplicates in the list.
Algorithm:
Step 1: Start
Step 2: read the size of the list
Step 3: read the elements of the list
Step 4: print list elements
Step 5: call the function dups with the list elements passed to it.
Step 6: In the calling function find the duplicate elements as return them as a list.
Step 7: print duplicate elements
Step 8: stop.
Program:
def dups(l):
d=[]
for item in l:
if(l.count(item)>1):
if item not in d:
d.append(item)
return(d)
l1=[]
n=int(input("Enter the number of elements to be inserted in the list:"))
for i in range(n):
print("enter the element ",i+1,":")
num=int(input())
l1.append(num)
print("original list:",l1)
print("duplicate elements of a list:",dups(l1))
Output:
[root@localhost ~]# vi 9b.c
[root@localhost ~]# python3 9b.c
Enter the number of elements to be inserted in the list:6
enter the element 1 :
1
enter the element 2 :
2
enter the element 3 :
3
enter the element 4 :
4
enter the element 5 :
5
enter the element 6 :
6
original list: [1, 2, 3, 4, 5, 6]
duplicate elements of a list: []
[root@localhost ~]# python3 9b.c
Enter the number of elements to be inserted in the list:6
enter the element 1 :
1
enter the element 2 :
3
enter the element 3 :
2
enter the element 4 :
5
enter the element 5 :
3
enter the element 6 :
3
original list: [1, 3, 2, 5, 3, 3]
duplicate elements of a list: [3]
AIM:
c) Write a function unique to find all the unique elements of a list.
Algorithm:
Step 1: Start
Step 2: read the size of the list
Step 3: read the elements of the list
Step 4: print list elements
Step 5: call the function unique with the list elements passed to it.
Step 6: In the calling function find the unique elements as return them as a list.
Step 7: print list elements
Step 8: stop.
Program:
def unique(l):
d=[]
for item in l:
if item not in d:
d.append(item)
return(d)
l1=[]
n=int(input("Enter the number of elements to be inserted in the list:"))
for i in range(n):
print("enter the element ",i+1,":")
num=int(input())
l1.append(num)
print("original list:",l1)
print("unique list:",unique(l1))
Output:
[root@localhost ~]# vi 9c.py
[root@localhost ~]# python3 9c.py
Enter the number of elements to be inserted in the list:6
enter the element 1 :
1
enter the element 2 :
2
enter the element 3 :
3
enter the element 4 :
4
enter the element 5 :
5
enter the element 6 :
6
original list: [1, 2, 3, 4, 5, 6]
unique list: [1, 2, 3, 4, 5, 6]
[root@localhost ~]# python3 9c.py
Enter the number of elements to be inserted in the list:6
enter the element 1 :
2
enter the element 2 :
2
enter the element 3 :
1
enter the element 4 :
4
enter the element 5 :
6
enter the element 6 :
6
original list: [2, 2, 1, 4, 6, 6]
unique list: [2, 1, 4, 6]
Exercise 10 - Multi-D Lists
AIM:
a) Write a program that defines a matrix and prints
Algorithm:
Step 1: Start
Step 2: read row and col values
Step 3: read the elements of matrix A
Step 4: print matrix elements.
Step 5: Stop.
Program:
r=int(input("Enter a row value:"))
c=int(input("Enter a column value:"))
matA=[[(int(input("Enter a number:")))for j in range(c)]for i in range(r)]
print(matA)
OutPut:
[root@localhost ~]# vi 11a.py
[root@localhost ~]# python3 11a.py
Enter a row value:4
Enter a column value:4
Enter a number:1
Enter a number:2
Enter a number:3
Enter a number:4
Enter a number:5
Enter a number:6
Enter a number:7
Enter a number:8
Enter a number:9
Enter a number:10
Enter a number:11
Enter a number:12
Enter a number:13
Enter a number:14
Enter a number:15
Enter a number:16
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
AIM:
b) Write a program to perform addition of two square matrices
Algorithm:
Step 1: Start
Step 2: read row and col values
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B
Step 5: initialize the result matrix
Step 6: compute the addition of matrix A and matrix B
Step 7: print result matrix
Step 8: Stop
Program:
m=int(input("enter row value:"))
n=int(input("enter column value:"))
print(“elements of matrix A”)
matA=[[(int(input("enter a number:"))) for j in range(n)]for i in range(m)]
print(matA)
print(“elements of matrix B”)
matB=[[(int(input("enter a number:"))) for j in range(n)]for i in range(m)]
print(matB)
res=[[int('0') for j in range(n)]for i in range(m)]
print(res)
for i in range(r):
for j in range(c):
res[i][j]=matA[i][j]+matB[i][j]
print(res)
Output:
[root@localhost ~]# python3 11b.py
enter row value:2
enter column value:2
enter a number:1
enter a number:2
enter a number:3
enter a number:4
[[1, 2], [3, 4]]
enter a number:5
enter a number:6
enter a number:7
enter a number:8
[[5, 6], [7, 8]]
[[6, 8], [10, 12]]
AIM:
c) Write a program to perform multiplication of two square matrices
Algorithm:
Step 1: Start
Step 2: read row and col values
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B
Step 5: initialize the result matrix
Step 6: compute the multiplication of matrix A and matrix B
Step 7: print result matrix
Step 8: Stop
Program:
r1=int(input("enter row value:"))
c1=int(input("enter column value:"))
matA=[[int(input("enter a number:")) for j in range(c1)]for i in range(r1)]
print("matA:",matA)
r2=int(input("enter row value:"))
c2=int(input("enter column value:"))
matB=[[int(input("enter a number:")) for j in range(c2)]for i in range(r2)]
print("matB:",matB)
res=[[int('0') for j in range(c2)]for i in range(r1)]
print("res:",res)
for i in range(r1):
for j in range(c2):
sum=0
for k in range(c1):
sum+=matA[i][k]*matB[k][j]
res[i][j]=sum
print("res:",res)
Output:
[root@localhost ~]# vi 11c.py
[root@localhost ~]# python3 11c.py
enter row value:2
enter column value:2
enter a number:2
enter a number:2
enter a number:2
enter a number:2
matA: [[2, 2], [2, 2]]
enter row value:2
enter column value:2
enter a number:2
enter a number:2
enter a number:2
enter a number:2
matB: [[2, 2], [2, 2]]
res: [[0, 0], [0, 0]]
res: [[8, 8], [8, 8]]
Exercise - 11 - Functions - Problem Solving
AIM:
a) Write a function cumulative_product to compute cumulative product of a list of
numbers.
Algorithm:
Step 1: Start
Step 2: read the size of the list
Step 3: read the elements of the list
Step 4: print list elements
Step 5: call the function cumulative_product with the list elements passed to it.
Step 6: In the calling function compute cumulative product of list elements and store it as list
and return list.
Step 7: print list
Step 8: stop.
Progarm:
def cummulative_product(l):
b=[]
prod=1
for i in range(len(l)):
prod*=l[i]
b.append(prod)
print("cummulative product:",b)
l1=[]
n=int(input("Enter the number of elements to be inserted in the list:"))
for i in range(n):
print("enter the element ",i+1,":")
num=int(input())
l1.append(num)
print("original list:",l1)
cummulative_product(l1)
Output:
[root@localhost ~]# vi 10a.py
[root@localhost ~]# python3 10a.py
Enter the number of elements to be inserted in the list:6
enter the element 1 :
1
enter the element 2 :
2
enter the element 3 :
3
enter the element 4 :
4
enter the element 5 :
5
enter the element 6 :
6
original list: [1, 2, 3, 4, 5, 6]
cummulative product: [1, 2, 6, 24, 120, 720]
AIM:
b) Write a function reverse to reverse a list. Without using the reverse function.
Algorithm:
Step 1: Start
Step 2: read the size of the list
Step 3: read the elements of the list
Step 4: print list elements
Step 5: call the function reverse with the list elements passed to it.
Step 6: In the calling function reverse the list elements and return reversed list elements.
Step 7: print list
Step 8: stop.
Program:
def reverse(l):
return(l[::-1])
l1=[]
n=int(input("Enter the number of elements to be inserted in the list:"))
for i in range(n):
print("enter the element ",i+1,":")
num=int(input())
l1.append(num)
print("original list:",l1)
print("reversed list:",reverse(l1))
Output:
[root@localhost ~]# vi 10b.py
[root@localhost ~]# python3 10b.py
Enter the number of elements to be inserted in the list:5
enter the element 1 :
1
enter the element 2 :
2
enter the element 3 :
3
enter the element 4 :
4
enter the element 5 :
5
original list: [1, 2, 3, 4, 5]
reversed list: [5, 4, 3, 2, 1]
AIM:
c) Write function to compute gcd, LCM of two numbers. Each function shouldn’t
exceed one line.
Algorithm:
Step 1: Start
Step 2: read two numbers n1 and n2
Step 3: call the recursive function gcd with the two numbers passed to it.
Step 4: in the calling function compute gcd and return it.
Step 5: print gcd value.
Step 6: call the recursive function lcm with the two numbers passed to it.
Step 7: In the calling function compute lcm and return it.
Step 8: print lcm value.
Step 9: Stop.
Program:
def gcd(x,y):
return y if x==0 else gcd(y%x,x)
def lcm(x,y):
return((x*y)//gcd(x,y))
n1=int(input("Enter a number:"))
n2=int(input("enter another number:"))
print("GCD=",gcd(n1,n2))
print("LCM=",lcm(n1,n2))
Output:
[root@localhost ~]# vi 10c.py
[root@localhost ~]# python3 10c.py
Enter a number:54
enter another number:67
GCD= 1
LCM= 3618
Exercise - 12 - Modules
AIM:
a) Install packages requests, flask and explore them. Using (pip)
Algorithm:
Step 1: Start
Step 2: To install packages issue command pip install <package_name>
Step 3: To explore the packages issue command pip show <package_name>
Step 4: Stop
Sol:
[root@localhost ~]# pip install request
Requirement already satisfied: request in /usr/lib/python2.7/site-packages
Requirement already satisfied: get in /usr/lib/python2.7/site-packages (from request)
Requirement already satisfied: post in /usr/lib/python2.7/site-packages (from request)
Requirement already satisfied: setupfiles in /usr/lib/python2.7/site-packages (from request)
Requirement already satisfied: query_string in /usr/lib/python2.7/site-packages (from
get->request)
Requirement already satisfied: public in /usr/lib/python2.7/site-packages (from
query_string->get->request)
[root@localhost ~] [root@localhost ~]# pip show request
Name: request
Version: 0.0.13
Summary: http REQUEST (GET+POST) dict
Home-page: UNKNOWN
Author: UNKNOWN
Author-email: UNKNOWN
License: UNKNOWN
Location: /usr/lib/python2.7/site-packages
Requires: get, post, setupfiles
[root@localhost ~]# pip install flask
Requirement already satisfied: flask in /usr/lib64/python2.7/site-packages
Requirement already satisfied: itsdangerous>=0.21 in /usr/lib/python2.7/site-pac
Requirement already satisfied: click>=2.0 in /usr/lib/python2.7/site-packages (f
Requirement already satisfied: Jinja2>=2.4 in /usr/lib/python2.7/site-packages (
Requirement already satisfied: Werkzeug>=0.7 in /usr/lib/python2.7/site-packages
Requirement already satisfied: MarkupSafe>=0.23 in /usr/lib/python2.7/site-packa
[root@localhost ~]# pip show flask
Name: Flask
Version: 0.12.2
Summary: A microframework based on Werkzeug, Jinja2 and good intentions
Home-page: http://github.com/pallets/flask/
Author: Armin Ronacher
Author-email: armin.ronacher@active-4.com
License: BSD
Location: /usr/lib64/python2.7/site-packages
Requires: itsdangerous, click, Jinja2, Werkzeug
[root@localhost ~]#
AIM:
b) Write a script that imports requests and fetch content from the page. E.g. (Wiki)
Algorithm:
Step 1: Start
Step 2: import necessary packages for executing program
Step 3: use get method of requests module to fetch the content of web page and store it in
variable r.
Step 4: print r
Step 5: Stop
Program:
#write a script that imports requests and fetch content from web page
import requests
r = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
print( r.text)
Output:
[root@localhost ~]# python3 12b.py
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN>
<html>
<body>
<TITLE>What time is it?</TITLE>
<H2> US Naval Observatory Master Clock Time</H2> <H3><PRE>
<BR>Nov. 14, 08:41:33 UTC Universal Time
<BR>Nov. 14, 03:41:33 AM EST Eastern Time
<BR>Nov. 14, 02:41:33 AM CST Central Time
<BR>Nov. 14, 01:41:33 AM MST Mountain Time
<BR>Nov. 14, 12:41:33 AM PST Pacific Time
<BR>Nov. 13, 11:41:33 PM AKST Alaska Time
<BR>Nov. 13, 10:41:33 PM HAST Hawaii-Aleutian Time
</PRE></H3><P><A HREF="http://www.usno.navy.mil"> US Naval Observatory</A>
</body></html>
AIM:
c) Write a simple script that serves a simple HTTP Response and a simple HTML Page.
Algorithm:
Step 1: Start
Step 2: import necessary packages for executing program
Step 3: read response by using urlopen() method and store the response in the variable
response
Step 4: decode the response using decode() method
Step 5: Print response
Step 6: Stop
Program:
from urllib.request import urlopen
with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
for line in response:
line = line.decode('utf-8')
print(line)
Output:
[root@localhost ~]# python3 12b.py
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN>
<html>
<body>
<TITLE>What time is it?</TITLE>
<H2> US Naval Observatory Master Clock Time</H2> <H3><PRE>
<BR>Nov. 14, 08:41:33 UTC Universal Time
<BR>Nov. 14, 03:41:33 AM EST Eastern Time
<BR>Nov. 14, 02:41:33 AM CST Central Time
<BR>Nov. 14, 01:41:33 AM MST Mountain Time
<BR>Nov. 14, 12:41:33 AM PST Pacific Time
<BR>Nov. 13, 11:41:33 PM AKST Alaska Time
<BR>Nov. 13, 10:41:33 PM HAST Hawaii-Aleutian Time
</PRE></H3><P><A HREF="http://www.usno.navy.mil"> US Naval Observatory</A>
</body></html>
Exercise - 13 OOP
AIM:
a) Class variables and instance variable
i)Robot
Algorithm:
Step 1: Start
Step 2: class robot designed as shown in the class diagram. It contains:
Step 3: Constructor to initialize the class variable population.
Step 4: Destructor to destroy the object and decrease the count of the class variable
population
Step 5: sayHi() method to say greeting’s from the robot.
Step 6: howMany() method to count the number of robots currently working and return it
Step 7: Stop
Class Diagram:
Robot
Population=0
sayHi()
howMany()
Fig: class diagram for Robot Class
Program:
class Robot:
'''Represents a robot, with a name.'''
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
'''Initializes the data.'''
self.name = name
print('(Initializing {0})'.format(self.name))
# When this person is created, the robot
# adds to the population
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working.'.format(Robot.population))
def sayHi(self):
'''Greeting by the robot.
Yeah, they can do that.'''
print('Greetings, my masters call me {0}.'.format(self.name))
def howMany():
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))
howMany = staticmethod(howMany)
droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()
print("nRobots can do some work here.n")
print("Robots have finished their work. So let's destroy them.")
del droid1
del droid2
Robot.howMany()
Output:
[root@localhost ~]# python3 robot.py
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.
Robots can do some work here.
Robots have finished their work. So let's destroy them.
R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.
AIM:
a) Class variables and instance variable
ii) ATM Machine
Algorithm:
Step 1: Start
Step 2: class ATM designed as shown in the class diagram. It contains:
Step 3: Constructor to initialize the data member account={}.
Step 4: new() method creates new account with a password. Optional initial amount of funds
Step 5: withdraw() method to withdraw money from the ATM
Step 6: check_balance() method to check balance
Step 7: deposit() method to deposit money in the ATM
Step 8: delete_account() method to delete account.
Step 9: start() method to transact with ATM
Step 10: Stop
Class Diagram:
Robot
account={}
new(name, pw, initial)
withdraw(name, account)
check_balance(name,pw=0)
deposit(name, account)
delete_account(name, pw=0)
start()
Fig: class diagram for ATM Class
Program:
class ATM(object):
def __init__(self, accounts={}):
#This is what shall be performed upon creation of an ATM (more like a bank really)
self.accounts = accounts
def new(self, name, pw=0, initial=0):
#Creates new account with a password. Optional initial amount of funds
self.accounts[name] = [initial, pw]
#This is the data structure: A dictionary keyed by the customer's name, containing an
array with pw and balance
def withdraw(self, name, amount):
#Method to withdraw money from the ATM
if name not in self.accounts:
print 'You do not currently have an account at this ATM to withdraw from!'
elif amount > self.accounts[name][0]:
print 'You do not have enough money to withdraw, your current balance is only %d' %
self.accounts[name][0]
else:
self.accounts[name][0] -= amount
print 'You have withdrawn %d dollars and have a remaining balance of %d.' %
(amount, self.accounts[name][0])
def check_balance(self, name, pw=0):
#Method to check balance
if name not in self.accounts:
print 'You do not have an account at this ATM!'
else:
print 'You currently have a balance of $%d' % self.accounts[name][0]
def deposit(self, name, amount):
#Method to deposit money
if name not in self.accounts:
print 'You do not have an account at this ATM!'
else:
self.accounts[name][0] += amount
print 'You have deposited $%d and now have $%d' % (amount,
self.accounts[name][0])
def delete_account(self, name, pw=0):
del self.accounts[name]
def start(self):
print 'Welcome to the new PyATM v.001'
print 'Please type in the name associated with your account'
name = raw_input('If you do not have an account, this will open an empty one for you')
if name not in self.accounts:
self.new(name)
while True:
print 'To check your balance, type C'
print 'To make a withdraw, type W'
print 'To make a deposit, type D'
print 'To change accounts, type A'
print 'To exit, type Q'
inp = raw_input('To delete your account, type DEL:').lower()
if inp == 'c':
self.check_balance(name)
elif inp == 'w':
amount = raw_input('What amount what you like to withdraw?')
try:
amount = int(amount)
except ValueError:
print 'You did not enter an integer, returning to menu'
self.withdraw(name, amount)
elif inp == 'd':
amount = raw_input('What amount would you like to deposit?')
try:
amount = int(amount)
except ValueError:
print 'You did not enter an integer, returning to menu'
self.deposit(name, amount)
elif inp == 'a':
name = raw_input('What account would you like to log into?')
if name not in self.accounts:
print 'Creating a new account under that name...'
self.new(name)
else:
print 'You are now logged into account under %s' % name
elif inp == 'del':
self.delete_account(name)
print 'The account under name %s is now deleted! Have a nice day' % name
elif inp == 'q':
print 'Exiting. Have a nice day.'
break
else:
print 'You did not enter a valid option.'
machine = ATM()
machine.start()
Output:
[root@localhost ~]# python ATM.py
Welcome to the new PyATM v.001
Please type in the name associated with your account
If you do not have an account, this will open an empty one for yousviet
To check your balance, type C
To make a withdraw, type W
To make a deposit, type D
To change accounts, type A
To exit, type Q
To delete your account, type DEL:D
What amount would you like to deposit?2000
You have deposited $2000 and now have $2000
To check your balance, type C
To make a withdraw, type W
To make a deposit, type D
To change accounts, type A
To exit, type Q
To delete your account, type DEL:C
You currently have a balance of $2000
To check your balance, type C
To make a withdraw, type W
To make a deposit, type D
To change accounts, type A
To exit, type Q
To delete your account, type DEL:W
What amount what you like to withdraw?200
You have withdrawn 200 dollars and have a remaining balance of 1800.
To check your balance, type C
To make a withdraw, type W
To make a deposit, type D
To change accounts, type A
To exit, type Q
To delete your account, type DEL:A
What account would you like to log into?achyuth
Creating a new account under that name...
To check your balance, type C
To make a withdraw, type W
To make a deposit, type D
To change accounts, type A
To exit, type Q
To delete your account, type DEL:Q
Exiting. Have a nice day.
Exercise - 14 GUI, Graphics
AIM:
a) Write a GUI for an Expression Calculator using tk
Algorithm:
Step 1: Start
Step 2: Importing the module – tkinter
Step 3: Create the main window (container)
Step 4: Add any number of widgets to the main window
Step 5: Apply Grid layout to arrange the widgets in the main window
Step 6: Apply the event Trigger on the widgets and run the application by using
root.mainloop() usally at the bottom
Step 7: Stop
Program:
import tkinter as tk
def click(key):
if key=='=':
if '/' in entry.get() and '.' not in entry.get():
entry.insert(tr.END,"0")
str1="-+0123456789"
if entry.get()[0] not in str1:
entry.insert(tk.END,"first char not in"+str1)
try:
result=eval(entry.get())
entry.insert(tk.END,"="+str(result))
except:
entry.insert(tk.END,"-->error")
elif key=='c':
entry.delete(0,tk.END)
elif key=="neg":
if'=' in entry.get():
entry.delte(0,tk.END)
try:
if entry.get()[0]=='-':
entry.delte(0)
else:
entry.insert(0,'-')
except indexerror:
pass
else:
if"=" in entry.get():
entry.delte(0,tk.END)
entry.insert(tk.END,key)
root=tk.Tk()
root.title('simple calculation')
btn_list=[
'7','8','9','*','c',
'4','5','6','/','**',
'1','2','3','-','%',
'0','.','=','+','neg']
r=1
c=0
for b in btn_list:
rel='ridge'
cmd=lambda x=b:click(x)
tk.Button(root,text=b,width=5,relief=rel,command=cmd).grid(row=r,column=c)
c+=1
if c>4:
c=0
r+=1
entry=tk.Entry(root,width=33,bg="yellow")
entry.grid(row=0,column=0,columnspan=5)
root.mainloop()
Output:
AIM:
b) Write a program to implement the following figures using turtle.
b) i)
Algorithm:
Step 1: Start
Step 2: import the turtle module.
Step 3: initialize a list with three colors and store it in list1 and i=0
Step 4: set the turtle background color as yellow and pensize as 5
Step 5: repeat the steps 6 to 10 for angle in range(0,360,30)
Step 6: set the angle of turtle using seth() method
Step 7: set the turtle color using color() method
Step 8: draw a circle with radius of 100 using circle() method
Step 9: increment i valu by 1
Step 10: if i==3 the set i value to 0.
Step 11: stop
Program:
import turtle
list1=["red","green","blue"]
turtle.bgcolor("yellow")
turtle.pensize(5)
i=0
for angle in range(0,360,30):
turtle.seth(angle)
turtle.color(list1[i])
turtle.circle(100)
i=i+1
if i==3:i=0
Output:
b) ii)
Algorithm:
Step 1: Start
Step 2: import the turtle module.
Step 3: set the turtle color as black using color() method and pensize as 5 using pensize()
method.
Step 4: set the turtle speed as 10 using speed() method
Step 5: repeat the steps 6 to 10 for i in range(0,180,5)
Step 6: turn the turtle to left by 10 pixels using left() method
Step 7: move the turtle to the forward direction by 100 pixels using forward() method
Step 8: turn the turtle to left by 90 pixels using left() method
Step 9: move the turtle to the forward direction by 100 pixels using forward() method
Step 10: turn the turtle to left by 90 pixels using left() method
Step 11: move the turtle to the forward direction by 100 pixels using forward() method
Step 12: turn the turtle to left by 90 pixels using left() method
Step 13: move the turtle to the forward direction by 100 pixels using forward() method
Step 14: turn the turtle to left by 90 pixels using left() method
Step 15: stop
Program:
import turtle
turtle.color("black")
turtle.pensize(5)
turtle.speed(10)
for i in range(0,180,5):
turtle.left(10)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
Output:

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Procedural vs. object oriented programming
Procedural vs. object oriented programmingProcedural vs. object oriented programming
Procedural vs. object oriented programming
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
pushdown automata
pushdown automatapushdown automata
pushdown automata
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT I
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT IGE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT I
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT I
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Namespaces
NamespacesNamespaces
Namespaces
 
PYTHON FEATURES.pptx
PYTHON FEATURES.pptxPYTHON FEATURES.pptx
PYTHON FEATURES.pptx
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
C++ string
C++ stringC++ string
C++ string
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 

Similar a python lab programs.pdf

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Revision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfRevision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfoptimusnotch44
 
Chapter 1 Class 12 Computer Science Unit 1
Chapter 1 Class 12 Computer Science Unit 1Chapter 1 Class 12 Computer Science Unit 1
Chapter 1 Class 12 Computer Science Unit 1ssusera7a08a
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...Yashpatel821746
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Yashpatel821746
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...Yashpatel821746
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxusvirat1805
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionARVIND PANDE
 
Python Course Basic
Python Course BasicPython Course Basic
Python Course BasicNaiyan Noor
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasserySHAMJITH KM
 

Similar a python lab programs.pdf (20)

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Revision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfRevision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdf
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
Chapter 1 Class 12 Computer Science Unit 1
Chapter 1 Class 12 Computer Science Unit 1Chapter 1 Class 12 Computer Science Unit 1
Chapter 1 Class 12 Computer Science Unit 1
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Python Course Basic
Python Course BasicPython Course Basic
Python Course Basic
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Python
PythonPython
Python
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 

Último

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Último (20)

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

python lab programs.pdf

  • 1. Exercise 1 - Basics AIM: a) Running instructions in interactive interpreter and a python script. Algorithm for running instructions in Interactive interpreter: Step 1: Start Step 2: Open terminal in Linux/Unix OS or open IDLE. Step 3: start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu Step 4: The >>> is Python's way of telling you that you are in interactive mode. Step 5: In interactive mode what you type is immediately run. Try typing 1+1 in. Python will respond with 2. Interactive mode allows you to test out and see what Python will do. If you ever feel the need to play with new Python statements, go into interactive mode and try them out. Step 6: stop [root@localhost ~]# python3 Python 3.5.3 (default, May 11 2017, 09:10:41) [GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print("Welcome to the world of Python!!!") Welcome to the world of Python!!! >>> 10+7 17 >>> 50+40-35 55 >>> 12*10 120 >>> 96/12 8.0 >>> (-30*4)+500 380 >>> 5*3.0 15.0 >>> 78//5 15 >>> 78%5 3 >>> 5**3 125 >>> "Hello" 'Hello' >>> 'Hello' 'Hello' >>> '''Hello''' 'Hello'
  • 2. >>> print("what's your name") what's your name >>> print("The boy replies, "My name is John."") The boy replies, "My name is John." >>> print("Today is 15th August. n India became independent on this day") Today is 15th August. India became independent on this day >>> print("I have studied many programming languages. ... But my best favorite langugae is Python.") I have studied many programming languages. But my best favorite langugae is Python. >>> print(R"What's your name") What's your name >>> print('Beautiful Weather' '.....' 'Seems it would rain') Beautiful Weather.....Seems it would rain >>> a=10 >>> b=20 >>> print(a+b) 30 >>> print(a,b) 10 20 >>> a>b False >>> a<b True >>> a==b False >>> a!=b True >>> type(a) <class 'int'> >>> help Type help() for interactive help, or help(object) for help about object. >>> help(int) Help on class int in module builtins: class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
  • 3. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | self != 0 | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. >>> Press ctrl+d to exit from pyhon interpreter Algorithm for running Python Srcipt: Step 1: Start Step 2: Open an editor Step 3: Write the instructions Step 4: Save it as a file with the filename having the extension .py Step 5: Run the interpreter with command python program_name.py or uses IDLE to run the programs. Step 6: Stop
  • 4. AIM: b) Write a program to purposefully raise indentation error and correct it. Whitespace at the beginning of the line is called indentation. These whitespaces or the indentation are very important in python. In a python program, the leading whitespace including spaces and tabs at the beginning of the logical line determines the indentation level of that logical line. In python, indentation is used to associate the group statements. Program to exhibit indentation error [root@localhost ~]# vi try.py Age=21 Print(“You can vote”) [root@localhost ~]# python3 try.py File "try.py", line 2 print("You can vote") ^ IndentationError: unexpected indent The level of indentation groups statements to form a block of statements. This means that statements in a block must have the same indentation level. Python very strictly checks the indentation level and gives an error if indentation is not correct. Like other programming languages python does not use curly braces to indicate blocks of code for class, function definitions or flow of control statements. It uses only indentation to form a block. All statements inside a block should be at the same indentation level. The above example is corrected as below to get output [root@localhost ~]# vi try.py Age=21 Print(“You can vote”) [root@localhost ~]# python3 try.py You can vote
  • 5. Exercise 2 - Operations AIM: a) Write a program to compute distance between two points taking input from the user (Pythagorean Theorem). Algorithm: Step 1: Start Step 2: import the math module. Step 3: Read x1,y1,x2,y2 Step 4: compute distance between two points using Pythagorean Theorem. Step 5: print distance Step 6: stop Program: import math x1=int(input("Enter x1 value:")) y1=int(input("Enter y1 value:")) x2=int(input("Enter x2 value:")) y2=int(input("Enter y2 value:")) distance=math.sqrt(((x2-x1)**2)+((y2-y1)**2)) print("Distance=",distance) Output: [root@localhost python] python3 2a.py Enter x1 value:3 Enter y1 value:4 Enter x2 value:5 Enter y2 value:6 Distance= 2.8284271247461903
  • 6. AIM: b) Write a program add.py that takes 2 numbers as command line arguments and prints its sum. Algorithm: Step 1: Start Step 2: import the sys module. Step 3: read command line arguments to variables a,b Step 4: compute sum = int(a) + int(b) Step 5: print sum Step 6: stop Program: import sys a=sys.argv[1] b=sys.argv[2] sum=int(a)+int(b) print("Sum=",sum) print("Length of argv=",len(sys.argv)) Output: [root@localhost python]# python3 2b.py 45 67 Sum= 112 Length of argv= 3
  • 7. Exercise - 3 Control Flow AIM: a) Write a Program for checking whether the given number is a even number or not. Algorithm: Step 1: Start Step 2: read n value. Step 3: if n is divisible by 2 goto step 4 else goto step 5 Step 4: print n is even Step 5: print n is odd Step 6: stop Program: n=int(input("enter any one number:")) if(n%2==0): print(n,"is even") else: print(n,"is odd") Output: [root@localhost python] vi 3a.py [root@localhost python] python3 3a.py enter any one number:64 64 is even [root@localhost python] python3 3a.py enter any one number:66 66 is even [root@localhost python] python3 3a.py enter any one number:45 45 is odd
  • 8. AIM: b) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3, 1/4, - - - - -- -- ---1/10 AIM: b) Write a program add.py that takes 2 numbers as command line arguments and prints its sum. Algorithm: Step 1: Start Step 2: import the sys module. Step 3: read command line arguments to variables a,b Step 4: compute sum = int(a) + int(b) Step 5: print sum Step 6: stop Program: import sys a=sys.argv[1] b=sys.argv[2] sum=int(a)+int(b) print("Sum=",sum) print("Length of argv=",len(sys.argv)) Output: [root@localhost python]# python3 2b.py 45 67 Sum= 112 Length of argv= 3
  • 9. Exercise - 3 Control Flow AIM: a) Write a Program for checking whether the given number is a even number or not. Algorithm: Step 1: Start Step 2: read n value. Step 3: if n is divisible by 2 goto step 4 else goto step 5 Step 4: print n is even Step 5: print n is odd Step 6: stop Program: n=int(input("enter any one number:")) if(n%2==0): print(n,"is even") else: print(n,"is odd") Output: [root@localhost python] vi 3a.py [root@localhost python] python3 3a.py enter any one number:64 64 is even [root@localhost python] python3 3a.py enter any one number:66 66 is even [root@localhost python] python3 3a.py enter any one number:45 45 is odd
  • 10. AIM: b) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3, 1/4, - - - - -- -- ---1/10 Algorithm: Step 1: Start Step 2: read a string Step 3: split the string using split() method and store it in variable list1 Step 4: print list1 Step 5: join the string using join() method and store it in sj Step 6: print sj Step 7: stop Program: str=input("Enter a string:") print("string after spliting:") list1=str.split() print(list1) print("string after join:") sj=' '.join(l) print(sj) Output: [root@localhost python]# python3 5b.py Enter a string::python programming lab in first sem first year string after spliting: [':python', 'programming', 'lab', 'in', 'first', 'sem', 'first', 'year'] string after join: :python programming lab in first sem first year
  • 11. Exercise - 6 DS - Continued AIM: a) Write a program combine lists that combines these lists into a dictionary. Algorithm: Step 1: Start Step 2: initialize list1 and list2 Step 3: add one list elements to another list by using concatenation (+) operator Step 4: combine two lists using zip() method and store it in variable rev Step 5: convert rev into dictionary by using dict() method and print it Step 6: stop Program: list1=[1,2,3] list2=['one','two','three'] l3=list1+list2 print('combination of two lists:',l3) rev=zip(list1,list2) print(dict(rev)) Output: [root@localhost python]# vi 6a.py [root@localhost python]# python3 6a.py combination of two lists: [1, 2, 3, 'one', 'two', 'three'] {1: 'one', 2: 'two', 3: 'three'}
  • 12. AIM: b) Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file? Algorithm: Step 1: Start Step 2: read filename Step 3: open file in read mode Step 4: find the index position of ‘.’ Using index() method Step 5: get the extension of file using [:] operator Step 6: if the file extension is ‘py’ then go to step 8 otherwise go to step 9 Step 7: Print ‘The given file is a python file’ Step 8: if the file extension is ‘c’ then go to step 10 otherwise go to step 11 Step 9: print ‘The given file is a C file’ Step 10: if the file extension is ‘txt’ then go to step 12 otherwise go to step 13 Step 11: print ‘The given file is a text file’ Step 12: read file contents by using read() method and store in variable str Step 13: close the file Step 14: initialize dict = {} Step 15: repeat the step 16 for char in str Step 16: add dict[char] = str.count(char) Step 17: print dict Step 18: stop Program: fname=input("enter file name:") f=open(fname,'r') index=fname.index('.') ext=fname[index+1:] if(ext=='py'): print('The given file is a python file') elif(ext=='c'): print('The given file is a C file') elif(ext=='txt'): print('The given file is a text file') str=f.read() print(str) f.close() dict={} for ch in s: dict[ch]=s.count(ch) print(dict)
  • 13. Output: [root@localhost python]# python3 6b.py enter file name:6a.py The given file is a python file l1=[1,2,3] l2=['one','two','three'] l3=l1+l2 print('combination of two lists:',l3) rev=zip(l1,l2) print(dict(rev)) {' ': 3, 'i': 7, 'l': 9, ':': 1, 'w': 2, 'c': 2, 'z': 1, 's': 2, 'd': 1, 'o': 6, 'a': 1, '+': 1, 'h': 1, 'e': 5, 't': 8, 'b': 1, '3': 3, ')': 4, 'n': 5, '2': 4, 'v': 2, ']': 2, 'f': 1, "'": 8, '[': 2, '(': 4, 'p': 3, 'n': 6, '=': 4, 'r': 5, 'm': 1, '1': 4, ',': 6} [root@localhost python]# vi sample.txt [root@localhost python]# python3 6b.py enter file name:sample.txt The given file is a text file sdfasdjkfkasdf sdafasdfsd sdgvsdfgsd fgsdgsdgsd sdfsd fsdgfsdfg sdgvfgvsdfgsd gvsdfgsdf f sdfsd fsdfv {'k': 2, 's': 24, 'n': 11, 'j': 1, 'v': 5, 'd': 24, 'f': 19, 'g': 12, 'a': 4} [root@localhost python]# python3 6b.py enter file name:sample.c The given file is a C file dafdas adf dfasf adfsd fds {'s': 4, 'a': 5, 'f': 6, 'd': 7, 'n': 5}
  • 14. Exercise - 7 Files AIM: a) Write a program to print each line of a file in reverse order. Algorithm: Step 1: Start Step 2: read filename Step 3: open file in read mode Step 4: read lines in a file by using readlines() method and store them in str Step 5: initialize lines = [] Step 6: repeat steps 7, 8 and 9 for each line in str Step 7: replace ‘n’ with ‘’ in each line Step 8: reverse the line Step 9: append the reversed line to lines Step 10: close the file Step 11: repeat step 12 for each line in lines Step 12: print line Step 13: stop Program: f=open("sample.txt","r") str=f.readlines() lines=[] for line in str: line=line.replace('n','') reverse=line[::-1] lines.append(reverse) f.close() for line in lines: print(line) Output: [root@localhost python]# vi 7a.py [root@localhost python]# python3 7a.py fdsakfkjdsafds dsfdsafads dsgfdsvgds dsgdsgdsgf dsfds gfdsfgdsf AIM: b) Write a program to compute the number of characters, words and lines in a file. Algorithm:
  • 15. Step 1: Start Step 2: open file in read mode Step 3: read contents of file using read() method into variable str Step 4: close the file Step 5: print str Step 6: compute lines = str.count('n') Step 7: compute words = str.count(' ')+lines Step 8: compute chars = len(str)-words Step 9: print lines, words, chars Step 10: stop Program: f=open("sample.txt",'r') str=f.read() f.close() print(str) words=0;chars=0;lines=0 lines=str.count('n') words=str.count(' ')+lines chars=len(str)-words print("number of lines:",lines) print("number of words:",words) print("number of characters:",chars) Output: [root@localhost python]# vi 7b.py [root@localhost python]# python3 7b.py sdfasdjkfkasdf sdafasdfsd sdgvsdfgsd fgsdgsdgsd sdfsd fsdgfsdfg sdgvfgvsdfgsd gvsdfgsdf f sdfsd fsdfv number of lines: 11 number of lines: 11 number of words: 11 number of characters: 91
  • 16.
  • 17. Exercise - 8 Functions AIM: a) Write a function ball collides that takes two balls as parameters and computes if they are colliding. Your function should return a Boolean representing whether or not the balls are colliding. Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius If (distance between two balls centers) <= (sum of their radius) then (they are colliding). Algorithm: Step 1: Start Step 2: read t1, t2 as tuple data structure Step 3: call function ball_collide by passing t1 and t2 Step 4: compute the distance between two balls in calling function Step 5: compare distance with sum of radius Step 6: Return the value from the calling function to the called function Step 7: print the return value in called function Step 8: stop Program: import math def ball_collide(b1,b2): dx=int(b2[0])-int(b1[0]) dy=int(b2[1])-int(b1[1]) dist=math.sqrt(dx**2+dy**2) if dist<=(int(b1[2])+int(b2[2])): return True else: return False t1=tuple(input("Enter the x,y points and radius of ball 1:").split(',')) t2=tuple(input("Enter the x,y points and radius of ball 2:").split(',')) print(ball_collide(t1,t2)) Output: [root@localhost python]# vi 8a.py [root@localhost python]# python3 8a.py Enter the x,y points and radius of ball 1:2,3,4 Enter the x,y points and radius of ball 2:5,6,7 True
  • 18. AIM: b) Find mean, median, mode for the given set of numbers in a list. Algorithm: Step 1: Start Step 2: read the size of the list Step 3: read the elements of the list Step 4: print list elements Step 5: call the function mean with the list elements passed to it. Step 6: In the calling function compute the mean and return it. Step 7: print mean Step 8: call the function median with the list elements passed to it. Step 9: In the calling function compute median and return it. Step 10: print median Step 11: call the function mode with the list elements passed to it. Step 12: In the calling function compute the mode and return it. Step 13: print mode Step 14: stop Program: def mean(l): return(sum(l)/len(l)) def median(l): l.sort() i=len(l)-1 if(len(l)%2==0): return(l[i//2]+l[(i+1)//2]) else: return(l[i//2]) def mode(l): m=max([l.count(a)for a in l]) l=[x for x in l if l.count(x)==m] l=list(set(l)) if m>1 and len(l)==1: return(l[0]) else: return None l1=[] n=int(input("Enter number of elements to be inserted in a list:")) for i in range(n): print("Enter element",i+1,":") num=int(input()) l1.append(num) print(l1) print("Mean of list of numbers:",mean(l1)) print("Median of list of numbers:",median(l1))
  • 19. print("Mode of list of numbers:",mode(l1)) Output: [root@localhost ~]# vi 8b.py [root@localhost ~]# python3 8b.py Enter number of elements to be inserted in a list:6 Enter element 1 : 1 Enter element 2 : 2 Enter element 3 : 3 Enter element 4 : 4 Enter element 5 : 5 Enter element 6 : 6 [1, 2, 3, 4, 5, 6] Mean of list of numbers: 3.5 Median of list of numbers: 7 Mode of list of numbers: None
  • 20. Exercise - 9 Functions - Continued AIM: a) Write a function nearly equal to test whether two strings are nearly equal. Two strings a and b are nearly equal when a can be generated by a single mutation on b. Algorithm: Step 1: Start Step 2: call the function nearly_equal with two strings Step 3: call the function mutate with word1 from the calling function Step 4: generate list of strings by adding new character to word1 and store them as a list in variable inserting Step 5: generate list of strings by deleting each character from word1 and store them as a list in the variable deleting. Step 6: generate list of strings by replacing each character in word1 and store them as a list in the variable replacing. Step 7: generate list of strings by swapping characters in word1 and store them as a list in the variable swapping Step 8: concatenate all the four lists and store them in all Step 9: return the list all to the called function Step 10: Return the value from the calling function to the called function by checking word2 is in all list or not Step 11: Print the value. Step 12: stop Program: import string def mutate(word): inserting=[word[:i]+x+word[i:] for i in range(len(word)) for x in list(string.ascii_lowercase)] deleting=[word[:i]+word[i+1:] for i in range(len(word))] replacing=[word[:i]+x+word[i+1:] for i in range(len(word)) for x in list(string.ascii_lowercase)] swapping=[word[:i]+word[i+1]+word[i]+word[i+2:] for i in range(len(word)-1)] all=inserting+deleting+replacing+swapping return all def nearly_equal(word1,word2): return True if word2 in mutate(word1) else False print(nearly_equal('python','perl')) print(nearly_equal('perl','pearl')) print(nearly_equal('python','jython')) print(nearly_equal('man','woman'))
  • 21. Output: [root@localhost ~]# vi 9a.py [root@localhost ~]# python3 9a.py False True True False
  • 22. AIM: b) Write a function dups to find all duplicates in the list. Algorithm: Step 1: Start Step 2: read the size of the list Step 3: read the elements of the list Step 4: print list elements Step 5: call the function dups with the list elements passed to it. Step 6: In the calling function find the duplicate elements as return them as a list. Step 7: print duplicate elements Step 8: stop. Program: def dups(l): d=[] for item in l: if(l.count(item)>1): if item not in d: d.append(item) return(d) l1=[] n=int(input("Enter the number of elements to be inserted in the list:")) for i in range(n): print("enter the element ",i+1,":") num=int(input()) l1.append(num) print("original list:",l1) print("duplicate elements of a list:",dups(l1)) Output: [root@localhost ~]# vi 9b.c [root@localhost ~]# python3 9b.c Enter the number of elements to be inserted in the list:6 enter the element 1 : 1 enter the element 2 : 2 enter the element 3 : 3 enter the element 4 : 4 enter the element 5 : 5 enter the element 6 :
  • 23. 6 original list: [1, 2, 3, 4, 5, 6] duplicate elements of a list: [] [root@localhost ~]# python3 9b.c Enter the number of elements to be inserted in the list:6 enter the element 1 : 1 enter the element 2 : 3 enter the element 3 : 2 enter the element 4 : 5 enter the element 5 : 3 enter the element 6 : 3 original list: [1, 3, 2, 5, 3, 3] duplicate elements of a list: [3]
  • 24. AIM: c) Write a function unique to find all the unique elements of a list. Algorithm: Step 1: Start Step 2: read the size of the list Step 3: read the elements of the list Step 4: print list elements Step 5: call the function unique with the list elements passed to it. Step 6: In the calling function find the unique elements as return them as a list. Step 7: print list elements Step 8: stop. Program: def unique(l): d=[] for item in l: if item not in d: d.append(item) return(d) l1=[] n=int(input("Enter the number of elements to be inserted in the list:")) for i in range(n): print("enter the element ",i+1,":") num=int(input()) l1.append(num) print("original list:",l1) print("unique list:",unique(l1)) Output: [root@localhost ~]# vi 9c.py [root@localhost ~]# python3 9c.py Enter the number of elements to be inserted in the list:6 enter the element 1 : 1 enter the element 2 : 2 enter the element 3 : 3 enter the element 4 : 4 enter the element 5 : 5 enter the element 6 : 6
  • 25. original list: [1, 2, 3, 4, 5, 6] unique list: [1, 2, 3, 4, 5, 6] [root@localhost ~]# python3 9c.py Enter the number of elements to be inserted in the list:6 enter the element 1 : 2 enter the element 2 : 2 enter the element 3 : 1 enter the element 4 : 4 enter the element 5 : 6 enter the element 6 : 6 original list: [2, 2, 1, 4, 6, 6] unique list: [2, 1, 4, 6]
  • 26. Exercise 10 - Multi-D Lists AIM: a) Write a program that defines a matrix and prints Algorithm: Step 1: Start Step 2: read row and col values Step 3: read the elements of matrix A Step 4: print matrix elements. Step 5: Stop. Program: r=int(input("Enter a row value:")) c=int(input("Enter a column value:")) matA=[[(int(input("Enter a number:")))for j in range(c)]for i in range(r)] print(matA) OutPut: [root@localhost ~]# vi 11a.py [root@localhost ~]# python3 11a.py Enter a row value:4 Enter a column value:4 Enter a number:1 Enter a number:2 Enter a number:3 Enter a number:4 Enter a number:5 Enter a number:6 Enter a number:7 Enter a number:8 Enter a number:9 Enter a number:10 Enter a number:11 Enter a number:12 Enter a number:13 Enter a number:14 Enter a number:15 Enter a number:16 [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] AIM: b) Write a program to perform addition of two square matrices
  • 27. Algorithm: Step 1: Start Step 2: read row and col values Step 3: read the elements of matrix A Step 4: read the elements of matrix B Step 5: initialize the result matrix Step 6: compute the addition of matrix A and matrix B Step 7: print result matrix Step 8: Stop Program: m=int(input("enter row value:")) n=int(input("enter column value:")) print(“elements of matrix A”) matA=[[(int(input("enter a number:"))) for j in range(n)]for i in range(m)] print(matA) print(“elements of matrix B”) matB=[[(int(input("enter a number:"))) for j in range(n)]for i in range(m)] print(matB) res=[[int('0') for j in range(n)]for i in range(m)] print(res) for i in range(r): for j in range(c): res[i][j]=matA[i][j]+matB[i][j] print(res) Output: [root@localhost ~]# python3 11b.py enter row value:2 enter column value:2 enter a number:1 enter a number:2 enter a number:3 enter a number:4 [[1, 2], [3, 4]] enter a number:5 enter a number:6 enter a number:7 enter a number:8 [[5, 6], [7, 8]] [[6, 8], [10, 12]] AIM: c) Write a program to perform multiplication of two square matrices Algorithm: Step 1: Start
  • 28. Step 2: read row and col values Step 3: read the elements of matrix A Step 4: read the elements of matrix B Step 5: initialize the result matrix Step 6: compute the multiplication of matrix A and matrix B Step 7: print result matrix Step 8: Stop Program: r1=int(input("enter row value:")) c1=int(input("enter column value:")) matA=[[int(input("enter a number:")) for j in range(c1)]for i in range(r1)] print("matA:",matA) r2=int(input("enter row value:")) c2=int(input("enter column value:")) matB=[[int(input("enter a number:")) for j in range(c2)]for i in range(r2)] print("matB:",matB) res=[[int('0') for j in range(c2)]for i in range(r1)] print("res:",res) for i in range(r1): for j in range(c2): sum=0 for k in range(c1): sum+=matA[i][k]*matB[k][j] res[i][j]=sum print("res:",res) Output: [root@localhost ~]# vi 11c.py [root@localhost ~]# python3 11c.py enter row value:2 enter column value:2 enter a number:2 enter a number:2 enter a number:2 enter a number:2 matA: [[2, 2], [2, 2]] enter row value:2 enter column value:2 enter a number:2 enter a number:2 enter a number:2 enter a number:2 matB: [[2, 2], [2, 2]] res: [[0, 0], [0, 0]] res: [[8, 8], [8, 8]]
  • 29.
  • 30. Exercise - 11 - Functions - Problem Solving AIM: a) Write a function cumulative_product to compute cumulative product of a list of numbers. Algorithm: Step 1: Start Step 2: read the size of the list Step 3: read the elements of the list Step 4: print list elements Step 5: call the function cumulative_product with the list elements passed to it. Step 6: In the calling function compute cumulative product of list elements and store it as list and return list. Step 7: print list Step 8: stop. Progarm: def cummulative_product(l): b=[] prod=1 for i in range(len(l)): prod*=l[i] b.append(prod) print("cummulative product:",b) l1=[] n=int(input("Enter the number of elements to be inserted in the list:")) for i in range(n): print("enter the element ",i+1,":") num=int(input()) l1.append(num) print("original list:",l1) cummulative_product(l1) Output: [root@localhost ~]# vi 10a.py [root@localhost ~]# python3 10a.py Enter the number of elements to be inserted in the list:6 enter the element 1 : 1 enter the element 2 : 2 enter the element 3 : 3 enter the element 4 : 4
  • 31. enter the element 5 : 5 enter the element 6 : 6 original list: [1, 2, 3, 4, 5, 6] cummulative product: [1, 2, 6, 24, 120, 720]
  • 32. AIM: b) Write a function reverse to reverse a list. Without using the reverse function. Algorithm: Step 1: Start Step 2: read the size of the list Step 3: read the elements of the list Step 4: print list elements Step 5: call the function reverse with the list elements passed to it. Step 6: In the calling function reverse the list elements and return reversed list elements. Step 7: print list Step 8: stop. Program: def reverse(l): return(l[::-1]) l1=[] n=int(input("Enter the number of elements to be inserted in the list:")) for i in range(n): print("enter the element ",i+1,":") num=int(input()) l1.append(num) print("original list:",l1) print("reversed list:",reverse(l1)) Output: [root@localhost ~]# vi 10b.py [root@localhost ~]# python3 10b.py Enter the number of elements to be inserted in the list:5 enter the element 1 : 1 enter the element 2 : 2 enter the element 3 : 3 enter the element 4 : 4 enter the element 5 : 5 original list: [1, 2, 3, 4, 5] reversed list: [5, 4, 3, 2, 1] AIM: c) Write function to compute gcd, LCM of two numbers. Each function shouldn’t exceed one line.
  • 33. Algorithm: Step 1: Start Step 2: read two numbers n1 and n2 Step 3: call the recursive function gcd with the two numbers passed to it. Step 4: in the calling function compute gcd and return it. Step 5: print gcd value. Step 6: call the recursive function lcm with the two numbers passed to it. Step 7: In the calling function compute lcm and return it. Step 8: print lcm value. Step 9: Stop. Program: def gcd(x,y): return y if x==0 else gcd(y%x,x) def lcm(x,y): return((x*y)//gcd(x,y)) n1=int(input("Enter a number:")) n2=int(input("enter another number:")) print("GCD=",gcd(n1,n2)) print("LCM=",lcm(n1,n2)) Output: [root@localhost ~]# vi 10c.py [root@localhost ~]# python3 10c.py Enter a number:54 enter another number:67 GCD= 1 LCM= 3618
  • 34. Exercise - 12 - Modules AIM: a) Install packages requests, flask and explore them. Using (pip) Algorithm: Step 1: Start Step 2: To install packages issue command pip install <package_name> Step 3: To explore the packages issue command pip show <package_name> Step 4: Stop Sol: [root@localhost ~]# pip install request Requirement already satisfied: request in /usr/lib/python2.7/site-packages Requirement already satisfied: get in /usr/lib/python2.7/site-packages (from request) Requirement already satisfied: post in /usr/lib/python2.7/site-packages (from request) Requirement already satisfied: setupfiles in /usr/lib/python2.7/site-packages (from request) Requirement already satisfied: query_string in /usr/lib/python2.7/site-packages (from get->request) Requirement already satisfied: public in /usr/lib/python2.7/site-packages (from query_string->get->request) [root@localhost ~] [root@localhost ~]# pip show request Name: request Version: 0.0.13 Summary: http REQUEST (GET+POST) dict Home-page: UNKNOWN Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Location: /usr/lib/python2.7/site-packages Requires: get, post, setupfiles [root@localhost ~]# pip install flask Requirement already satisfied: flask in /usr/lib64/python2.7/site-packages Requirement already satisfied: itsdangerous>=0.21 in /usr/lib/python2.7/site-pac Requirement already satisfied: click>=2.0 in /usr/lib/python2.7/site-packages (f Requirement already satisfied: Jinja2>=2.4 in /usr/lib/python2.7/site-packages ( Requirement already satisfied: Werkzeug>=0.7 in /usr/lib/python2.7/site-packages Requirement already satisfied: MarkupSafe>=0.23 in /usr/lib/python2.7/site-packa [root@localhost ~]# pip show flask Name: Flask Version: 0.12.2 Summary: A microframework based on Werkzeug, Jinja2 and good intentions Home-page: http://github.com/pallets/flask/ Author: Armin Ronacher Author-email: armin.ronacher@active-4.com License: BSD
  • 35. Location: /usr/lib64/python2.7/site-packages Requires: itsdangerous, click, Jinja2, Werkzeug [root@localhost ~]#
  • 36. AIM: b) Write a script that imports requests and fetch content from the page. E.g. (Wiki) Algorithm: Step 1: Start Step 2: import necessary packages for executing program Step 3: use get method of requests module to fetch the content of web page and store it in variable r. Step 4: print r Step 5: Stop Program: #write a script that imports requests and fetch content from web page import requests r = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl') print( r.text) Output: [root@localhost ~]# python3 12b.py <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN> <html> <body> <TITLE>What time is it?</TITLE> <H2> US Naval Observatory Master Clock Time</H2> <H3><PRE> <BR>Nov. 14, 08:41:33 UTC Universal Time <BR>Nov. 14, 03:41:33 AM EST Eastern Time <BR>Nov. 14, 02:41:33 AM CST Central Time <BR>Nov. 14, 01:41:33 AM MST Mountain Time <BR>Nov. 14, 12:41:33 AM PST Pacific Time <BR>Nov. 13, 11:41:33 PM AKST Alaska Time <BR>Nov. 13, 10:41:33 PM HAST Hawaii-Aleutian Time </PRE></H3><P><A HREF="http://www.usno.navy.mil"> US Naval Observatory</A> </body></html>
  • 37. AIM: c) Write a simple script that serves a simple HTTP Response and a simple HTML Page. Algorithm: Step 1: Start Step 2: import necessary packages for executing program Step 3: read response by using urlopen() method and store the response in the variable response Step 4: decode the response using decode() method Step 5: Print response Step 6: Stop Program: from urllib.request import urlopen with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response: for line in response: line = line.decode('utf-8') print(line) Output: [root@localhost ~]# python3 12b.py <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN> <html> <body> <TITLE>What time is it?</TITLE> <H2> US Naval Observatory Master Clock Time</H2> <H3><PRE> <BR>Nov. 14, 08:41:33 UTC Universal Time <BR>Nov. 14, 03:41:33 AM EST Eastern Time <BR>Nov. 14, 02:41:33 AM CST Central Time <BR>Nov. 14, 01:41:33 AM MST Mountain Time <BR>Nov. 14, 12:41:33 AM PST Pacific Time <BR>Nov. 13, 11:41:33 PM AKST Alaska Time <BR>Nov. 13, 10:41:33 PM HAST Hawaii-Aleutian Time </PRE></H3><P><A HREF="http://www.usno.navy.mil"> US Naval Observatory</A> </body></html>
  • 38. Exercise - 13 OOP AIM: a) Class variables and instance variable i)Robot Algorithm: Step 1: Start Step 2: class robot designed as shown in the class diagram. It contains: Step 3: Constructor to initialize the class variable population. Step 4: Destructor to destroy the object and decrease the count of the class variable population Step 5: sayHi() method to say greeting’s from the robot. Step 6: howMany() method to count the number of robots currently working and return it Step 7: Stop Class Diagram: Robot Population=0 sayHi() howMany() Fig: class diagram for Robot Class Program: class Robot: '''Represents a robot, with a name.''' # A class variable, counting the number of robots population = 0 def __init__(self, name): '''Initializes the data.''' self.name = name print('(Initializing {0})'.format(self.name)) # When this person is created, the robot # adds to the population Robot.population += 1 def __del__(self): '''I am dying.''' print('{0} is being destroyed!'.format(self.name)) Robot.population -= 1 if Robot.population == 0: print('{0} was the last one.'.format(self.name)) else: print('There are still {0:d} robots working.'.format(Robot.population))
  • 39. def sayHi(self): '''Greeting by the robot. Yeah, they can do that.''' print('Greetings, my masters call me {0}.'.format(self.name)) def howMany(): '''Prints the current population.''' print('We have {0:d} robots.'.format(Robot.population)) howMany = staticmethod(howMany) droid1 = Robot('R2-D2') droid1.sayHi() Robot.howMany() droid2 = Robot('C-3PO') droid2.sayHi() Robot.howMany() print("nRobots can do some work here.n") print("Robots have finished their work. So let's destroy them.") del droid1 del droid2 Robot.howMany() Output: [root@localhost ~]# python3 robot.py (Initializing R2-D2) Greetings, my masters call me R2-D2. We have 1 robots. (Initializing C-3PO) Greetings, my masters call me C-3PO. We have 2 robots. Robots can do some work here. Robots have finished their work. So let's destroy them. R2-D2 is being destroyed! There are still 1 robots working. C-3PO is being destroyed! C-3PO was the last one. We have 0 robots.
  • 40. AIM: a) Class variables and instance variable ii) ATM Machine Algorithm: Step 1: Start Step 2: class ATM designed as shown in the class diagram. It contains: Step 3: Constructor to initialize the data member account={}. Step 4: new() method creates new account with a password. Optional initial amount of funds Step 5: withdraw() method to withdraw money from the ATM Step 6: check_balance() method to check balance Step 7: deposit() method to deposit money in the ATM Step 8: delete_account() method to delete account. Step 9: start() method to transact with ATM Step 10: Stop Class Diagram: Robot account={} new(name, pw, initial) withdraw(name, account) check_balance(name,pw=0) deposit(name, account) delete_account(name, pw=0) start() Fig: class diagram for ATM Class Program: class ATM(object): def __init__(self, accounts={}): #This is what shall be performed upon creation of an ATM (more like a bank really) self.accounts = accounts def new(self, name, pw=0, initial=0): #Creates new account with a password. Optional initial amount of funds self.accounts[name] = [initial, pw] #This is the data structure: A dictionary keyed by the customer's name, containing an array with pw and balance def withdraw(self, name, amount): #Method to withdraw money from the ATM if name not in self.accounts: print 'You do not currently have an account at this ATM to withdraw from!' elif amount > self.accounts[name][0]: print 'You do not have enough money to withdraw, your current balance is only %d' % self.accounts[name][0] else:
  • 41. self.accounts[name][0] -= amount print 'You have withdrawn %d dollars and have a remaining balance of %d.' % (amount, self.accounts[name][0]) def check_balance(self, name, pw=0): #Method to check balance if name not in self.accounts: print 'You do not have an account at this ATM!' else: print 'You currently have a balance of $%d' % self.accounts[name][0] def deposit(self, name, amount): #Method to deposit money if name not in self.accounts: print 'You do not have an account at this ATM!' else: self.accounts[name][0] += amount print 'You have deposited $%d and now have $%d' % (amount, self.accounts[name][0]) def delete_account(self, name, pw=0): del self.accounts[name] def start(self): print 'Welcome to the new PyATM v.001' print 'Please type in the name associated with your account' name = raw_input('If you do not have an account, this will open an empty one for you') if name not in self.accounts: self.new(name) while True: print 'To check your balance, type C' print 'To make a withdraw, type W' print 'To make a deposit, type D' print 'To change accounts, type A' print 'To exit, type Q' inp = raw_input('To delete your account, type DEL:').lower() if inp == 'c': self.check_balance(name) elif inp == 'w': amount = raw_input('What amount what you like to withdraw?') try: amount = int(amount) except ValueError: print 'You did not enter an integer, returning to menu' self.withdraw(name, amount) elif inp == 'd': amount = raw_input('What amount would you like to deposit?') try: amount = int(amount) except ValueError:
  • 42. print 'You did not enter an integer, returning to menu' self.deposit(name, amount) elif inp == 'a': name = raw_input('What account would you like to log into?') if name not in self.accounts: print 'Creating a new account under that name...' self.new(name) else: print 'You are now logged into account under %s' % name elif inp == 'del': self.delete_account(name) print 'The account under name %s is now deleted! Have a nice day' % name elif inp == 'q': print 'Exiting. Have a nice day.' break else: print 'You did not enter a valid option.' machine = ATM() machine.start()
  • 43. Output: [root@localhost ~]# python ATM.py Welcome to the new PyATM v.001 Please type in the name associated with your account If you do not have an account, this will open an empty one for yousviet To check your balance, type C To make a withdraw, type W To make a deposit, type D To change accounts, type A To exit, type Q To delete your account, type DEL:D What amount would you like to deposit?2000 You have deposited $2000 and now have $2000 To check your balance, type C To make a withdraw, type W To make a deposit, type D To change accounts, type A To exit, type Q To delete your account, type DEL:C You currently have a balance of $2000 To check your balance, type C To make a withdraw, type W To make a deposit, type D To change accounts, type A To exit, type Q To delete your account, type DEL:W What amount what you like to withdraw?200 You have withdrawn 200 dollars and have a remaining balance of 1800. To check your balance, type C To make a withdraw, type W To make a deposit, type D To change accounts, type A To exit, type Q To delete your account, type DEL:A What account would you like to log into?achyuth Creating a new account under that name... To check your balance, type C To make a withdraw, type W To make a deposit, type D To change accounts, type A To exit, type Q To delete your account, type DEL:Q Exiting. Have a nice day.
  • 44. Exercise - 14 GUI, Graphics AIM: a) Write a GUI for an Expression Calculator using tk Algorithm: Step 1: Start Step 2: Importing the module – tkinter Step 3: Create the main window (container) Step 4: Add any number of widgets to the main window Step 5: Apply Grid layout to arrange the widgets in the main window Step 6: Apply the event Trigger on the widgets and run the application by using root.mainloop() usally at the bottom Step 7: Stop Program: import tkinter as tk def click(key): if key=='=': if '/' in entry.get() and '.' not in entry.get(): entry.insert(tr.END,"0") str1="-+0123456789" if entry.get()[0] not in str1: entry.insert(tk.END,"first char not in"+str1) try: result=eval(entry.get()) entry.insert(tk.END,"="+str(result)) except: entry.insert(tk.END,"-->error") elif key=='c': entry.delete(0,tk.END) elif key=="neg": if'=' in entry.get(): entry.delte(0,tk.END) try: if entry.get()[0]=='-': entry.delte(0) else: entry.insert(0,'-') except indexerror: pass else: if"=" in entry.get(): entry.delte(0,tk.END) entry.insert(tk.END,key) root=tk.Tk() root.title('simple calculation')
  • 45. btn_list=[ '7','8','9','*','c', '4','5','6','/','**', '1','2','3','-','%', '0','.','=','+','neg'] r=1 c=0 for b in btn_list: rel='ridge' cmd=lambda x=b:click(x) tk.Button(root,text=b,width=5,relief=rel,command=cmd).grid(row=r,column=c) c+=1 if c>4: c=0 r+=1 entry=tk.Entry(root,width=33,bg="yellow") entry.grid(row=0,column=0,columnspan=5) root.mainloop()
  • 47. AIM: b) Write a program to implement the following figures using turtle. b) i) Algorithm: Step 1: Start Step 2: import the turtle module. Step 3: initialize a list with three colors and store it in list1 and i=0 Step 4: set the turtle background color as yellow and pensize as 5 Step 5: repeat the steps 6 to 10 for angle in range(0,360,30) Step 6: set the angle of turtle using seth() method Step 7: set the turtle color using color() method Step 8: draw a circle with radius of 100 using circle() method Step 9: increment i valu by 1 Step 10: if i==3 the set i value to 0. Step 11: stop Program: import turtle list1=["red","green","blue"] turtle.bgcolor("yellow") turtle.pensize(5) i=0 for angle in range(0,360,30): turtle.seth(angle) turtle.color(list1[i]) turtle.circle(100) i=i+1 if i==3:i=0 Output:
  • 48.
  • 49. b) ii) Algorithm: Step 1: Start Step 2: import the turtle module. Step 3: set the turtle color as black using color() method and pensize as 5 using pensize() method. Step 4: set the turtle speed as 10 using speed() method Step 5: repeat the steps 6 to 10 for i in range(0,180,5) Step 6: turn the turtle to left by 10 pixels using left() method Step 7: move the turtle to the forward direction by 100 pixels using forward() method Step 8: turn the turtle to left by 90 pixels using left() method Step 9: move the turtle to the forward direction by 100 pixels using forward() method Step 10: turn the turtle to left by 90 pixels using left() method Step 11: move the turtle to the forward direction by 100 pixels using forward() method Step 12: turn the turtle to left by 90 pixels using left() method Step 13: move the turtle to the forward direction by 100 pixels using forward() method Step 14: turn the turtle to left by 90 pixels using left() method Step 15: stop Program: import turtle turtle.color("black") turtle.pensize(5) turtle.speed(10) for i in range(0,180,5): turtle.left(10) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90)