Professional Documents
Culture Documents
PP Lab Manual
PP Lab Manual
PP Lab Manual
Code in C++:
#include<iostream>
main()
{
std::cout<<"Hello
world!\n";
}
Code in Python:
print("Hello world!")
! By comparing the code written in both the languages, we can say python takes less time
for coding.
How to download and install python??
Step-1: Open browser and search python download.
Step-2: There appear many sites.
Step-3: go to download python/python.org.site and click on it.
Step-4: site appears and there exists many options we can see
Step-5: Click on download python 3.6.1 according to your bit capacity of system.
Step-6: Now it will download
Step-7: It will take few minutes depending upon your connection speed.
Step-8: After downloading execute it.
Step-9: Now install python in your system.
(Set up process)
Step-10: Just wait for a minute, the process goes on….. It’s almost done.
Step-11: Then you get a message like set up was successful. Installation is performed
successfully.
Step-12: Create as a icon on your desktop. So that you can easily open it.
INTERACTIVE MODE:
Interactive mode is a command line shell which gives immediate feedback for each
statement. This mode is good way to play around and try variations on syntax. We can invoke
python interpreter using two ways:
• Command Prompt (cmd)
• Python IDLE
In Command prompt:
On windows bring up the command prompt and type “python”, that prints a welcome message
stating its version and a copyright notice as shown below
The >>> is python’s way of telling that we are in a interactive mode.A sample interactive session:
So we don’t need to use any data type, header files and etc,we can type in a single instruction,
and have the python interpreter execute it immediately. Line after the result has a REPL shell
with a cursor waiting for users other commands.
In Python IDLE:
1. Go to Start
2. Search python IDLE in search bar
3. Open it
Python IDLE window will open with welcome statements like the following fig.2:
Now it is the interactive mode of python IDLE. We can start coding right at the REPL shell.
SCRIPT MODE:
Instead of running python in interactive mode, we run it in script mode. We use script
mode when we want to execute a code which has more than one command. The code is to be run
(called a script) is entered into a file (called module).We then ask python to run a script.Script
mode also can be done in two ways.
• Command Prompt(cmd)
• Python IDLE
In command prompt:
1. Start
2. Search command prompt or type cmd
3. Open cmd
4. In cmd type python (check whether python is installed or not)
If it is installed you will get a welcome message and some information (refer fig.1)
5. Now get out of python environment through cmd by command exit().
6. So that we again come to cmd environment, here type edit filename.py or notepad filename.py
It means we are opening a file or a module in editor /notepad of some filename with .py
extension representing and indicating to OS that the file is a python script file.
7. An editor will open, thus we can write our script in editor.
When an editor /notepad is opened, it is like the following with certain options.
The following fig is an editor:
! The editor is opened with a blue screen.
! It has a tool bar
! The tool bar consists several options like: file, edit, search, view, options etc.
! At the bottom it shows in which line we are working with displaying ”Line: number”
8. Save the script(ctrl+s) written in editor/notepad and exit (ctrl+f+x).and again we come to cmd
environment.
9. Now we need to run the script.For that type the following command ,
Python filename.py (it means invoking the python interpreter to interpret the script written in
filename.py and print the result)
10. We will get the result of the interpreted script in the interactive shell.
In python IDLE:(integrated development environment)
1. Start
2. Search Python IDLE in search bar
3. Open it
4. A python interactive window will be opened.(refer fig. 2)
5. Now go to file and open new file.
A new window will be opened like this:
6. Type the script and save it before you run it.
7. Go to file and select save as to save.
8. Now go to Run and select run module.
This will executes our script code by retsarting into python IDLE shell.For example:
f=101
print(f)
def x():
f=20
print(f)
f="hai"
print(f)
x()
print(f)
OUTPUT :
Indentation Error
f=101
print(f)
def x():
f=20
print(f)
f="hai"
print(f)
x()
print(f)
OUTPUT:
101
20
hai
101
Exercise 2 – Operations
a) AIM: Write a program to compute distance between two points taking input from
the user (Pythagorean Theorem)
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 :"))
print("(x1,y1) is ({},{})".format(x1,y1))
print("(x2,y2) is ({},{})".format(x2,y2))
def distance(x1,y1,x2,y2):
d=math.sqrt((x2-x1)**2+(y2-y2)**2)
return d
k=distance(x1,y1,x2,y2)
print("the distance between two points is",k)
OUTPUT:
Enter x1 value :2
Enter y1 value :4
Enter x2 value :6
Enter y2 value :8
(x1,y1) is (2,4)
(x2,y2) is (6,8)
the distance between two points is 4.0
b) AIM: Write a program add.py that takes 2 numbers as command line arguments
and prints its sum.
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
c=a+b
print("The sum is",c)
C:\USERS\USER>python one.py 10 20
30
OUTPUT:
Enter a number :5
5
5 is odd
OUTPUT:
Enter a number :4
4
4 is even
b) AIM: Using a for loop , write a program that prints out the decimal equivalents of
1/2,1/3,1/4, . . . .1/10.
import fractions
for i in range(2,11):
x=fractions.Fraction(1,i)
print(float(x))
OUTPUT:
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
0.1111111111111111
0.1
! The above program uses fractions module which performs Fraction() operation.
! If we write the same program in c , then the source code for for statement is
for(i=0;i<x;i++)
print(1/i)
c) AIM: Write a program using a for loop that loops over a sequence. What is
sequence ?
x=[6,5,8,3,4,2,5,4,11]
sum=0
for i in x:
sum=sum+i
print(" The sum is",sum)
OUTPUT:
The sum is 48
! What is a sequence?
• Sequence is the most basic data structure in python.
• In python , sequence is the generic term for an ordered set
• Mainly , sequence in a data structure is used to organize memory efficiently.
d) AIM: Write a program using a while loop that asks the user for a number, and
prints a countdown from that number to zero.
n=int(input("Enter a number :"))
print("countdown from {} to zero is".format(n))
while n>=0 :
print(n)
n=n-1
OUTPUT:
sum=0
n=int(input("Enter a number :"))
for x in range(2,n+1):
cou=0
for i in range(2,x):
if (x%i)==0 :
cou =cou+1
break
if (cou==0) :
sum= sum+x
print("Sum of all the primes below {} is {}".format(n,sum))
OUTPUT:
Enter a number :7
Sum of all the primes below 7 is 17
b) AIM: Write a python program to find the sum of the even-valued terms.
OUTPUT:
Enetr n1 :0
Enetr n2:1
n1= 0
n2= 1
Enter how many terms :10
t= 10
0 1 1 2 3 5 8 13 21 34 Even number sum in fibonacci sequence is 44
Exercise 5-DS
a) AIM: Write a program to count the number of characters in the string and store
them in a dictionary data structure
OUTPUT:
Enter string :Good morning world
{'Good morning world': 18}
! len(): Returns the length of the string that we had mentioned str in the above program.
b) AIM: Write a program to use split and join-methods in the string and trace a
birthday with a dictionary data structure.
OUTPUT:
! The split() method breaks up a string at the specified separator and returns a list of string.
! The join() method provides a flexible way to concatenate string.
Exercise -6 DS-Continued
a) AIM: Write a program combine_list that combines these lists into a dictionary.
keys=['name','age','status ']
values=['rani',24,'married']
details=zip(keys,values)
x=dict(details)
print(x)
OUTPUT:
{'name': 'r ani', 'age': 24, 's tatus': 'm arried'}
! zip() is a built in function that takes two or more sequences and “zips” them into a pair of
keys and values in case of dictionaries.
b) AIM: Write a program to count frequency of characters in a given file.
d={}
f=open("file_1.py","r")
for i in f:
for c in i:
if c in d:
d[c]+=1
else :
d[c]=1
print("The count of frequency of characters is {}".format(d))
OUTPUT:
The count of frequency of characters is {'h ': 2, 'e': 5, 'y ': 4, ' ': 10, 'o ': 3, 'w': 1, 'a': 4, 'r ': 1, 'u ': 2, '\n': 3,
'I ': 2, 'm ': 2, 'f ': 2, 'i ': 2, 'n ': 3, 'd ': 1, 's': 1}
! “r” is the default mode of opening a file which opens the file for reading only. The file
pointer is placed at the beginning of the file.
Exercise 7- Files
a) AIM: Write a program to print each line of a file in reverse order.
f=open("file_1.py","r")
for i in f :
k=i
d=k[::-1]
print(d)
enif ma I sey
b) AIM: Write a program to compute the number of characters, words and lines in a
file.
chars=words=lines=0
f=open("file_1.py","r")
for line in f :
lines=lines+1
words+=len(line.split ())
chars+=len(line)
print("no. of lines :",lines)
print("no. of words :",words)
print("no. of characters :",chars)
no. of lines : 3
no. of words : 13
no. of characters : 48
Exercise 8 – Functions
a) AIM: 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.
import math
print("Enter information of ball 1 :")
x1=int(input("Enter x1 :"))
y1=int(input("Enter y1 :"))
r1=int(input("Enter r1 :"))
print("Enter information of ball 2 :")
x2=int(input("Enter x2 :"))
y2=int(input("Enter y2 :"))
r2=int(input("Enter r2 :"))
c1=(x1,y1,r1)
c2=(x2,y2,r2)
def c(c1,c2):
d=math.sqrt ((x2-x1)**2+(y2-y1)**2)
r=r1+r2
if (d<=r):
return True
else :
return False
print(c(c1,c2)) a
OUTPUT:
Enter information of ball 1 :
Enter x1 :1
Enter y1 :2
Enter r1 :7
Enter information of ball 2 :
Enter x2 :2
Enter y2 :58
Enter r2 :2
False
OUTPUT:
Enter information of ball 1 :
Enter x1 :2
Enter y1 :3
Enter r1 :4
Enter information of ball 2 :
Enter x2 :3
Enter y2 :2
Enter r2 :5
True
b)AIM: Find mean, median, mode for the given set of numbers in a list.
OUTPUT:
Enter number of elements in a list :3
Enetr 0 number5
Enetr 1 number2
Enetr 2 number2
[5, 2, 2]
Mean is : 3
Median is : 2
Mode is : 2
Exercise-9 functions-Continued
a) AIM: 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.
OUTPUT:
def list():
n=int(input("Enter no. of elements in a list :"))
a=[]
b=[]
for i in range(n):
a.append(int(input("enter {} number :".format(i))))
print(a)
print("Duplicates are :")
for i in range(n):
if a.count(a[i])>1 :
b.append(a[i])
print(b)
b=set(b)
print(b)
list()
OUTPUT:
Enter no. of elements in a list :5
enter 0 number :1
enter 1 number :2
enter 2 number :3
enter 3 number :2
enter 4 number :1
[1, 2, 3, 2, 1]
Duplicates are :
[1, 2, 2, 1]
{1, 2}
c) AIM: Write a function unique to find all the unique elements of a list.
OUTPUT:
OUTPUT:
b) AIM: Write a function reverse to reverse a list ,Without using the reverse function.
c)AIM: Write a function to compute gcd,lcm of two numbers. Each function should not
exceed one line.
OUTPUT:
def mat(m,n):
x=[]
for i in range(m):
k=[]
print("Enter {} row :".format(i))
for j in range(n):
k.append(int(input()))
x.append(k)
return x
def add(a,b):
c=[]
for i in range(m):
t=[]
for j in range(n):
t.append(a[i][j]+b[i][j])
c.append(t)
return c
print("Enter details of 1st matrix")
m=int(input("Enter number of rows :"))
n=int(input("Enter number of columns :"))
a=mat(m,n)
print("Enter details of 2nd matrix")
OUTPUT:
Enter details of 1st matrix
Enter number of rows :2
Enter number of columns :2
Enter 0 row :
1
2
Enter 1 row :
3
4
Enter details of 2nd matrix
Enter number of rows :2
Enter number of columns :2
Enter 0 row :
5
6
Enter 1 row :
7
8
the addition of matrices is : [[6, 8], [10, 12]]
c)AIM:Write a program to perform multiplication of twow square matrices.
def matrix(m1,n1,m2,n2):
print("Enter 1st matrix details")
for i in range(m1):
x=[]
for j in range(n1):
x.append(int(input("Enter element :")))
a.append(x)
print("enter 2nd matrix details")
for i in range(m2):
y=[]
for j in range(n2):
y.append(int(input("Enter element :")))
b.append(y)
for i in range(m1):
k=[]
for j in range(n1):
k.append(0)
c.append(k)
for i in range(len(a)):
for j in range( len(b[0])):
for k in range(len(b)):
c[i][j]+=a[i][k]*b[k][j]
return c
a=[]
b=[]
c=[]
print("Enter details of 1st matrix")
m1=int(input("Enter number of rows :"))
n1=int(input("Enter number of columns :"))
print("Enter details of 2nd matrix")
m2=int(input("Enter number of rows :"))
n2=int(input("Enter number of columns :"))
print("the resulted matrix is :",matrix(m1,n1,m2,n2))
OUTPUT:
Exercise-12-Modules
AIM: Install packages requests, flask and explore them, using pip.
Open command prompt and use the following command to install packages.
for request -
Name: requests
Version: 2.18.4
Summary: python HTTP for Humans
Home_page: http://python_requests.org
Author: Kenneth Reitz
Author_email: me@kennethreitz.org
license: Apache 2.0
location: c:\users\csertaff\appdata\local\programs\python\python 36-32\lib\ site_packages
Requires: idna,cestif,chardet,vrllib3
for flask -
Name: flask
Version: 0-12-2
Summary: A microframe work based on welezerg and good intentions
Home_page : http://github.com|parallels flask
Author: Armin Ronaches
Author_email:armin.ronaches@active_4.com
license: BSD
location: c:\users\csertaff\appdata\local\programs\python\python 36-32\lib\site_packages
Requires: click, its dangerous, jinja 2, werlezerg.
Exercise-13 OOP
a) AIM: class variables and instance variable and illustration of the self variable
i)Robot
class Robot():
def __init__(self):
print("Hi I am a Robot How can I help you")
def Query(self,question):
if(question=="what is your name"):
print("This is chitti")
elif(question=="who is your professor"):
print("Apple corp")
else :
print("your choice is wrong")
obj=Robot()
while(True):
obj.Query(input("Ask me:"))
OUTPUT:
import turtle
colors=["red","green","blue"]
pen=turtle.Turtle()
pen.speed(20)
for i in range(18):
pen.pencolor(colors[i%3])
pen.right(20)
for j in range(360):
pen.forward(1)
pen.left(1)
OUTPUT:
import turtle
pen=turtle.Turtle()
pen.speed(20)
for i in range(60):
pen.right(6)
for j in range(4):
pen.forward(100)
pen.left(90)
OUTPUT:
Exercise-15-Testing
AIM: Write a test-case to check the function even_numbers which return True on passing
a list of all even numbers.
import unittest
def even_numbers(l):
for i in l:
if(i%2==0):
return True
else:
return False
class TestEven(unittest.TestCase):
def test_even_numbers(self):
self.assertTrue(even_numbers([2,4,8]))
self.assertTrue(even_numbers([12,2]))
self.assertTrue(even_numbers([12,24,80]))
self.assertTrue(even_numbers([12,24,13]))
self.assertFalse(even_numbers([13]))
self.assertFalse(even_numbers([19,29,133]))
if __name=="__main__":
unittest.main()
OUTPUT:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
In case of failure:
import unittest
def even_numbers(l):
for i in l:
if(i%2==0):
return True
else:
return False
class TestEven(unittest.TestCase):
def test_even_numbers(self):
self.assertTrue(even_numbers([2,4,8]))
self.assertTrue(even_numbers([12,2]))
self.assertTrue(even_numbers([12,24,80]))
self.assertFalse(even_numbers([12,24,13]))
self.assertFalse(even_numbers([13]))
self.assertFalse(even_numbers([19,29,133]))
if __name=="__main__":
unittest.main()
Output:
F
=====================================================================
=
FAIL: test_even_numbers (__main__.TestEven)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\sri\Pictures\testcase.py", line 13, in test_even_numbers
self.assertFalse(even_numbers([12,24,13]))
AssertionError: True is not false
----------------------------------------------------------------------
Ran 1 test in 0.063s
FAILED (failures=1)