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

Department of Computer and Communication Engineering

School of Computing & Information Technology


B.Tech Computer Science and Engineering (IoT and Intelligent Systems)

Lab Manual
Python Programming Lab
Course Code: IS 2132
Semester-III
MANIPAL UNIVERSITY JAIPUR
School of Computing and IT
Department of Computer and Communication Engineering
B.Tech Computer Science and Engineering (IoT and Intelligent Systems)

Course Hand-out
Python Programming Lab | IS 2132 | 1 Credits | 0 0 2 1
Ses Session: Aug’23 – Dec’23 | Course Coordinator: Dr. Sourabh Singh Verma | Class: 2nd Year / 3id Sem
Faculty: 1. Dr. Manoj Sharma, 2. Dr. Arpit Sharma

A. Introduction: Python programming is widely used in Artificial Intelligence, Natural Language


Generation, Neural Networks, and other advanced fields of Computer Science. Moreover, Python
is one of the most demanded programming languages in the market, so there are huge job
opportunities for candidates having knowledge of Python programming. This course is designed
to familiarize the students with Python programming basics and advanced concepts This Python
course contains a range of topics from installation and introduction to different IDE to basic
building blocks of Python, looping and control structures, functions etc. Through this course
student will also get the opportunity to learn various object-oriented concepts related to python
and will get knowledge about various Python libraries and GUI frameworks.

B. Course Outcome: At the end of the course, students will be able to


[IS2132.1] Demonstrate basic programming skills of Python
programming.
[2132.2] Implement the concept of Python GUI and data structures.
[2132.3] Illustrate the concept of object-oriented programming using python.
[2132.4] Implement the concept of analytics using python libraries.

C. Program Outcomes and Program Specific Outcomes

