6CS4 23 Python Manual
6CS4 23 Python Manual
6CS4 23 Python Manual
3 Lab PEO
4 LAB Plan
Write a program to compute distance between two points taking input from the
user.
Write a program add.py that takes 2 numbers as command line arguments and perform their
Exp:- 2
sum.
Sample Viva Question
Write a program for checking whether the given number is an even number or not.
Exp:- 3 Using for loop,write a program that prints out the decimal equivalent of ½+1/3…..1/n
Exp:- 5 By considering the terms in the Fibonacci sequence whose values do not exceed four
million,WAP to find the sum of the even numbers in sequence.
Sample Viva Question
Write a program to count the numbers of characters in the string and store them in a dictionary
data structure.
Exp:- 6 Write a program to use split and join methods in the string and trace a birthday of a person
with dictionary data structure.
Sample Viva Question
Write a program to count frequency of characters in a given file,Can you use character
Exp:- 7 frequency to tell whether the given file is a Python program file,C program file or a text file?
Sample Viva Question
Exp:- 8 Write a program to compute the number of characters, words and lines in a file.
Exp:-9 Write a function early equal to test whether two strings are nearly equal .Two strings a and b
are nearly equal when a can be
Write function to compute gcd,lcm of two numbers.Each function shouldn’t be exceed one
line.
Sample Viva Question
Write a program to implement Merge sort.
1. Student should get the record of previous experiment checked before starting the new
experiment.
2. Read the manual carefully before starting the experiment.
3. Turn off the computer before leaving the lab unless a member of lab staff has specifically
told you not to do so
4. Before switching on the power supply, get the circuit connections checked.
5. Get your outputs checked by the teacher.
6. PC and Apparatus must be handled carefully.
7. Maintain strict discipline.
8. Keep your mobile phone switched off or in vibration mode.
9. Students should get the experiment allotted for next turn, before leaving the lab.
DONT’S
1. Don’t use internet, internet chat of any kind in your regular lab schedule.
2. Do not download or upload of MP3, JPG or MPEG files.
3. No games are allowed in the lab sessions
4. No hardware including USB drives can be connected or disconnected in the
labs without prior permission of the lab in-charge.
5. Do not leave the lab without permission from the teacher.
6. If you are having problems or questions,please go to either the faculty,lab in-
charge or the supporting staff.They will help you.We need your full support
and cooperation for smooth functioning of the lab.
LIST OF PROGRAMS
S. NO. TITLE
2 A)Write a program to compute distance between two points taking input from the user
B) Write a program add.py that takes 2 numbers as command line arguments and prints
its sum..
3 A)Write a Program for checking whether the given number is an even number or not.
B)Using a for loop, write a program that prints out the decimal equivalents of
1/2, 1/3, 1/4, . . . , 1/10
A) Write a Program to demonstrate list and tuple in python.
4 B Write a program using a for loop that loops over a sequence.
C) Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero..
A)Find the sum of all the primes below two million.
5 B)By considering the terms in the Fibonacci sequence whose values do not
exceed four million, WAP to find the sum of the even-valued terms..
A)Write a program to count the numbers of characters in the string and store
6 them in a dictionary data structure.
B)Write a program to use split and join methods in the string and trace a
Birth day of a person with a dictionary data structure
Write a program to count frequency of characters in a given file. Can you use character
7 frequency to tell whether the given file is a Python program file, C program file or a
text file?
A)Write a program to print each line of a file in reverse order.
8 B)Write a program to compute the number of characters, words and lines in a file.
A)Write a function nearly equal to test whether two strings are nearly equal. Two
9 strings a and b are nearly equal when a can be generated by a single mutation on.
B)Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed
one line.
A)Write a program to implement Merge sort.
10 B)Write a program to implement Selection sort, Insertion sort.
Course Outcomes
COs Statements
CO3 Describe python programs that appropriately utilize built-in functions and
control flow statements
COs
POs PSOs
PSO-1
PSO-2
PSO-3
PO-10
PO-11
PO-12
PO-1
PO-2
PO-3
PO-4
PO-5
PO-6
PO-8
PO-9
PO7
CO1 2 2 2 2 2 - - - - - - - 2 2 2
CO2 2 3 3 2 2 - - - - - - - 2 2 2
CO3 2 2 2 2 2 - - - - - - - 2 2 2
CO4 2 2 2 2 2 - - - - - - - 2 2 2
CO5 2 2 2 2 2 - - - - - - - 2 2 2
Program No.1
Aim:-
Description:-
Every value in Python has a data type. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.
Source Code:-
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output:-
Aim:-
Write a program to compute distance between two points taking input from the user
Description:-
Arithmetic operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.
Relational Operators: Relational operators compares the values. It either returns True or False
according to the condition.
Logical operators: Logical operators perform Logical AND, Logical OR and Logical NOT
operations.
Source Code:
Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
Assignment operators: Assignment operators are used to assign values to the variables.
• Identity operators-
is and is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal does not imply that they are
identical.
• Membership operators-
in and not in are the membership operators; used to test whether a value or variable is in
a sequence.
Source Code:-
import math
# Calculating distance
return math.sqrt(math.pow(x2 - x1, 2) +
math.pow(y2 - y1, 2) * 1.0)
# Drivers Code
print("%.6f"%distance(3, 4, 4, 3))
Output:-
1.414214
Aim:-
Write a program add.py that takes 2 numbers as command line arguments and prints its sum.
Source Code:-
Output:
Q.5. How will you check if all characters in a string are alphanumeric?
Q.7. We know Python is all the rage these days. But to be truly accepting of a great
technology, you must know its pitfalls as well. Would you like to talk about this?
Q.8. With Python, how do you find out which directory you are currently in?
Program No.3
Aim
Write a Program for checking whether the given number is an even number or not.
Description:
The if Statement
Often, you need to execute some statements only if some condition holds, or choose statements
to execute depending on several mutually exclusive conditions. The Python compound statement
if, which uses if, elif, and else clauses.
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
The elif and else clauses are optional. Note that unlike some languages, Python does not have a
switch statement, so you must use if, elif, and else for all conditional processing.
Source Code:
Output:
Enter a number: 2
2 is Even
Aim:
Using a for loop, write a program that prints out the decimal equivalents of
½+1/3+1/4+. . . , 1/10
Description:
Source Code:
Output:
Enter the number of terms: 2
The sum of series is 0.5
VIVA QUESTIONS
Q.7. Will the do-while loop work if you don’t end it with a semicolon?
Q.8. In one line, show us how you’ll get the max alphabetical character from a string.
Experiment-4
Aim:
Write a Program to demonstrate list and tuple in python.
Description:
Lists are one of the most powerful tools in python. They are just like the arrays declared in other
languages. But the most powerful thing is that list need not be always homogenous. A single list
can contain strings, integers, as well as objects. Lists can also be used for implementing stacks
and queues. Lists are mutable, i.e., they can be altered once declared.
A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception
that tuples cannot be changed once declared. Tuples are usually faster than lists.
Source Code:
L = [1, "a" , "string" , 1+2]
print L
L.append(6)
print L
L.pop()
print L
print L[1]
The output is :
The output is :
Aim:
Write a program using a for loop that loops over a sequence.
Source Code:
str="i am python developer"
for i in str:
print(i)
Output:
i
a
m
p
y
t
h
o
n
d
e
v
e
l
o
p
e
r
Aim:
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 A Number--->"));
while n >=0:
print (n);
n = n - 1;
Output:
Enter A Number--->3
3
2
1
0
VIVA QUESTIONS
Q.2. Can you name ten built-in functions in Python and explain each in brief?
Source Code:
def eratosthenes2(n):
#Declare a set - an unordered collection of unique elements
multiples = set()
#Yay prime!
yield i
#Now sum it up
iter = 0
ml = list(eratosthenes2(2000000))
for x in ml:
iter = int(x) + iter
print(iter)
Output:
142913828922
Aim:
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
WAP to find the sum of the even-valued terms.
Source Code:
prev, cur = 0, 1
total = 0
while True:
prev, cur = cur, prev + cur
if cur >= 4000000:
break
if cur % 2 == 0:
total += cur
print(total)
Output
4613732
VIVA QUESTIONS
Write a program to count the numbers of characters in the string and store
them in a dictionary data structure
Source Code:
str=input("Enter a String:")
dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)
OR
str=input("Enter a String")
dict = {}
for i in str:
dict[i] = str.count(i)
print (dict)
OR
str=input("Enter a String")
dist={}
L=len(str);
d={str:L};
print(d)
Output:
Enter a Stringhello how are you
{'r': 1, 'l': 2, 'w': 1, 'u': 1, ' ': 3, 'a': 1, 'h': 2, 'e': 2, 'o': 3, 'y': 1}
Aim:
Write a program to use split and join methods in the string and trace a birthday of a person with a
dictionary data structure
Source Code:
pen='+'
pin=['H','E','L','L','O']
print("Joining")
print(pen.join(pin))
c=pen.join(pin)
print("Splitting")
print(c.split('+'))
people={
'Netaji':{
'birthday':'Aug 15'
},
'Manaswi':{
'birthday':'Mar 21'
},
'Chandrika':{
'birthday':'July 7'
}
}
labels={
'birthday':'birth date'
}
name=input("Name:")
request=input('birthday(b)?')
if request=='b':
key='birthday'
if name in people:
print("%s's %s is %s." % (name, labels[key], people[name][key]))Output:
Joining
H+E+L+L+O
Splitting
['H', 'E', 'L', 'L', 'O']
Name:Netaji
birthday(b)?b
Netaji's birth date is Aug 15.
VIVA QUESTIONS
Aim:
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:
import os
count =0
file=open("D:/a.txt")
for line in file:
for l in range(0,len(line)):
count+=1;
print("count:",count)
filename,file_extension=os.path.splitext("D:/a.txt");
print("file_extension==",file_extension);
if(file_extension=='.py'):
print("its python program file");
elif(file_extension==".txt"):
print("its a txt file");
elif(file_==extension==".c"):
print("its a c program file");
VIVA QUESTIONS
Q.3. Write code to print everything in the string except the spaces.
Q.7. Create a new list to convert the following list of number strings to a list of numbers.
Q.8. Given the first and last names of all employees in your firm, what data type will you
use to store it?
Experiment-8
Aim:
Source Code:
input_file=open('D:/a.txt','r')
for line in input_file:
l=len(line)
s=' '
while(l>=1):
s=s+line[l-1]
l=l-1
print(s)
input_file.close()
Aim:
Source Code:
k=open('D:/a.txt','r')
char,wc,lc=0,0,0
for line in k:
for k in range(0,len(line)):
char +=1
if(line[k]==' '):
wc+=1
if(line[k]=='\n'):
wc,lc=wc+1,lc+1
print("The no.of chars is %d\n The no.of words is %d\n The
no.of lines is %d"%(char,wc,lc))
VIVA QUESTIONS
Q.1. How would you work with numbers other than those in the decimal number system?
Q.6. What is the best code you can write to swap two numbers?
Q.8. If you are ever stuck in an infinite loop, how will you break out of it?
Experiment-9
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.
Source Code:
Output:
Both Strings are similar
a is mutation on b
Aim:
Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed one line.
Source Code:
import fractions
n1 = int(input("Enter n1 value:"))
n2 = int(input("Enter n2 value:"))
gcd = fractions.gcd(n1, n2)
print("GCD value is:",gcd)
def lcm(n, m):
return n * m / gcd
print("LCM value is:",int(lcm(n1,n2)))
Output:
Enter n1 value:6
Enter n2 value:12
GCD value is: 6
LCM value is: 12
VIVA QUESTIONS
Source Code:
i=j=k=0
Output:
Given array is
12 11 13 5 6 7
Sorted array is:
5 6 7 11 12 13
Aim:
Source Code:
# Python program for implementation of Selection
# Sort
import sys
A = [64, 25, 12, 22, 11]
Output:
Sorted array
11
12
22
25
64
Source Code:
key = arr[i]
Output:
Q.8. If given the first and last names of bunch of employees how would you store it and
what datatype?