Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

6CS4 23 Python Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

LAB MANUAL

Subject Name : PYTHON LAB


Subject Code : 6CS4-23
Branch : Computer Science Engineering
Year : III Year/ VI Semester

Arya Group of Colleges


Department of Computer Science & Engineering
(Rajasthan Technical University, KOTA)
S.NO CONTENTS Page
1 Syllabus

2 Do’s and Don’t’s

3 Lab PEO

4 LAB Plan

Experiment as per RTU syllabus


Write a program to demonstrate basic data type in python.
Exp:- 1
Sample Viva Question

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

Sample Viva Question

Write a program to demonstrate list and tuple in python.

Write a program using a for loop that loops over a sequence.


Exp:- 4
Write a program using a while loop that asks the user for a number,and prints a countdown
from that number to zero.
Sample Viva Question

Find the sum of all primes below two million.

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

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

Exp:- 8 Write a program to compute the number of characters, words and lines in a file.

Sample Viva Question

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.

Exp:-10 Write a program to implement Selection Sort, Insertion Sort.

Sample Viva Question


DO’S AND DONT’S
DO’S

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

1 Write a program to demonstrate basic data type in python..

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

CO1 Understand and develop Computational Thinking concepts.

CO2 Express a problem-solving strategy to breakdown a complex problem into a


series of simpler tasks.

CO3 Describe python programs that appropriately utilize built-in functions and
control flow statements

CO4 Use functions for structuring Python programs.

CO5 Represent compound data using Python lists, tuples, dictionaries

List of Program Outcomes


Engineering Knowledge: Apply knowledge of mathematics and science,
PO-1 with fundamentals of Computer Science & Engineering to be able to solve
complex engineering problems related to CSE.
Problem Analysis: Identify, Formulate, review research literature and
analyze complex engineering problems related to CSE and reaching
PO-2
substantiated conclusions using first principles of mathematics, natural
sciences and engineering sciences.
Design/Development of solutions: Design solutions for complex engineering
problems related to CSE and design system components or processes that
PO-3
meet the specified needs with appropriate consideration for the public health
and safety and the cultural societal and environmental considerations.
Conduct Investigations of Complex problems: Use research–based
knowledge and research methods including design of experiments, analysis
PO-4
and interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern Tool Usage: Create, Select and apply appropriate techniques,
resources and modern engineering and IT tools including prediction and
PO-5
modeling to computer science related complex engineering activities with an
understanding of the limitations.
The Engineer and Society: Apply Reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
PO-6
consequent responsibilities relevant to the CSE professional engineering
practice.
Environment and Sustainability: Understand the impact of the CSE
PO-7 professional engineering solutions in societal and environmental contexts and
demonstrate the knowledge of, and need for sustainable development.
Ethics: Apply Ethical Principles and commit to professional ethics and
Responsibilities and norms of the engineering practice.
PO-8

PO-9 Individual and Team Work: Function effectively as an individual and as a


member or leader in diverse teams and in multidisciplinary Settings.

PO-10 Communication: Communicate effectively on complex engineering activities


with the engineering community and with society at large such as able to
comprehend and with write effective reports and design documentation, make
effective presentations and give and receive clear instructions
PO-11 Project Management and Finance: Demonstrate knowledge and
understanding of the engineering management principles and apply these to
one’s own work, as a member and leader in a team, to manage projects and in
multi disciplinary environments
PO-12 Life-Long Learning: Recognize the need for and have the preparation and
ability to engage in independent and life-long learning the broadest context of
technological change.

Course Articulation Matrix (CO-PO Mapping)

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:-

Write a program to demonstrate basic data type in python.

Description:-

Data types in Python

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:-

5 is of type <class 'int'>


2.0 is of type <class 'float'>
(1+2j) is complex number? True
VIVA QUESTIONS

Q.1. What are the key features of Python?

Q.2. Differentiate between lists and tuples.

Q.3. Explain the ternary operator in Python.

Q.4. What are negative indices?

Q.5. Is Python case-sensitive?

Q.6. How long can an identifier be in Python?

Q.7. How would you convert a string into lowercase?

Q.8. What is the pass statement in Python?


Program No.2

Aim:-

Write a program to compute distance between two points taking input from the user

Description:-

Basic Operators in Python

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.

Special operators: There are some special type of operators like-

• 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:-

# Python3 program to calculate


# distance between two points

import math

# Function to calculate distance


def distance(x1 , y1 , x2 , y2):

# 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:-

# Store input numbers


num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output:

Enter first number: 5


Enter second number: 88
The sum of 5 and 88 is 93.0
VIVA QUESTIONS

Q.1. Explain help() and dir() functions in Python

Q.2. How do you get a list of all the keys in a dictionary?

Q.3. What is slicing?

Q.4. How would you declare a comment in Python?

Q.5. How will you check if all characters in a string are alphanumeric?

Q.6. How will you capitalize the first letter of a string?

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:

Control Flow Statements


A program’s control flow is the order in which the program’s code executes. The control flow of
a Python program is regulated by conditional statements, loops, and function calls.

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.

Here’s the syntax for the if statement:

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:

# Python program to check if the input number is odd or even.


# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

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:

The for Statement


The for statement in Python supports repeated execution of a statement or block of statements
that is controlled by an iterable expression. Here’s the syntax for the for statement:
for target in iterable:
statement(s)
Note that the in keyword is part of the syntax of the for statement and is functionally unrelated to
the in operator used for membership testing. A for statement can also include an else clause and
break and continue statements

