You are on page 1of 48

Exercise 1 – Basics

a) Running instructions in Interactive interpreter and a Python Script

1.Using Interactive Prompt:-

It is the simplest way to run the python programs. This interactive mode would be started
with DOS console and with IDE(Integrated Development Environment). The drawback of the
interactive mode is it doesn’t allow your program to save a file.

2. Using the Integrated Development Environment:-

We can run python from Graphical User Interface(GUI) environment as well .It
provides lot of menu’s like File, Edit, Shell, Debug etc.

 Click on the file and click on new file


 Type your python code
 Save the file with “.py” as extension
 The python program is simply a text file that contains python instructions
 Click on the run tab to run the program .If everything goes well, you will see results being
displayed in the python shell prompt. You will see errors otherwise

1
Output:

3. Invoking the Python Interpreter From Command Prompt:-

We can invoke from the DOS command prompt

 To use this way of execution we have to set the path as follows.


 Click on start
 Right click on my computer and select properties.
 Separate window will be open and click on advanced system settings in it.
 System properties window will be open here click on environment variables button.
 Go to the system variable window and select the path variable button
 Put(;) at the end for the variable value and type (C:\python 27) and click OK and closed all
windows
 Open the DOS command prompt and go to the directory where you have saved your files
 Type “python file_name.py” and press enter
 If everything goes well, you will see results being displayed in the python shell prompt (or)
you will see errors otherwise

2
b) Write a program to purposefully raise Indentation Error and correct it

Source code :-

3
Exercise 2- Operations

a) Write a program to compute distance between two points taking input from the
user(Pythagorean Theorem)

Source Code:-

import math

x1=int(input("enter value of x1:"))

y1=int(input("enter value of y1:"))

x2=int(input("enter value of x2:"))

y2=int(input("enter value of y2:"))

d=math.sqrt((x2-x1)**2+(y2-y1)**2)

print("the distance between two points is",d)

Output:-

enter value of x1:2


enter value of y1:3
enter value of x2:4
enter value of y2:5
the distance between two points is 2.8284271247461903

b) Write a program add.py that takes 2 numbers as command line arguments and prints its
sum.

Source Code:

import sys

s=int(sys.argv[1])+int(sys.argv[2])

print ("the sum of two no using cl is:",s)

Output:

4
5
Exercise -3 Control Flow

a) Write a Program for checking whether the given number is an even number or not.

Source Code:-

n=int(input ("enter the number:"))


if((n%2)==0):
print ("EVEN NUMBER")
else:
print ("NOT A EVEN NUMBER")

Output:-

enter the number:5

NOT A EVEN NUMBER

enter the number:10

EVEN NUMBER

b) Using a for loop ,write a program that prints out the decimal equivalents of 1/2
,1/3,1/4,…,1/10

Source code :-

i=0
for i in range(2,11):
print ("value of 1/",i,"is:",(1.0/i))

Output:-

value of 1/ 2 is: 0.5


value of 1/ 3 is: 0.3333333333333333
value of 1/ 4 is: 0.25
value of 1/ 5 is: 0.2
value of 1/ 6 is: 0.16666666666666666
value of 1/ 7 is: 0.14285714285714285
value of 1/ 8 is: 0.125
value of 1/ 9 is: 0.1111111111111111
value of 1/ 10 is: 0.1

6
c) Write a program using a for loop that loops over a sequence.What is sequence?

Source code:-

i=0
for i in "hello python":
print(i)

Output:-

d) Write a program using a while loop that asks the user for a number, and prints a countdown
from that number to zero.

Source code:-

n=int(input("Enter the number"))


while(n>=0):
print( "the value is :",n)
n=n-1

7
Output:-

8
Exercise 4 - Control Flow – Continued

a) Find the sum of all the primes below two million.


Source Code:-

s=2
i=0
j=0
for i in range(3,20,2):
for j in range(2,i):
if(i%j==0):
break
else:
print(i)
s=s+i
print ("sum of all prime numbers",s)