[PO.1]. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems
[PO.2]. Problem analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences
[PO.3]. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations
[PO.4]. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions
[PO.5]. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations
[PO.6]. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal, and cultural issues and the consequent responsibilities
relevant to the professional engineering practice
[PO.7]. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development
[PO.8]. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practices
[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, being able to comprehend and
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 and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments
[PO.12]. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change
Program Specific Outcomes (PSOs)
At the end of the B Tech CCE program, the student:
[PSO.1] Imbibe the basic concepts and applications of computer-based Communication or
networking, information sharing, signal processing, web-based systems, smart devices, and
communication technology.
[PSO.2] Investigate prominent areas in the field of Computer and Communication Engineering to
provide feasible solutions.
[PSO.3] Apply the contextual knowledge in the field of Computing and Communication to assess
social, health, safety, and security issues relevant to the professional engineering practice.

D. Assessment Rubrics:
Criteria Description Maximum
Marks
Internal Assessment (Formative) Fortnightly evaluation 40
(Record + execution + viva)
Mini project 20
End Term Exam (Summative) End Term Exam 40
Total 100
Attendance (Formative) A minimum of 75% Attendance is required to be maintained
by a student to be qualified for taking up the End Semester
examination. The allowance of 25% includes all types of
leaves including medical leaves.
Make up Assignments Students who missed the lab will have to report to the
(Formative) teacher about the absence. A makeup assignment on the
topic taught on the day of absence will be given which has
to be submitted within a week from the date of absence. No
extensions will be given on this. The attendance for that
particular day of absence will be marked blank, so that the
student is not accounted for absence. These assignments are
limited to a maximum of 2 throughout the entire semester.
E. Syllabus
Python IDE: Introduction to Python IDE, Use of Python IDE (Jupyter, Pycharm, Pydev, VIM
etc.). Control Statement: If, If else, else if, nested if, for loop, while loop, do while, break,
continue, pass. Python OOPs: OOPs Concepts, Object, Class, Constructors, Inheritance,
Multilevel Inheritance, Multiple Inheritance. Data structures: List, Set, Dictionary (mapping),
Tuple, Graph (from a third-party library), List Slicing (sub list), List comprehension (shorthand
for a loop), Mutable and immutable data structures, Distinction between identity and (abstract)
value. Functions: Procedural abstraction, Functions as values, recursion, Function design
methodology. The Python Library: String and Text Handling, Data Structures and
Algorithms, Threading, Networking, Web Programming, Graphical Programming, Database
Access. Python GUI: Introduction to python GUI framework, Use of Python GUI.

Reference Books:
1. A. Martelli, Python in a Nutshell, (3e), O'Reilly Media, Inc, 2017.
2. J. Georzen, T. Bower, B. Rhodes, Foundations of Python Network Programming,(3e),
APress, 2014.
3. D. M. Beazley, Python Essential Reference,(4e), Pearson Addison-Wesley Professional,
2009.
4. M. Lutz, Programming Python, (4e), O'Reilly Media, 2010
F. Lecture Plan:

Lect. Topics Session Objective Mode of Corresponding Mode of Assessing the Outcome
No Delivery CO
1 Introduction to Python IDE Make the students familiarized with the development Lab IS2132.1 Internal Evaluation
environment which has been used throughout this Assignments
Course series to run Python code. External Evaluation
Variables, Keywords, Program to demonstrate how to declare Keywords, Lab IS2132.1 Internal Evaluation
Identifiers, Literals, Variables, Datatypes, and Comments in Python. Assignments
Operators, Comments Program to demonstrate different datatypes and External Evaluation
and datatype. arithmetic operations in Python.
2 Data structures: List, Program to create a list and perform various operations Lab IS2132.2 Internal Evaluation
List Slicing and Set on the list. Assignments
Program to demonstrate list slicing in Python External Evaluation

Program to create a set and perform various


operations on the set.
3 Dictionary, Tuple, Program to create Dictionary and perform various Lab IS2132.2 Internal Evaluation
Graph operations on the dictionary Assignments
External Evaluation
Program to create Tuple and perform various
operations on the Tuple.
Program to create Graph using third party library.
4 Control Statement: If, Program to check whether a number is even or not. Lab IS2132.1 Internal Evaluation
If else, else if, nested if Assignments
Program to find the largest number among the External Evaluation
three input numbers
Python program to print prime numbers in a given
range.
Python program to check whether a number is an
Armstrong number or not.
Python program to check if a year is a leap year
5-6 Python program to construct various ‘*’ patterns Lab IS2132.1 Internal Evaluation
For loop, while loop, do Python program to find t h e factorial of a Assignments
while, Break, Continue. number provided by user External Evaluation
Program to find sum of natural numbers up to nth
term
Program to display the Fibonacci sequence up to
nth term
Python program to demonstrate break and
continue
7 Functions Python program to make a Simple Calculator Lab IS2132.1 Internal Evaluation
using function Assignments
Python program to print LCM and HCF for the External Evaluation
given numbers
Python program to print factorial of a number
using recursion
Python program to print Fibonacci series up to nth
term using recursion
8 Python OOPs: OOPs Python program to demonstrate the concept of Lab IS2132.3 Internal Evaluation
Concepts, Object, Class, class and object. Assignments
Constructors. External Evaluation
9 Inheritance, Multilevel Python program to demonstrate the concept of Lab IS2132.3 Internal Evaluation
Inheritance, Multiple multilevel inheritance. Assignments
Inheritance. Python program to demonstrate the concept of External Evaluation
multiple inheritance.
10 The Python Library Python program to demonstrate the use of various Lab IS2132.4 Internal Evaluation
python library (use of libraries in string and text Assignments
handling) External Evaluation
11 Networking and Web Write a simple client server program in python Lab IS2132.4 Internal Evaluation
Programming using sockets. Assignments
External Evaluation
12 Python GUI Build a temperature converter using tkinter Lab IS2132.4 Internal Evaluation
Buid a Calculator using tkinter Assignments
Build a text editor using tkinter External Evaluation

G. Course Articulation Matrix: (Mapping of COs with POs)


CORRELATION WITH PROGRAM OUTCOMES CORRELATION
CO WITH PROGRAM
STATEMENT SPECIFIC
OUTCOMES
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO PSO1 PSO2
12

IS2132.1 Demonstrate basic 1 3 1 2 1


programming skills of Python
programming
IS2132.2 Implement the concept of 1 2 1 1 1
Python GUI and data
structures.
IS2132.3 Illustrate the concept of object- 1 2 1 1 1
oriented programming using
Python.

IS2132.4 Implement the concept of 1 2 1 1 2 1


analytics using Python
libraries.
1- Low Correlation; 2- Moderate Correlation; 3- Substantial Correlation
Department of Computer and Communication Engineering
School of Computing & Information Technology
B.Tech Computer Science and Engineering (IoT and Intelligent Systems)

Python Programming Lab


Course Code: IS2132
Semester-III

List of Experiments

1. Introduction and basic building blocks


1.1 WAP in python to add, subtract, multiply two integer, float and complex numbers
1.2 WAP in Python to calculate simple and compound interest
1.3 WAP in python to convert Celsius to Fahrenheit and kilometre to miles.
1.4 WAP in python to calculate roots of a quadratic equation
1.5 WAP in python to swap two variables with and without using temp variable.
2. Data Structures
2.1 WAP in python to create a list and perform various operations on the list.
2.2 WAP in python to demonstrate list slicing.
2.3 WAP in python to create set and perform various operations on the set
2.4 WAP in python to create Dictionary and perform various operations on the
dictionary
2.5 WAP in python to create Tuple and perform various operations on the Tuple.
2.6 WAP in python to create Graph using third party library.
3. Control Statements
3.1 WAP in python to check whether a number is even or odd
3.2 WAP in python to find the largest number among the three input numbers
3.3 WAP in python to print prime numbers in a given range.
3.4 WAP in python to check whether a number is an Armstrong number or not.
3.5 WAP in python to check if a year is a leap year
3.6 WAP in python to construct various ‘*’ patterns
3.7 WAP in Python to find factorial of a number provided by user.
3.8 WAP in python to find sum of natural numbers up to nth term
3.9 WAP in python to display the Fibonacci sequence up to nth term.
3.10 WAP in python to demonstrate break and continue
4. Functions
4.1 WAP in Python to make a Simple Calculator using function
4.2 WAP in python to print LCM and HCF for the given numbers
4.3 WAP in python to print factorial of a number using recursion
4.4 WAP in python to print Fibonacci series up to nth term using recursion
5. Object oriented concept
5.1 WAP in python to demonstrate the concept of class and object.
5.2 WAP in python to demonstrate the concept of multilevel inheritance.
5.3 WAP in python to demonstrate the concept of multiple inheritance.
6. Python Library, Networking (WEB Programming) & GUI
6.1 WAP in python to demonstrate the use of various python library (use of libraries in
string and text handling).
6.2 Write a simple client server program in python using sockets.
6.3 WAP in python to build a Calculator using tkinter
6.4 WAP in python to build a text editor using tkinter
COURSE CODE: IS 2132
LAB MANUAL

Python is a high-level, interpreted, general-purpose programming language. Being a general-


purpose language, it can be used to build almost any type of application with the right
tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and
automatic memory management which help in modelling real-world problems and building
applications to solve these problems. It was created by Guido van Rossum and released in 1991.

How to install Python:

1. Install Python using Anaconda navigator: Anaconda Navigator is a desktop GUI interface
that comes with Anaconda Individual Edition.

Step 1: Visit the official site for anaconda https://www.anaconda.com/


Step 2: Click on Product then select Anaconda Distribution (Open Source)
Step 3: Click on the download button
Step 4: Select your OS and Download a package
Step 5: After the installer gets downloaded, open it
Step 6: Start the installation in your system
Step 7: Kudos! ANACONDA has been successfully installed in your system.

Happy Coding (click on jupyter notebook to start programming)

2. Run Python Code on Google Colab: Google provides Jupyter Notebook like interface to
run Python code on online Virtual Machines.
Step 1: Open https://colab.research.google.com/

Step 2: Select New Python3 Notebook

Step 3: Start Typing code into the code cells.

1. Introduction and basic building blocks


1.1 WAP in python to add, subtract, multiply two integer, float and complex
numbers
Source Code
# 1.1 WAP in python to add, subtract, multiply two integer, float and complex
# numbers
# Reading two numbers
num1 = input('Enter first int number: ')
num2 = input('Enter second int number: ')
# add, subtract, miltiply integer
# Converting to int, Conversion is required because input() function return
# string
number1 = int(num1)
number2 = int(num2)
addint=number1+number2
subint=number1-number2
multint=number1*number2
print('Sum of integers {0} and {1} is: {2}' .format(number1, number2, addint))
print('diff of integers {0} and {1} is: {2}' .format(number1, number2, subint))
print('mult of integers {0} and {1} is: {2}' .format(number1, number2, multint))
# add, subtract, miltiply float
num3 = input('Enter first float number: ')
num4 = input('Enter second float number: ')
number3 = float(num3)
number4 = float(num4)
addfloat=number3+number4
subfloat=number3-number4
multfloat=number3*number4
print('Sum of float {0} and {1} is: {2}' .format(num3, num4, addfloat))
print('diff of float {0} and {1} is: {2}' .format(num3, num4, subfloat))
print('mult of float {0} and {1} is: {2}' .format(num3, num4, multfloat))
# add, subtract, miltiply complex number
num5 = complex(input('Enter first complex number: '))
num6 = complex(input('Enter second complex number: '))
addcomplex=num5+num6
subcomplex=num5-num6
multcomplex=num5*num6
print('Sum of complex {0} and {1} is: {2}' .format(num5, num6, addcomplex))
print('diff of float {0} and {1} is: {2}' .format(num5, num6, subcomplex))
print('mult of float {0} and {1} is: {2}' .format(num5, num6, multcomplex))

OUTPUT
Enter first int number: 4
Enter second int number: 5
Sum of integers 4 and 5 is: 9
diff of integers 4 and 5 is: -1
mult of integers 4 and 5 is: 20
Enter first float number: 4.5
Enter second float number: 6.8
Sum of float 4.5 and 6.8 is: 11.3
diff of float 4.5 and 6.8 is: -2.3
mult of float 4.5 and 6.8 is: 30.599999999999998
Enter first complex number: 5+3j
Enter second complex number: 5+2j
Sum of complex (5+3j) and (5+2j) is: (10+5j)
diff of float (5+3j) and (5+2j) is: 1j
mult of float (5+3j) and (5+2j) is: (19+25j)

1.2 WAP in Python to calculate simple and compound interest


Source Code
# Reading principal amount, rate and time
principal = float(input('Enter amount: '))
time = float(input('Enter time: '))
rate = float(input('Enter rate: '))
# Calcualtion
simple_interest = (principal*time*rate)/100
compound_interest = principal * ( (1+rate/100)**time - 1)
# Displaying result
print('Simple interest is : {0}' .format(simple_interest))
print('Compound interest is: {0}' .format(compound_interest))

OUTPUT
Enter amount: 5000
Enter time: 2
Enter rate: 45
Simple interest is : 4500.0
Compound interest is: 5512.5

1.3 WAP in python to convert Celsius to Fahrenheit and kilometre to miles


Source Code
# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('{0} degree Celsius is equal to {1} degree Fahrenheit'.format (celsius,fahrenheit))
# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('{0} kilometers is equal to {1} miles'.format(kilometers,miles))
OUTPUT
37.5 degree Celsius is equal to 99.5 degree Fahrenheit
Enter value in kilometers: 34
34.0 kilometers is equal to 21.126614 miles

1.4 WAP in python to calculate roots of a quadratic equation


Source Code
# import complex math module
import cmath
a=1
b=5
c=6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

OUTPUT
The solution are (-3+0j) and (-2+0j)

1.5 WAP in python to swap two variables with and without using temp variable.
# Python program to swap two variables
x=5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Logic for without using temp variable


x=x+y
y=x-y
x=x–y
or
x=x*y
y=x/y
x=x/y

OUTPUT
The value of x after swapping: 10
The value of y after swapping: 5

2.Data Structures
2.1 WAP in python to create a list and perform various operations on the list.
Python Lists are like arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
list1 = [1, "hi", "Python", 2]

2.1 Program to demonstrate List datatype in Python.


2.2 WAP in python to demonstrate list slicing.
Source Code ( for 2.1 and 2.2 both)
list1 = [1, "Manipal", "University", 2]
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetition using * operator
print (list1 * 3)

OUTPUT
[1, 'Manipal', 'University', 2]
[2]
[1, 'Manipal']
[1, 'Manipal', 'University', 2, 1, 'Manipal', 'University', 2]
[1, 'Manipal', 'University', 2, 1, 'Manipal', 'University', 2, 1, 'Manipal', 'University', 2]

2.3 WAP in python to create set and perform various operations on the set
Python Set is the unordered collection of the data type. It is iterable, mutable (can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element.

Source Code
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)

OUTPUT
{'James', 'Python', 2, 3}
{'Python', 2, 3, 10, 'James'}
{'Python', 3, 10, 'James'}

2.4 WAP in python to create Dictionary and perform various operations on the
dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a
hash table where each key stores a specific value. Key can hold any primitive data type,
whereas value is an arbitrary Python object. The items in the dictionary are separated with the
comma (,) and enclosed in the curly braces {}.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

Source Code
d = {1:'Jaipur', 2:'Ajmer', 3:'Jodhpur', 4:'Udaipur'}
# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())

OUTPUT
{1: 'Jaipur', 2: 'Ajmer', 3: 'Jodhpur', 4: 'Udaipur'}
1st name is Jaipur
2nd name is Udaipur
dict_keys([1, 2, 3, 4])
dict_values(['Jaipur', 'Ajmer', 'Jodhpur', 'Udaipur'])

2.5 WAP in python to create Tuple and perform various operations on the Tuple.
A tuple is like the list in many ways. Like lists, tuples also contain the collection of the items of
different data types. The items of the tuple are separated with a comma (,) and enclosed in
parentheses (). A tuple is a read-only data structure as we can't modify the size and value of the
items of a tuple. tup = ("hi", "Python", 2)

Source Code
tup = ("Manipal", "University", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
tup[2] = "jaipur"

OUTPUT
<class 'tuple'>
('Manipal', 'University', 2)
('University', 2)
('Manipal',)
('Manipal', 'University', 2, 'Manipal', 'University', 2)
('Manipal', 'University', 2, 'Manipal', 'University', 2, 'Manipal', 'University', 2)
TypeError: 'tuple' object does not support item assignment

2.6 WAP in python to create Graph using third party library.


Python provides one of a most popular plotting library called Matplotlib. It is open-
source, cross-platform for making 2D plots for from data in array. It is generally used for
data visualization and represent through the various graphs.

Source Code
from matplotlib import pyplot as plt
Names = ['Arun','James','Ricky','Patrick']
Marks = [51,87,45,67]
plt.bar(Names,Marks,color = 'blue')
plt.title('Result')
plt.xlabel('Names')
plt.ylabel('Marks')
plt.show()

OUTPUT
3. Control Statements
3.1 WAP in python to check whether a number is even or odd
Source Code
# 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: 43
43 is Odd

3.2 WAP in python to find the largest number among the three input numbers
Source Code
# Python program to find the largest number among the three input numbers
# 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
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14.

3.3 WAP in python to print prime numbers in a given range.


Source Code
# First, we will take the input:
lower_value = int(input ("Please, Enter the Lowest Range Value: "))
upper_value = int(input ("Please, Enter the Upper Range Value: "))
print ("The Prime Numbers in the range are: ")
for number in range (lower_value, upper_value + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)

OUTPUT
Please, Enter the Lowest Range Value: 14
Please, Enter the Upper Range Value: 97
The Prime Numbers in the range are:
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

3.4 WAP in python to check whether a number is an Armstrong number or not.


Source Code
# Python program to check if the number is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

OUTPUT
Enter a number: 663
663 is not an Armstrong number
3.5 WAP in python to check if a year is a leap year
Source Code
# Python program to check if year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))

OUTPUT
2000 is a leap year

3.6 WAP in python to construct various ‘*’ patterns


Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")

OUTPUT
*
**
***
****
*****

Source Code
rows = int(input("Enter number of rows: "))
k=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k=0
print()
OUTPUT
*
***
*****
*******
*********

3.7 WAP in Python to find factorial of a number provided by user.


Source Code
# change the value for a different result
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

OUTPUT
The factorial of 7 is 5040

3.8 WAP in python to find sum of natural numbers up to nth term


Source Code
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

OUTPUT
The sum is 136

3.9 WAP in python to display the Fibonacci sequence up to nth term.


Source Code
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")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

OUTPUT
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

3.10 WAP in python to demonstrate break and continue


Source Code (break)
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")

OUTPUT
s
t
r
The end

Source Code (continue)


for val in "string":
if val == "i":
continue
print(val)

print("The end")

OUTPUT
s
t
r
n
g
The end

4. Functions
4.1 WAP in Python to make a Simple Calculator using function
Source Code
# Program make a simple calculator
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")

OUTPUT

4.2 WAP in python to print LCM and HCF for the given numbers
Source Code (LCM)
def compute_lcm(x, y):
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = 54
num2 = 24
print("The L.C.M. is", compute_lcm(num1, num2))

OUTPUT
The L.C.M. is 216

Source Code (HCF)


# Python program to find H.C.F of two numbers
# define a function
def compute_hcf(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
print("The H.C.F. is", compute_hcf(num1, num2))

OUTPUT
The H.C.F. is 6

4.3 WAP in python to print factorial of a number using recursion


Source Code
def factorial(x):
"""This is a recursive function to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))

OUTPUT
The factorial of 3 is 6

4.4 WAP in python to print Fibonacci series up to nth term using recursion
Source Code
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

OUTPUT
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
5. Object oriented concept
5.1 WAP in python to demonstrate the concept of class and object.
Source Code
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person class
harry = Person()
# Output: <function Person.greet>
print(Person.greet)
# Output: <bound method Person.greet of < main .Person object>>
print(harry.greet)
# Calling object's greet() method
# Output: Hello
harry.greet()

OUTPUT
<function Person.greet at 0x7fd288e4e160>
<bound method Person.greet of < main .Person object at 0x7fd288e9fa30>>
Hello

5.2 WAP in python to demonstrate the concept of multilevel inheritance.


Source Code
class Family:
def show_family(self):
print("This is our family:")
# Father class inherited from Family
class Father(Family):
fathername = ""
def show_father(self):
print(self.fathername)
# Mother class inherited from Family
class Mother(Family):
mothername = ""
def show_mother(self):
print(self.mothername)
# Son class inherited from Father and Mother classes
class Son(Father, Mother):
def show_parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son() # Object of Son class
s1.fathername = "Mark"
s1.mothername = "Sonia"
s1.show_family()
s1.show_parent()

OUTPUT
This is our family:
Father : Mark
Mother : Sonia

5.3 WAP in python to demonstrate the concept of multiple inheritance.


Source Code
class A:
def A(self):
print('This is class A.')
class B:
def B(self):
print('This is class B.')
class C(A,B):
def C(self):
print('This is class C which inherits features of both classes A and B.')
o = C()
o.A()
o.B()
o.C()

OUTPUT
This is class A.
This is class B.
This is class C which inherits features of both classes A and B.

6. Python Library, Networking (WEB Programming) & GUI


6.1 WAP in python to demonstrate the use of various python library (use of
libraries in string and text handling).
Python standard library
The Python Standard Library contains the exact syntax, semantics, and tokens of
Python. It contains built-in modules that provide access to basic system functionality
like I/O and some other core modules. Most of the Python Libraries are written in the
C programming language. The Python standard library consists of more than 200 core
modules. All these work together to make Python a high-level programming language.
Python Standard Library plays a very important role. Without it, the programmers
can’t have access to the functionalities of Python. But other than this, there are several
other libraries in Python that make a programmer’s life easier. Let’s have a look at
some of the commonly used libraries:
1. TensorFlow: This library was developed by Google in collaboration with the Brain
Team. It is an open-source library used for high-level computations. It is also used
in machine learning and deep learning algorithms. It contains a large number of
tensor operations. Researchers also use this Python library to solve complex
computations in Mathematics and Physics.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s why
it is used in data analysis. It is also an open-source library and plots high-defined
figures like pie charts, histograms, scatterplots, graphs, etc.
3. Pandas: Pandas are an important library for data scientists. It is an open-source
machine learning library that provides flexible high-level data structures and a
variety of analysis tools. It eases data analysis, data manipulation, and cleaning of
data. Pandas support operations like Sorting, Re-indexing, Iteration, Concatenation,
Conversion of data, Visualizations, Aggregations, etc.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly
used library. It is a popular machine learning library that supports large matrices
and multi-dimensional data. It consists of in-built mathematical functions for easy
computations. Even libraries like TensorFlow use Numpy internally to perform
several operations on tensors. Array Interface is one of the key features of this
library.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source
library used for high-level scientific computations. This library is built over an
extension of Numpy. It works with Numpy to handle complex computations. While
Numpy allows sorting and indexing of array data, the numerical data code is stored
in SciPy. It is also widely used by application developers and engineers.
6. Scrapy: It is an open-source library that is used for extracting data from websites.
It provides very fast web crawling and high-level screen scraping. It can also be
used for data mining and automated testing of data.
7. Scikit-learn: It is a famous Python library to work with complex data. Scikit-learn
is an open-source library that supports machine learning. It supports variously
supervised and unsupervised algorithms like linear regression, classification,
clustering, etc. This library works in association with Numpy and SciPy.
8. PyGame: This library provides an easy interface to the Standard Directmedia
Library (SDL) platform-independent graphics, audio, and input libraries. It is used
for developing video games using computer graphics and audio libraries along with
Python programming language.
9. PyTorch: PyTorch is the largest machine learning library that optimizes tensor
computations. It has rich APIs to perform tensor computations with strong GPU
acceleration. It also helps to solve application issues related to neural networks.
10. PyBrain: The name “PyBrain” stands for Python Based Reinforcement Learning,
Artificial Intelligence, and Neural Networks library. It is an open-source library
built for beginners in the field of Machine Learning. It provides fast and easy-to-
use algorithms for machine learning tasks. It is so flexible and easily understandable
and that’s why is really helpful for developers that are new in research fields.

Source Code
# Importing math library
import math
A = 16
print(math.sqrt(A))

OUTPUT
4.0

6.2 Write a simple client server program in python using sockets.


Source Code
# An example script to connect to Google using socket
# programming in Python
import socket # for socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except socket.error as err:
print ("socket creation failed with error %s" %(err))
# default port for socket
port = 80
try:
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
# this means could not resolve the host
print ("there was an error resolving the host")
sys.exit()
# connecting to the server
s.connect((host_ip, port))
print ("the socket has successfully connected to google")

OUTPUT
Socket successfully created
the socket has successfully connected to google
on port == 173.194.40.19

6.3 WAP in python to build a Calculator using tkinter


Source Code
# Python program to create a simple GUI
# calculator using Tkinter
# import everything from tkinter module
from tkinter import *
# globally declare the expression variable
expression = ""
# Function to update expression
# in the text entry box
def press(num):
# point out the global expression variable
global expression
# concatenation of string
expression = expression + str(num)
# update the expression by using set method
equation.set(expression)
# Function to evaluate the final expression
def equalpress():
# Try and except statement is used
# for handling the errors like zero
# division error etc.
# Put that code inside the try block
# which may generate the error
try:
global expression
# eval function evaluate the expression
# and str function convert the result
# into string
total = str(eval(expression))
equation.set(total)
# initialize the expression variable
# by empty string
expression = ""
# if error is generate then handle
# by the except block
except:
equation.set(" error ")
expression = ""
# Function to clear the contents
# of text entry box
def clear():
global expression
expression = ""
equation.set("")
# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()
# set the background colour of GUI window
gui.configure(background="light green")
# set the title of GUI window
gui.title("Simple Calculator")
# set the configuration of GUI window
gui.geometry("270x150")
# StringVar() is the variable class
# we create an instance of this class
equation = StringVar()
# create the text entry box for
# showing the expression .
expression_field = Entry(gui, textvariable=equation)
# grid method is used for placing
# the widgets at respective positions
# in table like structure .
expression_field.grid(columnspan=4, ipadx=70)
# create a Buttons and place at a particular
# location inside the root window .
# when user press the button, the command or
# function affiliated to that button is executed .
button1 = Button(gui, text=' 1 ', fg='black', bg='red',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='red',
command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='red',
command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='red',
command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='red',
command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='red',
command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='red',
command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='red',
command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='red',
command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='red',
command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='red',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='red',
command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='red',
command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='red',
command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='red',
command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='red',
command=clear, height=1, width=7)
clear.grid(row=5, column='1')
Decimal= Button(gui, text='.', fg='black', bg='red',
command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()

OUTPUT

6.4 WAP in python to build a text editor using tkinter

from tkinter import *


root = Tk()
root.geometry("350x250")
root.title("Sticky Notes")
root.minsize(height=250, width=350)
root.maxsize(height=250, width=350)
# adding scrollbar
scrollbar = Scrollbar(root)
# packing scrollbar
scrollbar.pack(side=RIGHT,
fill=Y)
text_info = Text(root,
yscrollcommand=scrollbar.set)
text_info.pack(fill=BOTH)
# configuring the scrollbar
scrollbar.config(command=text_info.yview)
root.mainloop()

OUTPUT

You might also like