Source Code:

n=int(input("Enter the number of terms: "))


sum1=0
for i in range(2,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))

Output:
Enter the number of terms: 2
The sum of series is 0.5
VIVA QUESTIONS

Q.1. How do you insert an object at a given index in Python?

Q.2. How do you reverse a list?

Q.3. What is the Python interpreter prompt?

Q.4. How does a function return values?

Q.5. How would you define a block in Python?

Q.6. Why do we need break and continue in Python?

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 :

[1, 'a', 'string', 3]


[1, 'a', 'string', 3, 6]
[1, 'a', 'string', 3]
a

tup = (1, "a", "string", 1+2)


print tup
print tup[1]

The output is :

(1, 'a', 'string', 3)


a

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.1. What is Python good for?

Q.2. Can you name ten built-in functions in Python and explain each in brief?

Q.3. What will the following code output?

Q.4. How will you convert a list into a string?

Q.5. How will you remove a duplicate element from a list?

Q.6. Can you explain the life cycle of a thread?

Q.7. Explain the //, %, and ** operators in Python.


Experiment-5
Aim:

Find the sum of all the primes below two million.

Source Code:

def eratosthenes2(n):
#Declare a set - an unordered collection of unique elements
multiples = set()

#Iterate through [2,2000000]


for i in range(2, n+1):

#If i has not been eliminated already


if i not in multiples:

#Yay prime!
yield i

#Add multiples of the prime in the range to the 'invalid' set


multiples.update(range(i*i, n+1, 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

Q.1. What do you know about relational operators in Python.

Q.2. What are assignment operators in Python?

Q.3. Explain logical operators in Python?

Q.4. What are membership operators?

Q.5. Explain identity operators in Python?

Q.6. Finally, tell us about bitwise operators in Python.

Q.7. What data types does Python support?

Q.8. What is a docstring?


Experiment-6
Aim:

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

Q.1. How would you convert a string into an int in Python?

Q.2. How do you take input in Python?

Q.3. What is a function?

Q.4. What is recursion?

Q.5. What does the function zip() do?

Q.6. How do you calculate the length of a string?

Q.7. Explain Python List Comprehension.

Q.8. How do you get all values from a Python dictionary?


Experiment-7

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.1. What if you want to toggle case for a Python string?

Q.2. Write code to print only upto the letter t.

Q.3. Write code to print everything in the string except the spaces.

Q.4. Now, print this string five times in a row.

Q.5. What is the purpose of bytes() in Python?

Q.6. What is a control flow statement?

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:

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

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:

Write a program to compute the number of characters, words and lines in a


file.

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.2. What does the following code output?

Q.3. How many arguments can the range() function take?

Q.4. What is PEP 8?

Q.5. How is Python different from Java

Q.6. What is the best code you can write to swap two numbers?

Q.7. How can you declare multiple assignments in one statement?

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:

from difflib import SequenceMatcher


def Nearly_Equal(a,b):
return SequenceMatcher(None,a,b).ratio();
a="khit"
b="khitc"
c=Nearly_Equal(a,b)
if(c*100>80):
print("Both Strings are similar")
print("a is mutation on b")
else:
print("Both Strings are Different")

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

Q.1. How do we execute Python?

Q.2. Explain Python’s parameter-passing mechanism.

Q.3. What is the with statement in Python?

Q.4. How is a .pyc file different from a .py file?

Q.5. What makes Python object-oriented?

Q.6. How many types of objects does Python support?


Experiment-10
Aim:

Write a program to implement Merge sort.

Source Code:

# Python program for implementation of MergeSort


def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves

mergeSort(L) # Sorting the first half


mergeSort(R) # Sorting the second half

i=j=k=0

# Copy data to temp arrays L[] and R[]


while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1

# Checking if any element was left


while i < len(L):
arr[k] = L[i]
i+=1
k+=1

while j < len(R):


arr[k] = R[j]
j+=1
k+=1

# Code to print the list


def printList(arr):
for i in range(len(arr)):
print(arr[i],end=" ")
print()

# driver code to test the above code


if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

Output:

Given array is
12 11 13 5 6 7
Sorted array is:
5 6 7 11 12 13

Aim:

Write a program to implement Selection sort, Insertion sort.Selection Sort

Source Code:
# Python program for implementation of Selection
# Sort
import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),

Output:

Sorted array
11
12
22
25
64

Source Code:

# Python program for implementation of Insertion Sort

# Function to do insertion sort


def insertionSort(arr):

# Traverse through 1 to len(arr)


for i in range(1, len(arr)):

key = arr[i]

# Move elements of arr[0..i-1], that are


# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver code to test above


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

Output:

Sorted array is:


5
6
11
12
13
VIVA QUESTIONS

Q.1. Why is it called Python?

Q.2. What is the interpreter in Python?

Q.3. What does a python do?

Q.4. What is the purpose of PYTHONHOME environment variable?

Q.5. What is the purpose of PYTHONCASEOK environment variable?

Q.6. What is the purpose of PYTHONSTARTUP environment variable?

Q.7. What is the purpose of PYTHONPATH environment variable?

Q.8. If given the first and last names of bunch of employees how would you store it and
what datatype?

You might also like