Output:- (sum upto 20 numbers)

Output:- (sum upto 200 numbers)

9
10
Output:- (sum upto 20000 numbers)

11
b) By considering the terms in the Fibonacci sequence whose values do not exceed four
million,find the sum of the even-valued terms.

Source Code:-

a=0
b=1
s=0
while(a<40):
print(a)
a,b=b,a+b
if(a%2==0):
s=s+a
print (“sum of even numbers in Fibonacci series :”,s)

Output:- (sum of even numbers upto 40and 400 )

Output:- (sum of evn numbers upto 4 million)

12
13
Exercise - 5 – DS

a) Write a program to count the numbers of characters in the string and store them in
dictionary data structure

Source code:

i=0
s=input("enter the string:")
k=1
print("Is it string?",s.isalpha())
l=len(s)
print("numbers of characters in string :",l)
d={1:" "}
while(i<l):
d.__setitem__(k,s[i])
i=i+1
k=k+1
print("the item of dictionary:",d)

Output:-

14
b) Write a program to use split and join methods in the string and trace a birthday with a
dictionary data structure.

Source code:

dob={"srinivas":"31 july 1998","george":"2 sep 1997","sri":"11 nov 1998"}


print("the dictionary data is :",dob)
s=input("Which person DOB you want:")
x=s.split()
for i in x:
if i in dob:
print("".join(["Birthday of ",i," is:",dob[i]]))

Output:-

15
Exercise - 6 DS – Continued

a) Write a program that combines these lists into a dictionary.

Source Code:-

sub=["OOPP","English","Physics","DENM","BEEE","ITE"]
marks=[85,96,88,75,81,92]

print("Given List are:")


print("Subject Names:",sub)
print("Marks values:",marks)

dic=dict(zip(sub,marks))
print("\n Dictionary:",dic)

Output:-
Given List are:

Subject Names: ['OOPP', 'English', 'Physics', 'DENM', 'BEEE', 'ITE']

Marks values: [85, 96, 88, 75, 81, 92]

Dictionary: {'OOPP': 85, 'English': 96, 'Physics': 88, 'DENM': 75, 'BEEE': 81, 'ITE': 92}

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?

Source Code:-

filetypes=['.py','.c','.txt']
fn=input("Enter the file name:")
f=open(fn,"r") #opening a file
print("Given file is:",end='\t')
for ft in filetypes:
if(ft in fn):
if(ft==".py"):
print("Python File")
elif(ft==".c"):
print("C File")
elif(ft==".txt"):
print("Text File")
st=f.read()
print("The file content is ",st)
s=set(st) #removes the duplicate characters
i=[]
for x in s:
count=0

16
for y in st:
if(x==y):
count=count+1
i.append(count)
print("The set contents are:",s)
print("The frequency table is:",i)
print("The character frequency is:",list(zip(s,i)))

Output:-

17
Exercise - 7 Files

a) Write a program to print each line of a file in reverse order.

Source code :-

f=open("first.txt","r") #reading content from file object


st=f.read()
print("the file content is:\n",st) #printing content on screen
lines=st.splitlines() #lines is a list
for x in lines:
print(x[ : : -1])

Output:-

b) Write a program to compute the number of characters, words and lines in a file.

Source code :-

f=open("first.txt","r")
st=f.read() #reading content from file object
print("The content of file :",st)
n=len(st)
print("the no. of characters in string :",n)
words=st.split()
wc=len(words)
print("the no. of words in string:",wc)
lines=st.splitlines()
lc=len(lines)
print("the no. of lines in string:",lc)

18
Output:-

19
Exercise - 8 Functions

a) Write a function ball_collide 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

Source code :-

import math
def ball_collide(t1,t2):
d=math.sqrt((x2-x1)**2+(y2-y1)**2)
r=r1+r2
print("centroid distance of two balls is:",d)
print("Sum of radius of two balls is:",r)
if(d<=r):
return True
else:
return False
x1=int(input("enter the value of x1:"))
y1=int(input("enter the value of y1:"))
x2=int(input("enter the value of x2:"))
y2=int(input("enter the value of y2:"))
r1=int(input("enter the value of r1:"))
r2=int(input("enter the value of r2:"))
t1=(x1,y1,r1)
t2=(x2,y2,r2)
if ball_collide(t1,t2):
print("balls are collide")
else:
print("the balls do not collide")

