You are on page 1of 24

PYTHON PROGRAMMING

LAB MANUAL

I-B.TECH II-SEM
CSE (AI & ML)

JNTUH-R22

Faculty In-charge:
Mr.A.SATISH,M.Tech(P.hD) Asst.Prof.

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

PYTHON PROGRAMMING LAB


LIST OF EXPERIMENTS:

1. Write a program to demonstrate different number data types in Python.

2. Write a program to perform different Arithmetic Operations on numbers in Python.

3. Write a program to create, concatenate and print a string and accessing sub-string
from a given string.

4. Write a python script to print the current date in the following format “Sun May 29
02:26:23 IST 2017”

5. Write a program to create, append, and remove lists in python.

6. Write a program to demonstrate working with tuples in python.

7. Write a program to demonstrate working with dictionaries in python.

8. Write a python program to find largest of three numbers.

9. Write a Python program to convert temperatures to and from Celsius, Fahrenheit. [


Formula : c/5 = f-32/9 ]

10. Write a Python program to construct the following pattern, using a nested for loop

11. Write a Python script that prints prime numbers less than 20.

12. Write a python program to find factorial of a number using Recursion.

13. Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Recall

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 1


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

from the Pythagorean Theorem that in a right triangle, the square of one side equals the sum
of the squares of the other two sides).

14. Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.

15. Write a python program to define a module and import a specific function in that
module to another program.

16. Write a script named copyfile.py. This script should prompt the user for the names of two
text files. The contents of the first file should be input and written to the second file.

17. Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.

18. Write a Python class to convert an integer to a roman numeral.

19. Write a Python class to implement pow(x, n)

20. Write a Python class to reverse a string word by word.

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 2


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 3


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 4


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

PYTHON PROGRAMMING LAB

Course Objectives:

 To be able to introduce core programming basics and program design with functions
using Python programming language.
 To understand a range of Object-Oriented Programming, as well as in-depth data and
information processing techniques.
 To understand the high-performance programs designed to strengthen the practical
expertise.

Course Outcomes:

 Student should be able to understand the basic concepts scripting and the
contributions of scripting language
 Ability to explore python especially the object oriented concepts, and the built in
objects of Python.
 Ability to create practical and contemporary applications such as TCP/IP network
programming, Web applications, discrete event simulations

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 5


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

INSTRUCTIONS FOR LABORATORY

1. Conduct the experiments with interest and an attitude of learning.

2. You need to come well prepared for the experiment.

3. Work quietly and carefully and equally share the work with your partners.

4. Be honest in recording and representing your data.

5. Never make up readings.

6. Tables and calculations should be neatly and carefully done.

7. Bring necessary graph papers for each of the experiment.

8. Graphs should be neatly drawn with pencil.

9. Always label graphs and the axes and display units.

10.Come equipped with calculator, scales and pencils etc.,

11.Do not fiddle idly with the apparatus.

12.Handle instruments with care.

13.Report any breakage to the instructor.

14.Return all the equipment you have signed out for the purpose of your experiment.

15.Maintain an observation note book sequent.

16.Submit the record work with in stipulated time.

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 6


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

1. Write a program to demonstrate different number data types in Python.

AIM: Write a program to demonstrate different number data types in Python.

x=10
print(type(x))
x=10.6
print(type(x))
x='abc'
print(type(x))
x=1+2j
print(type(x))
x=[1,'a',10.6,1+2j]
print(type(x))
x=(1,'a',10.6,1+2j)
print(type(x))
x={"name":'abc',"age":29,"salary":30000}
print(type(x))

OUTPUT:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'dict'>

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 7


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

2. Write a program to perform different Arithmetic Operations on numbers in Python.


AIM: Write a program to perform different Arithmetic Operations on numbers in
Python.

a=int(input("enter a value"))
b=int(input("enter b value"))
x=a+b
y=a-b
z=a*b
p=a/b
print(x,y,z,p)

OUTPUT:
enter a value10
enter b value20
30 -10 200 0.5

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 8


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

3. Write a program to create, concatenate and print a string and accessing sub-string
from a given string.
AIM: Write a program to create, concatenate and print a string and accessing sub-string
from a given string.

