0% found this document useful (0 votes)
415 views

Python Lab Manual 10.06.2022

This document provides a Python lab manual containing instructions and code examples for 16 weekly lab sessions. It introduces fundamental Python concepts like data types, arithmetic operations, strings, dates, lists, tuples, dictionaries, conditionals, functions, modules, file handling and more. Students are guided to write and run Python programs demonstrating these concepts and analyzing outputs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
415 views

Python Lab Manual 10.06.2022

This document provides a Python lab manual containing instructions and code examples for 16 weekly lab sessions. It introduces fundamental Python concepts like data types, arithmetic operations, strings, dates, lists, tuples, dictionaries, conditionals, functions, modules, file handling and more. Students are guided to write and run Python programs demonstrating these concepts and analyzing outputs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

PYTHON LAB MANUAL 2022

DEPARTMENT OF INFORMATION TECHNOLOGY

B.Tech II Year IV-Sem


# week-1
'''Aim:Write a program to demonstrate different number data types in Python.'''
a=10; #Integer Datatype
b=11.5; #Float Datatype
c=2.05j; #Complex Number
print("a is Type of",type(a)); #prints type of variable a
print("b is Type of",type(b)); #prints type of variable b
print("c is Type of",type(c)); #prints type of variable c

Output:

# week-2
'''Aim:Write a program to perform different Arithmetic Operations on numbers in Python.'''

a=int(input("Enter a value")); #input() takes data from console at runtime as string.


b=int(input("Enter b value")); #typecast the input string to int.
print("Addition of a and b ",a+b);
print("Subtraction of a and b ",a-b);
print("Multiplication of a and b ",a*b);
print("Division of a and b ",a/b);
print("Remainder of a and b ",a%b);
print("Exponent of a and b ",a**b); #exponent operator (a^b)
print("Floar division of a and b ",a//b); # floar division

Output:

1
PYTHON LAB MANUAL 2022

# week-3

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

s1=input("Enter first String : ");


s2=input("Enter second String : ");
print("First string is : ",s1);
print("Second string is : ",s2);
print("concatenations of two strings :",s1+s2);
print("Substring of given string :",s1[1:4]);

Output:

# week-4
'''Aim: . Write a python script to print the current date in the following format Sun May 29
02:26:23 IST 2017 '''
import time;
ltime=time.localtime();
print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime)); #returns the formatted time

''' %a : Abbreviated weekday name.


%b : Abbreviated month name.
%d : Day of the month as a decimal number [01,31].
%H : Hour (24-hour clock) as a decimal number [00,23].
%M : Minute as a decimal number [00,59].
%S : Second as a decimal number [00,61].
%Z : Time zone name (no characters if no time zone exists).
%Y : Year with century as a decimal number.'''
Output:

2
PYTHON LAB MANUAL 2022

# week-5
'''Aim: Write a program to create, append, and remove lists in python. '''

pets = ['cat', 'dog', 'rat', 'pig', 'tiger']


snakes=['python','anaconda','fish','cobra','mamba']
print("Pets are :",pets)
print("Snakes are :",snakes)
animals=pets+snakes
print("Animals are :",animals)
snakes.remove("fish")
print("updated Snakes are :",snakes)
Output:

# week-6
'''Write a program to demonstrate working with tuples in python'''
T = ("apple", "banana", "cherry","mango","grape","orange")
print("\n Created tuple is :",T)
print("\n Second fruit is :",T[1])
print("\n From 3-6 fruits are :",T[3:6])
print("\n List of all items in Tuple :")
for x in T:
print(x)
if "apple" in T:
print("\n Yes, 'apple' is in the fruits tuple")
print("\n Length of Tuple is :",len(T))
Output:

3
PYTHON LAB MANUAL 2022

# week-7

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

dict1 = {'StdNo':'532','StuName': 'Naveen', 'StuAge': 21, 'StuCity': 'Hyderabad'}


print("\n Dictionary is :",dict1)
#Accessing specific values
print("\n Student Name is :",dict1['StuName'])
print("\n Student City is :",dict1['StuCity'])
#Display all Keys
print("\n All Keys in Dictionary ")
for x in dict1:
print(x)
#Display all values
print("\n All Values in Dictionary ")
for x in dict1:
print(dict1[x])
#Adding items
dict1["Phno"]=85457854
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Change values
dict1["StuName"]="Madhu"
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Removing Items
dict1.pop("StuAge");
#Updated dictoinary
print("\n Uadated Dictionary is :",dict1)
#Length of Dictionary
print("Length of Dictionary is :",len(dict1))
#Copy a Dictionary
dict2=dict1.copy()
#New dictoinary
print("\n New Dictionary is :",dict2)
#empties the dictionary
dict1.clear()
print("\n Uadated Dictionary is :",dict1)

4
PYTHON LAB MANUAL 2022

Output:

# week-8

''' Write a python program to find largest of three numbers '''

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)

Output:

5
PYTHON LAB MANUAL 2022

# week-9

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

print("Options are \n")