Output:-

20
b) Find mean, median, mode for the given set of numbers in a list.

Source code :-

#To calculate mean


def mean(l):
add=0
for x in range(0,a):
add=add+l[x]
mean=add/a
print("mean of the given list is ",mean)
#to calculate median
def median(l):
l.sort()
print("sorted order of list :",l)
if(a%2==0):
n1=a//2
n2=n1-1
md=(l[n1]+l[n2])/2
print("median is",md)
else:

21
n=a//2
print("median is",l[n])
#calculate mode
def mode(l):
for x in l:
l1.append(l.count(x))
m=max(l1)
print("mode is",l[l1.index(m)])
#read size and elements into list
l=[]
l1=[]
i=0
m=int(input("Enter the size of the list:"))
while(i<m):
l.append(int(input("enter the element:")))
i=i+1
print("the list contains:",l)
a=len(l)
mean(l)
median(l)
mode(l)

Output:-

Enter the size of the list:4

enter the element:1

enter the element:2

enter the element:3

enter the element:4

the list contains: [1, 2, 3, 4]

mean of the given list is 2.5

sorted order of list : [1, 2, 3, 4]

median is 2.5

mode is 1

22
Exercise - 9 Functions – Continued

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.
Source code :-

def nearly_equal(s1,s2):
count=0
i=j=0
while(i<len(s1)and j<len(s2)):
if(s1[i]!=s2[j]):
count+=1
if(count>1):
return False
i+=1
j+=1
if(count<2):
return True
s1=input("enter string1:")
s2=input("enter string2:")
if(nearly_equal(s1,s2)):
print("Strings are nearly Equal")
else:
print("Strings are NOT Equal")

Output:-

enter string1:Engineering

enter string2:Engg

Strings are nearly Equal

enter string1:Engineering

enter string2:English

Strings are NOT Equal

23
b) Write a function dups to find all duplicates in the list.

Source code :-

def dups(list):
temp=[]
for x in list:
if(list.count(x)>1):
temp.append(x)
s=set(temp)
print("the duplicate values:",s)
#read the size of list and read the elements
list=[]
i=0
m=int((input("enter size of list:")))
while(i<m):
list.append(int(input("enter element:")))
i=i+1
print("the list contain:",list)
dups(list)

Output:-

enter size of list:5


enter element:1
enter element:5
enter element:2
enter element:4
enter element:2

the list contain: [1, 5, 2, 2, 5]


the duplicate values: {2, 5}

24
b) Write a function unique to find all the unique elements of a list.

Source code :-

def unquie(list):
temp=[]
for x in list:
if(list.count(x)==1):
temp.append(x)
print("the unqiue elements are :",temp)
#read the size of list and read the elements
list=[]
i=0
m=int(input("enter size of list:"))
while(i<m):
list.append(int(input("enter element:")))
i=i+1
print("the list contain:",list)
#function call
unquie(list)

Output:-

enter size of list:5

enter element:1

enter element:5

enter element:2

enter element:3

enter element:5

the list contain: [1, 5, 2, 3, 5]

the unqiue elements are : [1, 2, 3]

25
Exercise - 10 - Functions - Problem Solving

a. Write a function cumulative_product to compute cumulative product of a list of


numbers.

Source Code:-

n=int(input("Enter the size of list: "))


num=[]
for x in range(0,n):
num.append(int(input("Enter the elemet")))
#cumulative product
def prod(num):
p=1
for x in num:
p=p*x
return(p)
s=prod(num) #function call
print("The Cumulative product of list is:",s)

Output:

Enter the size of list: 4


Enter the elemet2
Enter the elemet3
Enter the elemet4
Enter the elemet5
The Cumulative product of list is: 120