a = "Hello"
b = "world"
print(a[:])
print(a[0:])
print(a[:5])
print(a*3) # prints HelloHelloHello
print(a+b)# prints Hello world
print(a[4]) # prints o
print(a[2:4]); # prints ll
print('w' in a) # prints false as w is not present in str
print('wo' not in b) # prints false as wo is present in str1.

OUTPUT:
Hello
Hello
Hello
HelloHelloHello
Helloworld
o
ll
Helloworld
HelloHello
False
False

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 9


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

4. Write a python script to print the current date in the following format “Sun May 29
02:26:23 IST 2017”
AIM: Write a python script to print the current date in the following format “Sun May
29 02:26:23 IST 2017”

import datetime
print(datetime.datetime.now())
import time
print(time.asctime(time.localtime(time.time())))

OUTPUT:

Wed Feb 26 14:26:57 2020

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 10


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

5. Write a program to create, append, and remove lists in python.

AIM: Write a program to create, append, and remove lists in python.

L = ["John", 102, "USA",10.6,1+2j]


print(L)
print(L[0])
print(L[1])
print(L[0:])
print(L[:])
print(L[1:3])
print(L.index(102))
print(L.index("USA"))
L.append([103,'VIJAY'])
print(L)
L.insert(5,20)
print(L)
del L[0]
print(L)
L.remove(10.6)
print(L)

OUTPUT:
['John', 102, 'USA', 10.6, (1+2j)]
John
102
['John', 102, 'USA', 10.6, (1+2j)]
['John', 102, 'USA', 10.6, (1+2j)]
[102, 'USA']
1
2
['John', 102, 'USA', 10.6, (1+2j), [103, 'VIJAY']]
['John', 102, 'USA', 10.6, (1+2j), 20, [103, 'VIJAY']]
[102, 'USA', 10.6, (1+2j), 20, [103, 'VIJAY']]
[102, 'USA', (1+2j), 20, [103, 'VIJAY']]

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 11


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

6. Write a program to demonstrate working with tuples in python.

AIM: Write a program to demonstrate working with tuples in python.

T = ("John", 102, "USA",10.6,1+2j)


print(T)
print(T[0])
print(T[1])
print(T[:])
print(T[0:])
print(T[2:4])
print(T.index(102))
print(T.index("USA"))
OUTPUT:
('John', 102, 'USA', 10.6, (1+2j))
John
102
('John', 102, 'USA', 10.6, (1+2j))
('John', 102, 'USA', 10.6, (1+2j))
('USA', 10.6)
1
2

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 12


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

7. Write a program to demonstrate working with dictionaries in python.

AIM: Write a program to demonstrate working with dictionaries in python.

d = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(type(d))
print(d)
print(d["Name"])
print(d["Age"])
print(d.keys())
print(d.values())

for x in d:
print(x)

for x in d:
print(d[x])

del d["Name"]
print(d)

for x in d:
print(x)

for x in d:
print(d)

OUTPUT:
<class 'dict'>
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
John
29
dict_keys(['Name', 'Age', 'salary', 'Company'])
dict_values(['John', 29, 25000, 'GOOGLE'])
Name
Age
salary
Company
John
29
25000
GOOGLE

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 13


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

{'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}


Age
salary
Company
29
25000
GOOGLE

8. Write a python program to find largest of three numbers.

AIM: Write a python program to find largest of three numbers.

a = float(input("Enter first number: "))


b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

if (a > b) and (a > c):


largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
print("The largest number is",largest)

OUTPUT:
Enter first number: 10
Enter second number: 20
Enter third number: 30
The largest number is 30.0

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 14


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

9. Write a Python program to convert temperatures to and from Celsius, Fahrenheit. [


Formula : c/5 = f-32/9 ]
AIM: Write a Python program to convert temperatures to and from Celsius, Fahrenheit.
[ Formula : c/5 = f-32/9 ]

celsius = float(input('Enter temperature in Celsius: '))


fahrenheit = (celsius * 1.8) + 32
print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))

OUTPUT:
Enter temperature in Celsius: 37

37.0 Celsius is equal to 98.6 degree Fahrenheit

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 15


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