print("1.Convert temperatures from Celsius to Fahrenheit \n")
print("2.Convert temperatures from Fahrenheit to Celsius \n")
opt=int(input("Choose any Option(1 or 2) : "))
if opt == 1:
print("Convert temperatures from Celsius to Fahrenheit \n")
cel = float(input("Enter Temperature in Celsius: "))
fahr = (cel*9/5)+32
print("Temperature in Fahrenheit =",fahr)
elif opt == 2:
print("Convert temperatures from Fahrenheit to Celsius \n")
fahr = float(input("Enter Temperature in Fahrenheit: "))
cel=(fahr-32)*5/9;
print("Temperature in Celsius =",cel)
else:
print("Invalid Option")

Output:

6
PYTHON LAB MANUAL 2022

# week-10

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

7
PYTHON LAB MANUAL 2022

# week-11
'''Write a Python script that prints prime numbers less than 20'''
print("Prime numbers between 1 and 20 are:")
ulmt=20;
for num in range(ulmt):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

Output:

# week-12
''' Write a python program to find factorial of a number using Recursion.'''
def recur_fact(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_fact(n-1)
num = int(input("Enter a number: "))
# check is the number is negative
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",recur_fact(num))
8
PYTHON LAB MANUAL 2022

Output:

# week-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).'''
base=float(input("Enter length of Base : "))
perp=float(input("Enter length of Perpendicular : "))
hypo=float(input("Enter length of Hypotenuse : "))
if hypo**2==((base**2)+(perp**2)):
print("It's a right triangle")
else:
print("It's not a right triangle")

Output:

9
PYTHON LAB MANUAL 2022

fibonacci.py
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end =" ")
a, b = b, a+b

# week-14
''' Write a python program to define a module to find Fibonacci Numbers and import the
module to another program'''
# import fibonacci module
import fibonacci
num=int(input("Enter any number to print Fibonacci series "))
fibonacci.fib(num)

Output:

# arth.py
''' Arithmetic Operations Module with Multiple functions'''
def Add(a,b):
c=a+b
return c
def Sub(a,b):
c=a-b
return c
def Mul(a,b):
c=a*b
return c

# week-15
'''Write a python program to define a module and import a specific function in that
module to another program.'''
from arth import Add
num1=float(input("Enter first Number : "))
10
PYTHON LAB MANUAL 2022

num2=float(input("Enter second Number : "))


print("Addition is : ",Add(num1,num2))
print("Subtraction is : ",Sub(num1,num2)) #gives error:Not importing Sub function from arth
Module
Output:

# file1.txt
This is python program
welcome to python

# week-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'''

file1=input("Enter First Filename : ")


file2=input("Enter Second Filename : ")
# open file in read mode
fn1 = open(file1, 'r')
# open other file in write mode
fn2 = open(file2, 'w')
# read the content of the file line by line
cont = fn1.readlines()
#type(cont)
for i in range(0, len(cont)):
fn2.write(cont[i])
# close the file
fn2.close()
print("Content of first file copied to second file ")
# open file in read mode
fn2 = open(file2, 'r')
# read the content of the file
cont1 = fn2.read()
# print the content of the file
print("Content of Second file :")
print(cont1)
# close all files
fn1.close()
11
PYTHON LAB MANUAL 2022

fn2.close()
Output:

# file1.txt
This is python program
welcome to python

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

fname = input("Enter file name: ")


fh = open(fname)
lst = list() # list for the desired output
words=[];
for line in fh: # to read every line of file romeo.txt
words += line.split()
words.sort() # display the sorted words
print("The unique words in alphabetical order are:")
for word in words:
if word in lst: # if element is repeated
continue # do nothing
else: # else if element is not in the list
lst.append(word)
print(word) #print(lst)

Output:

12
PYTHON LAB MANUAL 2022

# week-18

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

class irconvert:
num_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),(50, 'L'),
(40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]

def num2roman(self,num):
roman = ''
while num > 0:
for i, r in self.num_map:
while num >= i:
roman += r
num -= i
return roman

num=int(input("Enter any Number :"))


print("Roman Number is : ",irconvert().num2roman(num))

OUTPUT:

D:\PythonProject>python week18.py
Enter any Number :5
Roman Number is : V

13
PYTHON LAB MANUAL 2022

# week-19
'''Write a Python class to implement pow(x, n)'''
class py_pow:
def powr(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.powr(x,-n)
val = self.powr(x,n//2)
if n%2 ==0:
return val*val
return val*val*x

x=int(input("Enter x value :"))


n=int(input("Enter n value :"))
print("pow(x,n) value is :",py_pow().powr(x,n));

OUTPUT:

D:\PythonProject>python week19.py
Enter x value :2
Enter n value :3
pow(x,n) value is : 8

14
PYTHON LAB MANUAL 2022

# week-20

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


class py_reverse:
def revr(self, strs):
sp=strs.split()
sp.reverse()
res=" ".join(sp)
return res

str1=input("Enter a string with 2 or more words : ")


print("Reverse of string word by word: \n",py_reverse().revr(str1));

OUTPUT:

D:\PythonProject>python week20.py
Enter a string with 2 or more words : IT STUDENTS
Reverse of string word by word:
STUDENTS IT

15

You might also like