b. Write a function reverse to reverse a list. Without using the reverse function.

Source Code:-

n=int(input("Enter the size of list: "))


num=[]
for x in range(0,n):
num.append(int(input("Enter the element:")))
print("The lis before reversing is:",num)
i=0
def rev(num):
temp=[]
c=n
while(c>=1):
temp.append(num[c-1])
c=c-1

26
print("The elements after reversing are:",temp)
#function call
rev(num)

Output:
Enter the size of list: 5
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
Enter the element:5
The lis before reversing is: [1, 2, 3, 4, 5]
The elements after reversing are: [5, 4, 3, 2, 1]

c. Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed
one line.

Source Code:-

n1=int(input("Enter n1:"))
n2=int(input("Enter n2:"))
def gcd(a,b):
if a==b:
print("The GCD is:",a)
return a
elif a>b:
return(gcd(a-b,b))
else:
return(gcd(a,b-a))
def lcm(a,b):
return((a*b)/gcd(a,b))
res=lcm(n1,n2)
print("The LCM is:",res)

Output::

Enter n1:9
Enter n2:21
The GCD is: 3
The LCM is: 63.0

27
Exercise 11 - Multi-D Lists

a) Write a program that defines a matrix and prints

Source code :-

rows=int(input("Enter row size of Matrix:"))

cols=int(input("Enter column size of Matrix:"))

matrix=[[int(input("Enter [%d%d]value:"%(i,j))) for j in range(cols)] for i in range(rows)]

print("Matrix is:")

for i in range(rows):

for j in range(cols):

print(matrix[i][j],end='\t')

print()

Output:-

Enter row size of Matrix:2


Enter column size of Matrix:2
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2
3 4

28
b) Write a program to perform addition of two square matrices

Source code :-

rows=int(input("Enter row size of Matrix:"))

cols=int(input("Enter column size of Matrix:"))

matA=[[int(input("Enter [%d%d]value:"%(i,j))) for j in range(cols)] for i in


range(rows)]

print("Matrix is:")

for i in range(rows):

for j in range(cols):

print(matA[i][j],end='\t')

print()

matB=[[int(input("Enter [%d%d]value:"%(i,j))) for j in range(cols)] for i in


range(rows)]

print("Matrix is:")

for i in range(rows):

for j in range(cols):

print(matB[i][j],end='\t')

print()

res=[[matA[i][j]+matB[i][j] for j in range(cols)] for i in range(rows)]

#printing the matrix

for x in res:

print(x)

Output:-

Enter row size of Matrix:2


Enter column size of Matrix:2
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2

29
3 4
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2
3 4
[2, 4]
[6, 8]

c) Write a program to perform multiplication of two square matrices


Source code :-

rows=int(input("Enter row size of Matrix:"))


cols=int(input("Enter column size of Matrix:"))
matA=[[int(input("Enter [%d%d]value:"%(i,j))) for j in range(cols)] for i in
range(rows)]
print("Matrix is:")
for i in range(rows):
for j in range(cols):
print(matA[i][j],end='\t')
print()

matB=[[int(input("Enter [%d%d]value:"%(i,j))) for j in range(cols)] for i in


range(rows)]
print("Matrix is:")
for i in range(rows):
for j in range(cols):
print(matB[i][j],end='\t')
print()
res=[[0 for j in range(cols)] for i in range(rows)]
for i in range(rows):
for j in range(cols):
for k in range(cols):
res[i][j]+=matA[i][k]*matB[k][j]
#printing the matrix
for x in res:
print(x)

30
Output:-
Enter row size of Matrix:2
Enter column size of Matrix:2
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2
3 4
Enter [00]value:1
Enter [01]value:2
Enter [10]value:3
Enter [11]value:4
Matrix is:
1 2
3 4
[7, 10]
[15, 22]

31
Exercise - 12 – Modules

a) Install packages requests, flask and explore them. using (pip)

steps:

1. Open the cmd prompt