10. Write a Python program to construct the following pattern, using a nested for loop

AIM: Write a Python program to construct the following pattern, using a nested for loop

n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')

for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')

OUTPUT:

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 16


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

11. Write a Python script that prints prime numbers less than 20.

AIM: Write a Python script that prints prime numbers less than 20.

r=int(input("Enter upper limit: "))


for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)

OUTPUT:

Enter upper limit: 10

12. Write a python program to find factorial of a number using Recursion.

AIM: Write a python program to find factorial of a number using Recursion.

def recfac(n):
if n == 1:
return n
else:
return n*recfac(n-1)
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recfac(num))

OUTPUT:
Enter a number: 5
The factorial of 5 is 120

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 17


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

13. Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Recall
from the Pythagorean Theorem that in a right triangle, the square of one side equals
the sum of the squares of the other two sides).
AIM: Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Recall
from the Pythagorean Theorem that in a right triangle, the square of one side equals
the sum of the squares of the other two sides).

print("Input lengths of the triangle sides: ")


x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))

if x == y == z:
print("Equilateral triangle")
elif x==y or y==z or z==x:
print("isosceles triangle")
elif x==90 or y==90 or z==90:
print("right angle triangle")
else:
print("Scalene triangle")

OUTPUT:

Input lengths of the triangle sides:


x: 60
y: 45
z: 90
right angle triangle

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 18


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

14. Write a python program to define a module to find Fibonacci Numbers and import
the module to another program.
AIM: Write a python program to define a module to find Fibonacci Numbers and import
the module to another program.

n = int(input("How many terms you want? "))


# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if n <= 0:
print("Plese enter a positive integer")
elif n == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < n:
sum = n1 + n2
print(sum,end=' , ')
# update values
n1 = n2
n2 = sum
count += 1
OUTPUT:
How many terms you want? 20
Fibonacci sequence:
0 , 1, 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377 , 610 , 987 , 1597 , 2584 , 4181 ,

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 19


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

15. Write a python program to define a module and import a specific function in that
module to another program.
AIM: Write a python program to define a module and import a specific function in that
module to another program.

def sum(a,b):
return a+b
def mul(a,b):
return a*b
def div(a,b):
return a/b

OUTPUT:
enter the first number 10
enter the second number 20
sum=30
mul=200

16. Write a script named copyfile.py. This script should prompt the user for the names
of two text files. The contents of the first file should be input and written to the second
file.
AIM: . Write a script named copyfile.py. This script should prompt the user for the
names of two text files. The contents of the first file should be input and written to the
second file.

from c import sum,mul


a=int(input("enter the first number"))
b=int(input("enter the first number"))
print("sum=",sum(a,b))
print("mul=",mul(a,b))

OUTPUT:
Enter filename to copy:a.txt
Enter filename to save:b.txt
File copied successfully.

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 20


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

17. Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.
AIM: Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.

items = input("Input comma separated sequence of words")


words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))
OUTPUT:
Input comma separated sequence of wordsa,d,s,e
a,d,e,s

18. Write a Python class to convert an integer to a roman numeral.


AIM: Write a Python class to convert an integer to a roman numeral.

class py_solution:
def int_to_Roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i=0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 21


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

return roman_num
print(py_solution().int_to_Roman(1))
print(py_solution().int_to_Roman(4000))
OUTPUT:

IX
V

19. Write a Python class to implement pow(x, n)


AIM: Write a Python class to implement pow(x, n)

class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x

if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n//2)
if n%2 ==0:
return val*val
return val*val*x

print(py_solution().pow(2, -3));
print(py_solution().pow(3, 5));
print(py_solution().pow(100, 0));
OUTPUT:

0.125
243
1

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 22


PYTHON PROGRAMMING LAB MANUAL COMPUTER SCIENCE & ENGINEERING

20. Write a Python class to reverse a string word by word.

AIM: Write a Python class to reverse a string word by word.

class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
print(py_solution().reverse_words('murali krishna'))

OUTPUT:
li ra mu

KHAMMAM INSTITUTE OF TECHNOLOGY & SCIENCES, KHAMMAM 23

You might also like