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

DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING

PYTHON PROGRAMMING
LAB MANUAL

(18CS614)

Prepared by: Verified by:


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VISION
To create the most conducive environment for quality academic and research oriented undergraduate
and post graduate education in computer science and engineering and prepare the students for a
globalised technological society and orient them towards serving the society.
MISSION
Provide quality undergraduate and graduate education in both the theoretical and applied foundations
of computer science and train students to effectively apply this education to solve real-world
problems thus amplifying their potential for lifelong high-quality careers and give them a
competitive advantage in the ever-changing and challenging global work environment.

PROGRAM EDUCATIONAL OBJECTIVES (PEO'S)

PEO1: Graduates will have strong understanding in logical, mathematical and analytical reasoning
among peers, coupled with problem solving attitude.
PEO2: Graduates able to engage in the productive practice of Computer Science and Engineering to
identify and solve significant problems across broad range of application areas.
PEO3: Graduates able to engage in successful careers in industry, academics, and public service,
providing communication and management skills that generate entrepreneurship and/ or leadership
qualities.
PEO4: Graduates able to adapt to new technologies, tools and methodologies by life-long learning to
remain at the leading edge of computer engineering practice with the ability to respond to challenges of
changing environment with ethical approach.

PROGRAM SPECIFIC OUTCOMES (PSO'S)


PSO1: Graduates will have strong understanding in logical, mathematical and analytical reasoning
among peers, coupled with problem solving attitude.
PSO2: Graduates able to engage in the productive practice of Computer Science and Engineering to
identify and solve significant problems across broad range of application areas.
PSO3: Graduates able to engage in successful careers in industry, academics, and public service,
providing communication and management skills that generate entrepreneurship and/ or leadership
qualities.
PSO4: Graduates able to adapt to new technologies, tools and methodologies by life-long learning to
remain at the leading edge of computer engineering practice with the ability to respond to challenges of
a changing environment with ethical approach.
PYTHON PROGRAMMING LABORATORY

(18CS614)

Course Objectives:

Students should install Python on Linux platform. Course Objectives:

1. Able to introduce core programming basics and program design with functions using Python
programming language.

2. Understand a range of Object-Oriented Programming, as well as in-depth data and information


processing techniques.

3. Understand the high-performance programs designed to strengthen the practical expertise.

Course Outcomes:

At the end of the course, the student will be able to:

1. Implement data types, Lists.

2. Develop Programs on control structures, Tuples.

3. Develop Programs Using Lists.

4. Develop Programs Using Lists.


PYTHON PROGRAMMING LAB
(18CS614)
S. No. List of Experiments Page No.
PYTHON PROGRAMMING LAB
1 Write a program to demonstrate different number data types in Python. 1
2 Write a program to perform different Arithmetic Operations on numbers in 2
Python.
3 Write a program to defining strings in Python. 3
4 Write a python script to print the current date in the following format “Sun 4
May 07 03:30:03 IST 2020”
5 Write a program to create, append, and remove lists in python. 5
6 Write a program to demonstrate working with tuples in python. 7
7 Write a program to demonstrate working with dictionaries in python 8
8 Write a python program to find largest of three numbers. 9
9 Write a Python program to convert temperatures to and from Celsius, 10
Fahrenheit[ Formula: c/5 = f-32/9]
10 Write a Python script that prints prime numbers less than 20. 11

11 Write a Python script to print First n prime numbers 12

12 Write a Python script to Multiply matrices 13


13 Write a python program to find factorial of a number using Recursion. 14
14 Write a python program to define a module and import a specific function in 15
that module to another program.
15 Write a script named copyfile.py. This script should prompt the user for the 16
names of two text files. The contents of the first file should be input and
written to the second file.
16 Write a program that inputs a text file. The program should print all of the 17

unique words in the file in alphabetical order.


17 Write a Python class to convert an integer to a roman numeral. 18
18 Write a Python class to implement pow(x, n) 19
19 Write a Python class to reverse a string word by word. 20

20 Write a python program to define a module to find Fibonacci Numbers and 21


import the module to another program.
EXPERIMENT 1

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

Program:

# Python program to demonstrate numeric value


a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 1
EXPERIMENT 2

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

Program:

num1 = int(input('Enter First number: '))


num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
print('Division of ',num1 ,'and' ,num2 ,'is :',div)
print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 2
EXPERIMENT 3

AIM: Write a program to defining strings in Python.

Program:

# defining strings in Python


# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 3
EXPERIMENT 4

AIM: Write a python script to print the current date in the following format “Sun May 07
03:30:03 IST 2020”

Program:

import time
import datetime
print("Current date and time: " , datetime.datetime.now())
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 4
EXPERIMENT 5

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

Program:

class MyList:
def __init__(self):
self.n = []
def add(self, a):
return self.n.append(a)
def remove(self, b):
self.n.remove(b)
def display(self):
return (self.n)
obj = MyList()
choice = 1
while choice != 0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice = int(input("Enter choice: "))
if choice == 1:
n = int(input("Enter number to append: "))
obj.add(n)
print("List: ", obj.display())
elif choice == 2:
n = int(input("Enter number to remove: "))
obj.remove(n)
print("List: ", obj.display())
elif choice == 3:
print("List: ", obj.display())
elif choice == 0:
print("Exiting!")
else:
print("Invalid choice!!")

PYTHON PROGRAMMING LAB MANUAL


Page 5
Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 6
EXPERIMENT 6

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

Program:

# Different types of tuples


# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 7
EXPERIMENT 7

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

Program:

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Audisankara', 2: 'Engineering', 3: 'College'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Audisankara', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 8
EXPERIMENT 8

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

Program:

# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(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:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 9
EXPERIMENT 9

AIM:Write a Python program to convert temperatures to and from Celsius, Fahrenheit.


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

Program:

# Python Program to convert temperature in celsius to fahrenheit


# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 10
EXPERIMENT 10

AIM: Python program to display all the prime numbers within an interval

Program:

lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 11
EXPERIMENT 11

AIM: Write a Python script to print First n prime numbers.

Program:

# Python Program to print n prime number using for loop


Number = int(input(" Please Enter any Number: "))
print("Prime numbers between", 1, "and", Number, "are:")
for num in range(1, Number + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 12
EXPERIMENT 12

AIM: Write a Python script to multiply matrices # 3x2 matrix

Program:

X = [ [1,2],[3,4],[4,5] ]
# 2x3 matrix
Y = [ [1,2,3],[4,5,6] ]
# resultant matrix
result = [ [0,0,0],[0,0,0],[0,0,0] ]
my_list = []
# iterating rows of X matrix
for i in range( len(X) ):
# iterating columns of Y matrix
for j in range(len(Y[0])):
# iterating rows of Y matrix
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 13
EXPERIMENT 13

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

Program:

# Factorial of a number using recursion


def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 5
# check if 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_factorial(num))

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 14
EXPERIMENT 14

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

Program:

# top_module.py
import module1
module1.print_parameters()
print(module1.combinations(5, 2))
# module1.py
from module2 import k, print_parameters
from math import factorial
n = 5.0
def combinations(n, k):
return factorial(n) / factorial(k) / factorial(n-k)
# module2.py
import module1
k = 2.0
def print_parameters():
print('k = %.f n = %.f' % (k, module1.n))

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 15
EXPERIMENT 15

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.

Program:

# to prompt the user to enter the file1 which is input file


infile=input("enter the input filename with extension ");
# to prompt the user to enter the file2 which is output file
outfile=input("enter the output filename with extension ");
#opening the file1 in reading mode
f1=open(infile,"r");
#opening the file2 in output mode
f2=open(outfile,"w+");
#reading the content of file1 to content variable
content=f1.read();
#writing to the value of content variable to file2
f2.write(content);
#closing the file1 and file2
f1.close();
f2.close();

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 16
EXPERIMENT 16

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

Program:

# Program to sort alphabetically the words form a string provided by the user
my_str = "Hello this Is an Example With cased letters"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 17
EXPERIMENT 17

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


Program:

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
return roman_num
print(py_solution().int_to_Roman(1))
print(py_solution().int_to_Roman(4000))

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 18
EXPERIMENT 18

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

Program:

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:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 19
EXPERIMENT 19

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

Program:

# Function to reverse words of string


def rev_sentence(sentence):
# first split the string into words
words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))
# finally return the joined string
return reverse_sentence
if __name__ == "__main__":
input = 'araknasidua'
print rev_sentence(input)

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 20
EXPERIMENT 20

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

Program:

# Program to display the Fibonacci sequence up to n-th term


nterms = int(input("How many terms: "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output:

Conclusion:

PYTHON PROGRAMMING LAB MANUAL


Page 21

You might also like