2. Select AppData folder
3. Select Local folder
4. Select Programs folder
5. Select Python folder
6. Select Python 39
7. Select Scripts folder
As shown below

Installing requests:

 To install request package do the following step


pip install requests as shown below

32
 To see the contains about the packages type the following

pip show requests

 To uninstall the packages do the following

pip uninstall requests

33
Installing flask:

 To install flask package do the following steps

pip install flask

 To see the contains about the flask package type the following

34
pip show flask

 to uninstall the package do the following

pip uninstall flask

35
b) Write a script that imports requests and fetch content from the page. Eg. (Wiki)

Source code :-

import requests
req= requests.get("http://www.yahoo.com")
print("status code is:",req.status_code)
print("the URL is :",req.url)
print("the content type Header is:",req.headers['content-type'])
print("the non-textual content is:",req.content)
print("the text content is:",req.text)
print("the history is:",req.history)

Output:-

c) Write a simple script that serves a simple HTTP Response and a simple HTML
Page

Source code :-

from flask import Flask,render_template


app=Flask(__name__)
print(app)
@app.route('/') #Decrote to specify function

def main():
return render_template("login.html")
if __name__== "__main__":
app.run(host= "127.0.0.1",port=2500) #used the application

36
Output:-

37
Exercise - 13 OOP

i) Robot
ii) ATM Machine

a) Class variables and instance variable

Source code :-

class bankaccount:
balance=0
def deposit(self,d):
bankaccount.balance+=d
def withdrawal(self,w):
if(bankaccount.balance>=0):
print("withdrawal is successful")
bankaccount.balance-=w
else:
print("insufficient balance in your account")
def balenq(self):
print ("Balance is :",bankaccount.balance)
#creating objects
atm1=bankaccount()
atm2=bankaccount()
atm3=bankaccount()
#function call
atm1.deposit(float(input("enter amount to be deposit:")))
atm1.balenq()
atm2.withdrawal(float(input("enter amount to be withdraw:")))
atm2.balenq()
atm3.withdrawal(float(input("enter amount to be withdraw:")))
atm3.balenq()

Output:-
enter amount to be deposit:10000
Balance is : 10000.0
enter amount to be withdraw:5000
withdrawal is successful
Balance is : 5000.0
enter amount to be withdraw:2500
withdrawal is successful
Balance is : 2500.0

38
Instance variable version

class bankaccount:
balance=0
def deposit(self,d):
self.balance+=d
def withdrawal(self,w):
if(self.balance>=w):
print("withdrawal is successful")
self.balance-=w
else:
print("insufficient balance in your account")
def balenq(self):
print ("Balance is :",self.balance)
#creating objects
atm1=bankaccount()
atm2=bankaccount()
atm3=bankaccount()
#function call
atm1.deposit(float(input("enter amount to be deposit:")))
atm1.balenq()
atm2.withdrawal(float(input("enter amount to be withdraw:")))
atm2.balenq()
atm3.withdrawal(float(input("enter amount to be withdraw:")))
atm3.balenq()

Output:-

enter amount to be deposit:50000


Balance is : 50000.0
enter amount to be withdraw:10000
insufficient balance in your account
Balance is : 0
enter amount to be withdraw:1000
insufficient balance in your account
Balance is : 0

39
Robot

Class variable version

class robot:
rbno=5
def __init__(self,name):
self.name=name
robot.rbno+=1
def disp(self):
print("the robot name is:",self.name)
print("no. of robot created:",robot.rbno)
def killrobot(self):
robot.rbno-=1
r1=robot("srinu")
r2=robot("george")
r3=robot("vinay")
r1.disp()
r2.disp()
r3.disp()
r1.killrobot()
r1.disp()
r2.killrobot()
r2.disp()
r3.killrobot()
r3.disp()
Output:-

the robot name is: srinu


no. of robot created: 4
the robot name is: george
no. of robot created: 4
the robot name is: vinay
no. of robot created: 4
the robot name is: srinu
no. of robot created: 3
the robot name is: george
no. of robot created: 2
the robot name is: vinay
no. of robot created: 1

40
Instance variable version

class robot:
rbno=0
def __init__(self,name):
self.name=name
self.rbno+=1
def disp(self):
print"the robot name is:",self.name
print"no. of robot created:",self.rbno
def killrobot(self):
self.rbno-=1
print"starting with 5 robots"
r1=robot("srinu")
r2=robot("george")
r3=robot("vinay")
r1.disp()
r2.disp()
r3.disp()
r1.killrobot()
r1.disp()
r2.killrobot()
r2.disp()
r3.killrobot()
r3.disp()

Output:-

41
42
Exercise - 14 GUI, Graphics

a. Write a GUI for an Expression Calculator using tk

Source code :-

from tkinter import*


root=Tk()
root.title('calculator')
def printadd():
x=float(t1.get())
y=float(t2.get())
s1=x+y
s=str(s1)
res=Label(root,text='Result is :'+s)
res.config(font=('calbri',30,'italic'),bg='pink',fg='green')
res.grid(row=4,column=0)
def printsub():
x=float(t1.get())
y=float(t2.get())
s1=x-y
s=str(s1)
res=Label(root,text='Result is :'+s)
res.config(font=('calbri',30,'italic'),bg='pink',fg='green')
res.grid(row=4,column=0)
def printmul():
x=float(t1.get())
y=float(t2.get())
s1=x*y
s=str(s1)
res=Label(root,text='Result is :'+s)
res.config(font=('calbri',30,'italic'),bg='pink',fg='green')
res.grid(row=4,column=0)
def printdiv():
x=float(t1.get())
y=float(t2.get())
s1=x/y
s=str(s1)
res=Label(root,text='Result is :'+s)
res.config(font=('calbri',30,'italic'),bg='pink',fg='green')
res.grid(row=4,column=0)
def printmulodiv():
x=float(t1.get())
y=float(t2.get())
s1=x%y

43
s=str(s1)
res=Label(root,text='Result is :'+s)
res.config(font=('calbri',30,'italic'),bg='pink',fg='green')
res.grid(row=4,column=0)
#creating the widgets
l=Label(root,text='simple calculator')
l.config(font=('calbri',30,'italic'),bg='cyan',fg='red')
l1=Label(root,text='First Number')
l2=Label(root,text='Second Number')
t1=Entry(root,width=8)
t2=Entry(root,width=8)
a=Button(root,text='+',command=printadd)
s=Button(root,text='-',command=printsub)
m=Button(root,text='*',command=printmul)
d=Button(root,text='/',command=printdiv)
md=Button(root,text='%',command=printmulodiv)
#attaching the widgets to window
l.grid(row=0,column=0)
l1.grid(row=1,column=0)
t1.grid(row=1,column=1)
l2.grid(row=2,column=0)
t2.grid(row=2,column=1)
a.grid(row=3,column=2)
s.grid(row=3,column=3)
m.grid(row=3,column=4)
d.grid(row=3,column=5)
md.grid(row=3,column=6)

Output:-

44
45
b. Write a program to implement the following figures using turtle

Source code :-

import turtle
turtle.bgcolor('white')
turtle.pensize(3)
c=['purple','blue','green','black']

for a in range(0,360,20):
if a>=0 and a<=90:
turtle.color(c[0])
turtle.circle(100)
turtle.seth(a)
if a>90 and a<=180:
turtle.color(c[1])
turtle.circle(100)
turtle.seth(a)
if a>180 and a<=270:
turtle.color(c[2])
turtle.circle(100)
turtle.seth(a)
if a>270 and a<=360:
turtle.color(c[3])
turtle.circle(100)
turtle.seth(a)

46
Output:-

Source code :-

import turtle
turtle.bgcolor('black')
turtle.color('white')
l=[90,90,90,90]
for x in range(0,360,10):
for a in l:
turtle.forward(100)
turtle.left(a)
turtle.seth(x)

47
Output:-

-------------------------------> THE END <----------------------------

48

You might also like