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

Pp Lab Manual

Uploaded by

c8221251
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Pp Lab Manual

Uploaded by

c8221251
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

GURU NANAK INSTITUTE OF TECHNOLOGY

GURU NANAK INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PYTHON PROGRAMMING[20ES0CS04]
LAB MANUAL

For the Academic Year 2023-2024 [R22]


I B.Tech / IInd Semester

1
GURU NANAK INSTITUTE OF TECHNOLOGY
Guru Nanak Institute of Technoloogy
Ibrahimpatnam, R R District – 501 506.

2
GURU NANAK INSTITUTE OF TECHNOLOGY

GURU NANAK INSTITUTE OF TECHNOLOGY


Ibrahimpatnam, R. R. Dist-501 506.
Department of Information Technology

LAB MANUALFOR THE ACADEMIC YEAR: 2023-24

SUB : PYTHON PROGRAMMINGLAB

SUB CODE : 20ES0CS04

SEMESTER : B.TechCommon for All

STREAM : Common for All

INSTRUCTORES :

PROGRAMMER :

VENUE : BLOCK
: CSE

Authorized by
HOD-H&S

3
GURU NANAK INSTITUTE OF TECHNOLOGY

GURU NANAK INSTITUTE OF TECHNOLOGY


Ibrahimpatnam, R. R. Dist-501 506.
Department of Information Technology

INSTITUTE VISION

The vision of the GNIT:


To be a world –class educational and research institution in the service of humanity by promoting
high quality Engineering and Management Education.

The Mission GNIT, in pursuance of its vision:


M1: Imbibe soft skills and technical skills.
M2: Develop the faculty to reach the international standards.
M3: Maintain high academic standards and teaching quality that promotes the analytical thinking
and independent judgment.
M4: Promote research, innovation and Product development by collaboration with reputed foreign
Universities.
M5: Offer collaborative industry programs in emerging areas and spirit of enterprise.

4
GURU NANAK INSTITUTE OF TECHNOLOGY

GURU NANAK INSTITUTE OF TECHNOLOGY


Ibrahimpatnam, R. R. Dist-501 506.
Department of Computer Science &Engineering

DEPARTMENT VISION

Vision of the Computer Science and Engineering Department:


To be a leading department of Computer Science and Engineering in the region

Mission of the Computer Science and Engineering Department:


1. Nurture young individuals into knowledgeable, skilful and ethical professionals in their pursuit
of Computer Science and Engineering.
2. Nurture the faculty to expose them to world-class infrastructure.
3. Sustain high performance by excellence in teaching, research and innovations.
4. Extensive partnerships and collaborations with foreign universities for technology up
gradation.
5. Develop Industry-Interaction for innovation and product development.

5
GURU NANAK INSTITUTE OF TECHNOLOGY

Programme Educational Objectives

PEO-1:Graduates shall have the ability to apply knowledge and technical skills across the
disciplines and in emerging areas of Computer Science and Engineering for higher studies, research,
employability, product development and handle realistic problems.

PEO-2:Graduates shall possess managerial skills, maintain ethical conduct, sense of responsibility to
serve the society and to protect the environment.

PEO-3:Graduates shall possess academic excellence with innovative insight, soft skills, leadership
qualities, knowledge of contemporary issues for successful professional career.

Program Outcomes (POs)


A. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.

B. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics natural science, and engineering sciences.

C. Design / development of solutions: Design solutions for complex engineering problems


and design system components or process that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, society and environmental
consideration.

D. 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.

6
GURU NANAK INSTITUTE OF TECHNOLOGY

E. 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.

F. 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.

G. 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.

H. Ethics: Apply ethics principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

I. Individual and team work: Function effectively as an individual, and as a member or


leader in diverse teams, and in multidisciplinary settings.

J. 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.

K. 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 an team, to manage projects and in multidisciplinary environments.

L. 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.

7
GURU NANAK INSTITUTE OF TECHNOLOGY

Course Objectives (COs)


1. To install and run the Python interpreter
2. To learn control structures.
3. To Understand Lists, Dictionaries in python
4. To Handle Strings and Files in Python.

CourseOutcomes (COs)

After completion of the course, the student would be able to


1. Develop the application specific codes using python.
2. Understand Strings, Lists, Tuples and Dictionaries in Python
3. Verify programs using modular approach, file I/O, Python standard library
4. Implement Digital Systems using Python

8
GURU NANAK INSTITUTE OF TECHNOLOGY

INDEX

Remarks
Sl.No CONTENT Page. No
If any

1 Introduction About Lab 12

2 Guidelines to Students 16

List of Lab Exercises


3 17
Syllabus Programs

4 Solutions for Programs 23-130

5 References 20

Result: ________________ Signature of the faculty incharge

9
GURU NANAK INSTITUTE OF TECHNOLOGY
Contents of Lab Manual

Contents of Lab manual(student):


1. Index
2. List of experiments as per the university.
3. List of experiments to be conducted for this semester. Add the additional experiments
list separately.
4. Cycle to indicate schedule and the batch size.
5. Content of the experiment. (for CSE/Computer labs only flow charts/ algorithm
should be given with input and output).

Contents of Lab manual(Teacher):


1. Index
2. List of experiments as per the university.
3. List of experiments to be conducted for this semester. Add the additional experiments
list separately.
4. Cycle to indicate schedule and the batch size.
5. Content of the experiment. (for CSE/Computer labs flow charts/ algorithm should be
given with input and output. Program should also include. For other than computer
labs master reading to be taken and noted).

10
GURU NANAK INSTITUTE OF TECHNOLOGY
INDEX

S.No Contents Page.no

12
1 Lab Objective
13
2 Lab outcomes
14
3 Introduction About Lab
Guidelines to students 15

a). Standard Operating Procedure (SOP)


4
b). General guidelines

List of experiments as per the university curriculum 20


5
54-
6 List of Additional Experiments
24

Content of the experiment.

1. Objective of the Experiment


2. Hardware & Software Requirements
7 3. Pre- requisite
4. Flow chart/ algorithm with inputs and
outputs
5. Program
6. Output
7. Conclusion

22
8 Text Books / Reference Books

11
GURU NANAK INSTITUTE OF TECHNOLOGY

Python Programming LAB

LAB OBJECTIVE

1. To install and run the Python interpreter


2. To learn control structures.
3. To Understand Lists, Dictionaries in python
4. To Handle Strings and Files in Python.

12
GURU NANAK INSTITUTE OF TECHNOLOGY
Python Programming LAB

2. LAB OUTCOME

1.Develop the application specific codes using python.


2. Understand Strings, Lists, Tuples and Dictionaries in Python
3. Verify programs using modular approach, file I/O, Python standard library
4. Implement Digital Systems using Python

13
GURU NANAK INSTITUTE OF TECHNOLOGY
3. INTRODUCTION ABOUT LAB

There are 60 systems (Compaq Presario) installed in this Lab. Their configurations are as
follows:

Processor : Intel(R) Core i3 processor


RAM : 4 GB
Hard Disk : 160 GB
Mouse : Optical Mouse

Software

 All systems are configured in DUAL BOOT mode i.e., Students can boot from
Windows XP or Linux as per their lab requirement. This is very useful for students
because they are familiar with different Operating Systems so that they can
execute their programs in different programming environments.
 Each student has a separate login for database access Oracle 9i client version is
installed in all systems. On the server, account for each student has been created.
This is very useful because students can save their work (scenarios’, PL / SQL
programs, data related projects, etc) in their own accounts. Each student work is
safe and secure from other students.

 Softwares installed:Python software (python 3.8.0) is installed .


 Systems are provided for students in the 1:1 ratio.
 Systems are assigned numbers and same system is allotted for students when they
do the lab.

14
GURU NANAK INSTITUTE OF TECHNOLOGY

A. STANDARD OPERATING PROCEDURE – SOP

a) Explanation on today’s experiment by the concerned faculty using OHP/PPT covering the
following aspects: 25 mins.

1) Name of the experiment/Aim


2) Software/Hardware required
3) Commands with suitable Options
4) Test Data
1) Valid data sets
2) Limiting value sets
3) Invalid data sets
b) Writing of shell programs by the students 25 min.
c) Compiling and execution of the program

100 mins.
Writing of the experiment in the Observation Book:
The students will write the today’s experiment in the Observation book as per the
following format:
a) Name of the experiment/Aim
b) Software/Hardware required
c) Commands with suitable Options
d) Shell Programs/System call using C-Programs
e) Test Data
a. Valid data sets
b. Limiting value sets
c. Invalid data sets
f) Results for different data sets
g) Viva-Voice Questions and Answers
h) Errors observed (if any) during compilation/execution

15
GURU NANAK INSTITUTE OF TECHNOLOGY
i) Signature of the Faculty

B. Guide Lines to Students in Lab

Disciplinary to be maintained by the students in the Lab:

 Students are required to carry their lab observation book and record book with completed
experiments while entering the lab.
 Students must use the equipment with care. Any damage is caused student is punishable
 Students are not allowed to use their cell phones/pen drives/ CDs in labs.
 Students need to be maintain proper dress code along with ID Card
 Students are supposed to occupy the computers allotted to them and are not supposed to
talk or make noise in the lab.
 Students, after completion of each experiment they need to be updated in observation
notes and same to be updated in the record.
 Lab records need to be submitted after completion of experiment and get it corrected with
the concerned lab faculty.
 If a student is absent for any lab, they need to be completed the same experiment in the
free time before attending next lab.

Steps to perform experiments in the lab by the student

Step1: Students have to write the date, aim, S/W & H/W requirements for that experiment in the
observation book.
Step2: Students have to listen and understand the experiment explained by the faculty and note
down the important points in the observation book.
Step3: Students need to write procedure/algorithm in the observation book.
Step4: Analyze and Develop/implement the logic of the program by the student in respective
platform
Step5: after approval of logic of the experiment by the faculty then the experiment has to be
executed on the system.
Step6: After successful execution the results are to be shown to the faculty and noted the same in
the observation book.
Step7: Students need to attend the Viva-Voce on that experiment and write the same in the
observation book.

16
GURU NANAK INSTITUTE OF TECHNOLOGY
Step8: Update the completed experiment in the record and submit to the concerned faculty in-
charge.

Instructions to maintain the record

 Before start of the first lab they have to buy the record and bring the record to the lab.
 Regularly (Weekly) update the record after completion of the experiment and get it
corrected with concerned lab in-charge for continuous evaluation.
 In case the record is lost inform the same day to the faculty in charge and get the new
record within 2 days the record has to be submitted and get it corrected by the faculty.
 If record is not submitted in time or record is not written properly, the evaluation marks
(5M) will be deducted.

Awarding the marks for day to day evaluation:

Total marks for day to day evaluation is 10 Marks as per JNTUH.


These 10 Marks are distributed as:

Record 5 Marks

Exp setup/program written 3 Marks


and execution
Result and Viva-Voce 2 Marks

Allocation of Marks for Lab Internal:

Total marks for lab internal are 40 Marks as per JNTUH.


These 40 Marks are distributed as:
Average of day to day evaluation marks:10 Marks
Lab Mid exam: 10 Marks
Viva-Voice: 10 Marks
Experiment Design: 10 Marks

Allocation of Marks for Lab External

Total marks for lab internal are 60 Marks as per JNTUH.


These 60 Marks are distributed as:
Program Written: 10 Marks
17
GURU NANAK INSTITUTE OF TECHNOLOGY
Program Execution and Result: 15 Marks
Out/ Results: 15 Marks
Viva-Voce: 10Marks
Presentation: 10 Marks
4. Guidelines to Students

 Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care. Any
damage is caused is punishable.

 Students are required to carry their observation / programs book with completed exercises
while entering the lab.

 Students are supposed to occupy the machines allotted to them and are not supposed to
talk or make noise in the lab. The allocation is put up on the lab notice board.

 Lab can be used in free time / lunch hours by the students who need to use the systems
should take prior permission from the lab in-charge.

 Lab records need to be submitted on or before date of submission.

 Students are not supposed to use floppy disks

 Use of computer network is encouraged.

18
GURU NANAK INSTITUTE OF TECHNOLOGY

5. List of Lab Experiments as per Syllabus

19
GURU NANAK INSTITUTE OF TECHNOLOGY
Week11.i) Use a web browser to go to the Python website http://python.org. This page contains information
about Python and links to Python-related pages, and it gives you the ability to search the Python
documentation.
ii) Start the Python interpreter and type help() to start the online help utility.
2. Start a Python interpreter and use it as a Calculator.
3. i) Write a program to calculate compound interest when principal, rate and number of periods are given.
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through keyboard and print the details.
Week 21. Print the below triangle using for loop.
5
44
333
2222
11111
2. Write a program to check whether the given input is digit or lowercase character or uppercase character or a
special character (use 'if-else-if' ladder)
3. Python Program to Print the Fibonacci sequence using while loop 4. Python program to print all prime
numbers in a given interval (use break)
Week 3 1. i) Write a program to convert a list and tuple into arrays.
ii) Write a program to find common values between two arrays.
2. Write a function called gcd that takes parameters a and b and returns their greatest common divisor.
3. Write a function called palindrome that takes a string argument and returns True if it is a palindrome and
False otherwise. Remember that you can use the built-in function len to check the length of a string.
Week 4:1. Write a function called is sorted that takes a list as a parameter and returns True if the list is sorted
in ascending order and False otherwise.
2. Write a function called has duplicates that takes a list and returns True if there is any element that appears
more than once. It should not modify the original list.
i). Write a function called remove duplicates that takes a list and returns a new list with only the unique
elements from the original. Hint: they don’t have to be in the same order.
ii). The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add “I”, “a”,
and the empty string.
iii). Write a python code to read dictionary values from the user. Construct a function to invert its content. i.e.,
keys should be values and values should be keys.
3. i) Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e'
ii) Remove the given word in all the places in a string?
iii) Write a function that takes a sentence as an input parameter and replaces the first letter of every word with
the corresponding upper case letter and the rest of the letters in the word by corresponding letters in lower
case without using a built-in function?
4. Writes a recursive function that generates all binary strings of n-bit length
Week 5 – 1. i) Write a python program that defines a matrix and prints
ii) Write a python program to perform addition of two square matrices
iii) Write a python program to perform multiplication of two square matrices
2. How do you make a module? Give an example of construction of a module using different geometrical
shapes and operations on them as its functions.
3. Use the structure of exception handling all general purpose exceptions.
Week 6 – 1. a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as arguments and
draws a representation of the Rectangle on the Canvas.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle so that it uses the color
attribute as the fill color.
c. Write a function called draw_point that takes a Canvas and a Point as arguments and draws a representation
of the Point on the Canvas.
d. Define a new class called Circle with appropriate attributes and instantiate a few Circle objects. Write a20
function called draw_circle that draws circles on the canvas.
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in multiple levels of
Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it for correctness.
GURU NANAK INSTITUTE OF TECHNOLOGY
Week 7 – 1. Write a Python code to merge two given file contents into a third file.
2. Write a Python code to open a given file and construct a function to check for given words present in
it and display on found.
3. Write a Python code to Read text from a text file, find the word with most number of occurrences
4. Write a function that reads a file file1 and displays the number of words, number of vowels, blank
spaces, lower case letters and uppercase letters.
Week 8 – 1. Import numpy, Plotpy and Scipy and explore their functionalities.
2. a) Install NumPy package with pip and explore it.
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
5. Write a GUI program to create a window wizard having two text labels, two text fields and two
buttons as Submit and Reset.

6. Reference Books

 Comdex Information Technology course tool kit Vikas Gupta, WILEY Dreamtech
 The Complete Computer upgrade and repair book, 3rd edition Cheryl A Schmidt,
WILEY Dreamtech
 Introduction to Information Technology, ITL Education Solutions limited, Pearson
Education.
 PC Hardware - A Handbook – Kate J. Chase PHI (Microsoft)
 LaTeX Companion – Leslie Lamport, PHI/Pearson.

21
GURU NANAK INSTITUTE OF TECHNOLOGY
 IT Essentials PC Hardware and Software Companion Guide Third Edition by David
Anfinson and Ken Quamme. – CISCO Press, Pearson Education.
 IT Essentials PC Hardware and Software Labs and Study Guide Third Edition by Patrick
Regan – CISCO Press, Pearson Education.

TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland
2. Learning Python, Mark Lutz, O'reilly
REFERENCE BOOKS:
1. Python Programming: A Modern Approach, VamsiKurama, Pearson
2. Python Programming A Modular Approach with Graphics, Database, Mobile, and Web Applications,
SheetalTaneja, Naveen Kumar, Pearson
3. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India Edition
4. Think Python, Allen Downey, Green Tea Press
5. Introduction to Python, Kenneth A. Lambert, Cengage

INDEX
S.No Name Of the Experiment Page Numbers
INTRODUCTION TO PYTHON PROGRAMMING
1 24-25
2 WEEK1 26-28
3 WEEK2 29-32
4 WEEK3 33-34
5 WEEK4 35-39
6 WEEK5 40-42
7 WEEK6 43-44
8 WEEK7 45-48

22
GURU NANAK INSTITUTE OF TECHNOLOGY
9 WEEK8 49-53

INTRODUCTION TO PYTHON PROGRAMMING


• • Python is a high-level, general-purpose, interpreted, interactive and object-oriented
programming language.
• • It was created by Guido van Rossum during 1985- 1990.
• • Like Perl, Python source code is also available under the GNU General Public License (GPL).

Why the name python?


Guido van Rossum was interested on watching a comedy show, which is telecasting on the BBC channel
from 1969 to 1974 The complete Monty Python's Flying Circus.
Guido Van Rossum thought he needed a name that was short, unique, and slightly mysterious for his
programming language, so he decided to call the language Python.

23
GURU NANAK INSTITUTE OF TECHNOLOGY
FEATURES OF PYTHON
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed
to be highly readable. It uses English keywords frequently where as other languages use punctuation, and
it has fewer syntactical constructions than other languages. Python's features include the following –
• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross platform compatible on
UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
• Extendable − We can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.

24
GURU NANAK INSTITUTE OF TECHNOLOGY
• GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of
Unix.
• Scalable − Python provides a better structure and support for large programs than shell scripting.
APPLICATIONS OF PYTHON PROGRAMMING
• • Web Development
• • Game Development
• • Scientific and Numeric applications
• • Artificial Intelligence and Machine Learning based applications
• • Data Science related applications
• • Desktop GUI applications
• • Software Development
• • Enterprise-level/Business Applications
• • Education programs and training courses
• • Web Scraping Applications
• • Image Processing and Graphic Design Applications
• • Data Analysis

25
GURU NANAK INSTITUTE OF TECHNOLOGY
Experiment 1:
I. Use a web browser to go to the Python website http://python.org. This page contains
information about Python and links to Python-related pages, and it gives you the ability to
search the Python documentation.

CODE:
import webbrowser
webbrowser.open('http://www.python.org')

II. Start the Python interpreter and type help() to start the online help utility.

CODE:
>>> help()

Welcome to Python 3.9's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.9/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type


"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help>

Experiment 2: Start a Python interpreter and use it as a Calculator.

CODE:
first = input("Enter first number : ")
second = input("Enter second number : ")
first = int(first)
second = int(second)
print("----press keys for operator (+,-,*,/,%)----------")
operator = input("Enter operator : ")
if operator == "+":
print(first + second)
elif operator == "-":
print(first - second)
elif operator == "*":
print(first * second)
26
GURU NANAK INSTITUTE OF TECHNOLOGY
elif operator == "/":
print(first / second)
elif operator == "%":
print(first % second)
else:
print("Invalid Operation")

27
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
Enter first number: 5
Enter second number: 6
----press keys for operator (+,-,*,/,%)----------
Enter operator : +
11

Experiment 3:
i. Write a program to calculate compound interest when principal, rate and number of
periods are given.

CODE:
#Python program to compute compound interest
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time in years: "))
#compute compound interest
compound_interest = principal * ((1 + rate/100) ** time) - principal
#print
print("The compound interest is:", compound_interest)

Output:
Enter the principal amount: 50000
Enter the number of years: 5
Enter the rate of interest: 12
The compound interest is: 88117.08416000004

ii. Given coordinates (x1, y1), (x2, y2) find the distance between two points.

CODE:
# Python Program to Calculate Distance

# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))

# Calculating distance
d = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5

# Displaying result
#print('Distance = %f' %(d))
print("distance between",(x1,x2),"and",(y1,y2),"is : %f" %(d))

28
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
enter x1 : 15
enter x2 : 10
enter y1 : 4
enter y2 : 22
distance between (15, 10) and (4, 22) is : 18.681541

29
GURU NANAK INSTITUTE OF TECHNOLOGY
Experiment 4: Read name, address, email and phone number of a person through
keyboard and print the details.

CODE:
# read name, contact, email and birthday from user and print them
print("Enter your name: ", end="")
name = input()
print("Enter your phone number: ", end="")
ph_num = input()
print("Enter your email: ", end="")
email = input()
print("Enter your address: ", end="")
address = input()
print("Name: ", name)
print("Phone Number: ", ph_num)
print("Email: ", email)
print("Address: ", address)

Output:
Enter your name: Rahul
Enter your phone number: 1234567890
Enter your email: [email protected]
Enter your address: ibrahimpatnam
Name: Rahul
Phone Number: 1234567890
Email: [email protected]
Address: Ibrahimpatnam

30
GURU NANAK INSTITUTE OF TECHNOLOGY

Experiment 1: Print the below triangle using for loop.


5
54
543
5432
54321

CODE:

# outer loop
for i in range(0, 5):
count=5;
# nested loop
for j in range(0, i+1):
# display number
print(count-j,end="")
# new line after each row
print("\r")

Output:
5
54
543
5432
54321

Experiment 2: Write a program to check whether the given input is digit or lowercase
character or uppercase character or a special character (use 'if-else-if' ladder).

CODE:

# Python Program to check character is Lowercase or Uppercase


ch = input("Please Enter Your Own Character : ")
if ch >= '0' and ch <= '9':
print("The Given Character ", ch, "is a Digit")
elif ch.isupper():
print("The Given Character ", ch, "is an Uppercase Alphabet")
elif ch.islower():
print("The Given Character ", ch, "is a Lowercase Alphabet")
else:
print("The Given Character ", ch, "is a Special character")
31
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
Please Enter Your Own Character : A
The Given Character A is an Uppercase Alphabet

Experiment 3: Python Program to Print the Fibonacci sequence using while loop.

CODE:
# Program to display the Fibonacci sequence up to n-th term
num = int(input("Enter the Fibonacci Number Range: "))

n1 = 0
n2 = 1
Sum = 0
i=0

print("Fibonacci Series:")
while(i < num):
print(n1, end = ' ')
Sum = Sum + n1
Next = n1 + n2
n1 = n2
n2 = Next
i=i+1

print("\nSum of Fibonacci Series Numbers: %d" %Sum)

Output:
Enter the Fibonacci Number Range: 8
Fibonacci Series:
0 1 1 2 3 5 8 13
Sum of Fibonacci Series Numbers: 33

Experiment 4: Python program to print all prime numbers in a given interval (use break).

CODE:
# Python program to display all the prime numbers within an interval
lower = 1
upper = 50

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:
32
GURU NANAK INSTITUTE OF TECHNOLOGY
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num, end =" ")

Output:
Prime numbers between 1 and 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

33
GURU NANAK INSTITUTE OF TECHNOLOGY
Experiment 1:
i. Write a program to convert a list and tuple into arrays.
CODE:
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array: ")
print(np.asarray(my_list))
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Tuple to array: ")
print(np.asarray(my_tuple))
Output:
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]

ii. Write a program to find common values between two arrays.


CODE:
import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2))
Output:
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]

34
GURU NANAK INSTITUTE OF TECHNOLOGY

Experiment 2: Write
a function called gcd that takes parameters a and
b and returns their greatest common divisor.
CODE:
def GCD(x, y):
if x > y:
small = y
else:
small = x

for i in range(1, small + 1):


if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd

a = 60
b = 48
# prints 12
print ("The gcd of 60 and 48 is: ", end="")
print (GCD(60,48))

Output:
The gcd of 60 and 48 is: 12

C5, d0, d2, E0

35
GURU NANAK INSTITUTE OF TECHNOLOGY

Write a function called is sorted that takes a list as a


parameter and returns True if the list is sorted in
ascending order and False otherwise.
CODE:
def is_sorted(lst):
return lst == sorted(lst)

lst=[2,4,6,8,10]
print(is_sorted(lst))

OUTPUT:
True

36
GURU NANAK INSTITUTE OF TECHNOLOGY

2. Write a function called has duplicates that takes a list and


returns True if there is any element that appears more than
once. It should not modify the original list.

CODE:
def has_duplicates(lst):
return len(lst) != len(set(lst))

my_list = [1, 2, 3, 2, 4, 1, 5, 3]
result = has_duplicates(my_list)
print(result)
Output:
True

37
GURU NANAK INSTITUTE OF TECHNOLOGY
i). Write a function called remove duplicates that takes a list and returns a new list with
only the unique elements from the original. Hint: they don’t have to be in the same order.
def remove_duplicates(lst):
unique_elements = []
for element in lst:
if element not in unique_elements:
unique_elements.append(element)
return unique_elements
my_list = [1, 2, 3, 2, 4, 1, 5, 3]
result = remove_duplicates(my_list)
print(result)

Output:
[1, 2, 3, 4, 5]

iii). Write a python code to read dictionary values from the user. Construct a function to
invert its content. i.e., keys should be values and values should be keys.
CODE:
def invert_dictionary(dictionary):
inverted_dict = {}
for key, value in dictionary.items():
inverted_dict[value] = key
return inverted_dict
# Read dictionary values from the user
dictionary = {}
n = int(input("Enter the number of key-value pairs in the dictionary: "))
for i in range(n):
key = input("Enter the key: ")
value = input("Enter the value: ")
dictionary[key] = value

# Invert the dictionary


inverted_dictionary = invert_dictionary(dictionary)

# Print the inverted dictionary


print("Inverted Dictionary:")
for key, value in inverted_dictionary.items():
print(key, ":", value)

Output:
Enter the number of key-value pairs in the dictionary: 5
Enter the key: 1

38
GURU NANAK INSTITUTE OF TECHNOLOGY
Enter the value: a
Enter the key: 2
Enter the value: b
Enter the key: 3
Enter the value: c
Enter the key: 4
Enter the value: d
Enter the key: 5
Enter the value: e

Inverted Dictionary:
a:1
b:2
c:3
d:4
e:5

3. i) Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'

CODE:
# Read the word from the user
word = input("Enter a word: ")
# Add a comma between the characters of the word
word_with_comma = ','.join(word)
# Print the word with comma
print("Word with comma:", word_with_comma)

OTPUT
Enter a word: Apple
Word with comma: A,p,p,l,e

ii) Remove the given word in all the places in a string?


CODE:
# Read the string from the user
string = input("Enter a string: ")

# Read the word to be removed from the user


word = input("Enter the word to be removed: ")
# Remove the word from the string
result = string.replace(word, "")
# Print the modified string
print("Modified string:", result)

39
GURU NANAK INSTITUTE OF TECHNOLOGY

OUTPPUT:
Enter a string: GNITC
Enter the word to be removed: C
Modified string: GNIT

iii) Write a function that takes a sentence as an input parameter and replaces the first letter
of every word with the corresponding upper case letter and the rest of the letters in the
word by corresponding letters in lower case without using a built-in function?
CODE:
def capitalize_first_letter(sentence):
capitalized_sentence = ""
new_word = True
for char in sentence:
if new_word and char.isalpha():
char = char.upper()
new_word = False
elif not new_word and char.isalpha():
char = char.lower()
elif char.isspace():
new_word = True
capitalized_sentence += char
return capitalized_sentence

# Read the sentence from the user


sentence = input("Enter a sentence: ")

# Capitalize the first letter of each word in the sentence


capitalized_sentence = capitalize_first_letter(sentence)

# Print the modified sentence


print("Modified sentence:", capitalized_sentence)

OUTPUT:
Enter a sentence: Sanjay hasin esha
Modified sentence: Sanjay Hasin Esha

4. Writes a recursive function that generates all binary strings of n-bit length.

CODE:
def generate_binary_strings(n):
if n == 0:
return ['']
else:
previous_strings = generate_binary_strings(n-1)
40
GURU NANAK INSTITUTE OF TECHNOLOGY
return [string + bit for string in previous_strings for bit in ['0', '1']]

# Test the function


n = int(input("Enter the length of binary strings (n): "))
binary_strings = generate_binary_strings(n)

# Print the generated binary strings


print("Generated Binary Strings:")
for string in binary_strings:
print(string)

OUTPUT:
Enter the length of binary strings (n): 4
Generated Binary Strings:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

1. i) Write a python program that defines a matrix and prints.

CODE:
41
GURU NANAK INSTITUTE OF TECHNOLOGY
# Define a matrix
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

# Print the matrix


for row in matrix:
print(*row)

OUTPUT:
123
456
789

ii) Write a python program to perform addition of two square matrices

CODE:
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

matrix2 = [[9, 8, 7],


[6, 5, 4],
[3, 2, 1]]

# Perform the addition of matrices


result_matrix = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in
range(len(matrix1))]

# Print the result


print("Result:")
for row in result_matrix:
print(row)

OUTPUT:
Result:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

iii) Write a python program to perform multiplication of two square matrices:


CODE:
# Define the matrices
matrix1 = [[1, 2, 3],
42
GURU NANAK INSTITUTE OF TECHNOLOGY
[4, 5, 6],
[7, 8, 9]]

matrix2 = [[9, 8, 7],


[6, 5, 4],
[3, 2, 1]]

# Perform the multiplication of matrices using list comprehension and zip()


result_matrix = [[sum(a * b for a, b in zip(row1, col2)) for col2 in zip(*matrix2)] for row1 in
matrix1]

# Print the result


print("Result:")
for row in result_matrix:
print(row)

OUUTPUT:
Result:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]

2. How do you make a module? Give an example of construction of a module using


different geometrical shapes and operations on them as its functions.

CODE:
import geometry
# Calculate the area and perimeter of a rectangle
rectangle_length = 5
rectangle_width = 3
rectangle_area = geometry.rectangle_area(rectangle_length, rectangle_width)
rectangle_perimeter = geometry.rectangle_perimeter(rectangle_length, rectangle_width)

print("Rectangle Area:", rectangle_area)


print("Rectangle Perimeter:", rectangle_perimeter)

# Calculate the area and perimeter of a triangle


triangle_base = 4
triangle_height = 6
triangle_area = geometry.triangle_area(triangle_base, triangle_height)
triangle_perimeter = geometry.triangle_perimeter(triangle_base)

print("Triangle Area:", triangle_area)


print("Triangle Perimeter:", triangle_perimeter)
43
GURU NANAK INSTITUTE OF TECHNOLOGY

OUTPUT:
Rectangle Area: 15
Rectangle Perimeter: 16
Triangle Area: 12.0
Triangle Perimeter: 12

3. Use the structure of exception handling all general purpose exceptions.

CODE:
try:
# Code that may raise an exception
numerator = 10
denominator = 0
result = numerator / denominator

# If an exception occurs, the code below this line will not be executed
print("Result:", result)

except ZeroDivisionError:
# Handle ZeroDivisionError exception
print("Error: Cannot divide by zero!")

except ValueError:
# Handle ValueError exception
print("Error: Invalid value!")

except Exception as e:
# Handle any other general-purpose exception
print("Error:", str(e))

else:
# Code to execute if no exception occurs
print("No exception occurred.")

finally:
# Code that always executes, whether an exception occurred or not
print("Finally block executed.")

OUTPUT:
Error: Cannot divide by zero!
Finally block executed.

44
GURU NANAK INSTITUTE OF TECHNOLOGY

a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as


arguments and draws a representation of the Rectangle on the Canvas.

CODE:
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = [[' ' for _ in range(width)] for _ in range(height)]

def draw(self):
for row in self.grid:
print(' '.join(row))

class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height

def draw_rectangle(canvas, rectangle):


for i in range(rectangle.y, rectangle.y + rectangle.height):
for j in range(rectangle.x, rectangle.x + rectangle.width):
canvas.grid[i][j] = '#'

# Example usage
canvas = Canvas(10, 5)
rectangle = Rectangle(2, 1, 6, 3)
draw_rectangle(canvas, rectangle)
canvas.draw()

OUTPUT:
######
######
######
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle so
that it uses the color attribute as the fill color.

CODE:
45
GURU NANAK INSTITUTE OF TECHNOLOGY
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = [[' ' for _ in range(width)] for _ in range(height)]

def draw(self):
for row in self.grid:
print(' '.join(row))

class Rectangle:
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color

def draw_rectangle(canvas, rectangle):


for i in range(rectangle.y, rectangle.y + rectangle.height):
for j in range(rectangle.x, rectangle.x + rectangle.width):
canvas.grid[i][j] = rectangle.color

# Example usage
canvas = Canvas(10, 5)
rectangle = Rectangle(2, 1, 6, 3, 'red')
draw_rectangle(canvas, rectangle)
canvas.draw()

OUTPUT:
red red red red red red
red red red red red red
red red red red red red

1. Write a Python code to merge two given file contents into a third file.
46
GURU NANAK INSTITUTE OF TECHNOLOGY

CODE:
def merge_files(file1_path, file2_path, output_file_path):
try:
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2, open(output_file_path, 'w') as
output_file:
content1 = file1.read()
content2 = file2.read()
output_file.write(content1 + content2)
print("Files merged successfully.")
check=open(output_file_path,"r")
print(check.read())
check.close()
except IOError as e:
print(f"An error occurred: {e}")

# Example usage:
file1_path = 'D:\\file1.txt'
file2_path = 'D:\\file2.txt'
output_file_path = 'D:\\merged_file.txt'
merge_files(file1_path, file2_path, output_file_path)

OUTPUT:

2. Write a Python code to open a given file and construct a function to check for given
words present in it and display on found.

CODE:
def check_words_in_file(file_path, words_to_check):
try:
with open(file_path, 'r') as file:
content = file.read()
for word in words_to_check:

47
GURU NANAK INSTITUTE OF TECHNOLOGY
if word in content:
print(f"Found word '{word}' in the file.")
else:
print(f"Word '{word}' not found in the file.")
except IOError as e:
print(f"An error occurred while opening the file: {e}")

# Example usage:
file_path = 'D:\\sample_file.txt'
words_to_check = ['apple', 'banana', 'orange', 'grape']
check_words_in_file(file_path, words_to_check)

OUTPUT:

Found word 'apple' in the file.


Found word 'banana' in the file.
Word 'orange' not found in the file.
Found word 'grape' in the file.

3. Write a Python code to Read text from a text file, find the word with most number of
occurrences.

CODE:
def find_most_common_word(file_path):
try:
with open(file_path, 'r') as file:
content = file.read().lower() # Convert content to lowercase for case-insensitive
comparison
words = content.split() # Split the content into words

# Create a dictionary to store word counts


word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1

# Find the word with the most occurrences


most_common_word = max(word_counts, key=word_counts.get)
occurrences = word_counts[most_common_word]
return most_common_word, occurrences
except FileNotFoundError:

48
GURU NANAK INSTITUTE OF TECHNOLOGY
print("File not found.")
return None, None
except Exception as e:
print(f"An error occurred: {e}")
return None, None

# Example usage:
file_path = 'D:\\sample_file.txt'
most_common_word, occurrences = find_most_common_word(file_path)

if most_common_word and occurrences:


print(f"The word '{most_common_word}' appears {occurrences} times in the file.")
else:
print("No word found or an error occurred.")

OUTPUT:

"C
:\Users\NAG RAJ\PycharmProjects\pythonProject2\venv\Scripts\python.exe"
"C:/Users/NAG RAJ/PycharmProjects/pythonProject2/occurences.py"
The word 'time' appears 3 times in the file.

4. Write a function that reads a file file1 and displays the number of words, number of
vowels, blank spaces, lower case letters and uppercase letters.

CODE:
def analyze_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
# Count the number of words
words = content.split()
num_words = len(words)

# Count the number of vowels


vowels = 'aeiouAEIOU'
num_vowels = sum(1 for char in content if char in vowels)

# Count the number of blank spaces


num_blank_spaces = sum(1 for char in content if char.isspace())

49
GURU NANAK INSTITUTE OF TECHNOLOGY
# Count the number of lowercase and uppercase letters
num_lower_case = sum(1 for char in content if char.islower())
num_upper_case = sum(1 for char in content if char.isupper())
return num_words, num_vowels, num_blank_spaces, num_lower_case, num_upper_case
except FileNotFoundError:
print("File not found.")
return None, None, None, None, None
except Exception as e:
print(f"An error occurred: {e}")
return None, None, None, None, None

# Example usage:
file_path = 'D:\\file1.txt'
num_words, num_vowels, num_blank_spaces, num_lower_case, num_upper_case =
analyze_file(file_path)

if num_words is not None:


print(f"Number of words: {num_words}")
print(f"Number of vowels: {num_vowels}")
print(f"Number of blank spaces: {num_blank_spaces}")
print(f"Number of lowercase letters: {num_lower_case}")
print(f"Number of uppercase letters: {num_upper_case}")
else:
print("An error occurred or the file was not found.")

OUTPUT:

Number of words: 3
Number of vowels: 6
Number of blank spaces: 2
Number of lowercase letters: 16
Number of uppercase letters: 1

50
GURU NANAK INSTITUTE OF TECHNOLOGY

1. Import numpy, Plotpy and Scipy and explore their functionalities

CODE:
import numpy as np
import matplotlib.pyplot as plt
import scipy

# Numpy
arr = np.array([1, 2, 3, 4, 5])
mean = np.mean(arr)
std_dev = np.std(arr)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_transpose = np.transpose(matrix)
values = np.linspace(0, 10, 100)
squared_values = np.square(values)

# Matplotlib
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Function")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

x_scatter = np.random.rand(50)
y_scatter = np.random.rand(50)
plt.scatter(x_scatter, y_scatter)
plt.title("Scatter Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

# Scipy
from scipy.optimize import minimize

def quadratic(x):
return x**2 + 3*x + 2

result = minimize(quadratic, x0=0)


min_x = result.x

51
GURU NANAK INSTITUTE OF TECHNOLOGY
from scipy.interpolate import interp1d
x_interp = np.linspace(0, 10, num=11, endpoint=True)
y_interp = np.cos(-x_interp**2/9.0)
f = interp1d(x_interp, y_interp, kind='cubic')

new_x_interp = np.linspace(0, 10, num=41, endpoint=True)


new_y_interp = f(new_x_interp)

2. a) Install NumPy package with pip and explore it.


To install the NumPy package using pip, you can use the following command in your
terminal or command prompt:

pip install numpy

CODE:
import numpy as np

# Create a 1D array
arr1d = np.array([1, 2, 3, 4, 5])

# Create a 2D array (matrix)


matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Basic array operations


mean = np.mean(arr1d)
std_dev = np.std(arr1d)

# Array manipulation
arr2d_transposed = np.transpose(matrix)

# Generating sequences
values = np.linspace(0, 10, 100) # Generates 100 values between 0 and 10

# Element-wise operations
squared_values = np.square(values)

# Indexing and slicing


subset = arr1d[1:4] # Get elements from index 1 to 3

# Mathematical operations
result = np.sin(arr1d)

print("1D Array:", arr1d)


print("2D Array:", matrix)
print("Mean:", mean)
52
GURU NANAK INSTITUTE OF TECHNOLOGY
print("Standard Deviation:", std_dev)
print("Transposed Matrix:", arr2d_transposed)
print("Generated Values:", values)
print("Squared Values:", squared_values)
print("Subset:", subset)
print("Sin Result:", result)

3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR

CODE:
# Implementing Digital Logic Gates in Python

# AND gate function


def AND(a, b):
return a and b

# OR gate function
def OR(a, b):
return a or b

# NOT gate function


def NOT(a):
return not a

# XOR gate function


def XOR(a, b):
return (a and not b) or (not a and b)

# Test the logic gates


input1 = True
input2 = False

and_result = AND(input1, input2)


or_result = OR(input1, input2)
not_result = NOT(input1)
xor_result = XOR(input1, input2)

# Display results
print("AND Gate:", and_result)
print("OR Gate:", or_result)
print("NOT Gate:", not_result)
print("XOR Gate:", xor_result)

4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
53
GURU NANAK INSTITUTE OF TECHNOLOGY

CODE:

5. Write a GUI program to create a window wizard having two text labels, two text fields
and two buttons as Submit and Reset.

CODE:
import tkinter as tk
from tkinter import messagebox

# Function to handle the Submit button click


def submit_click():
name = name_entry.get()
age = age_entry.get()
messagebox.showinfo("Submission", f"Name: {name}\nAge: {age}")

# Function to handle the Reset button click


def reset_click():
name_entry.delete(0, tk.END)
age_entry.delete(0, tk.END)

# Create the main window


root = tk.Tk()
root.title("Window Wizard")

# Labels
name_label = tk.Label(root, text="Name:")
age_label = tk.Label(root, text="Age:")

# Entry fields
name_entry = tk.Entry(root)
age_entry = tk.Entry(root)

# Buttons
submit_button = tk.Button(root, text="Submit", command=submit_click)
reset_button = tk.Button(root, text="Reset", command=reset_click)

# Organize widgets using grid layout


name_label.grid(row=0, column=0, padx=10, pady=10)
name_entry.grid(row=0, column=1, padx=10, pady=10)
age_label.grid(row=1, column=0, padx=10, pady=10)
age_entry.grid(row=1, column=1, padx=10, pady=10)
submit_button.grid(row=2, column=0, columnspan=2, padx=10, pady=10)
reset_button.grid(row=3, column=0, columnspan=2, padx=10, pady=10)

54
GURU NANAK INSTITUTE OF TECHNOLOGY
# Start the GUI event loop
root.mainloop()

OUTPUT:

List of Additional Experiments


Write a python program to print the messages
SOURCE CODE:

55
GURU NANAK INSTITUTE OF TECHNOLOGY
print("Ideas won't work unless we do...")
print('Ideas will not work unless we do...')
print('''Ideas won't work
unless we do....''')

Output:
Ideas won't work unless we do...
Ideas will not work unless we do...
Ideas won't work
unless we do....

Write a python program to print the messages


SOURCE CODE:
print("HelloWorld")
print("Hello"+"World")
print("Hello"+" World")
print(" Hello "+"World")
print(" Hello"+"World")

Output:
HelloWorld
HelloWorld
Hello World
Hello World
HelloWorld

Write a python program to print the message using separator


SOURCE CODE:
print("Ideas ","Won't","work","unless","we do...", sep=" ")

56
GURU NANAK INSTITUTE OF TECHNOLOGY
Output:
Ideas Won't work unless we do...

print("Ideas ","Won't","work","unless","we do...", sep=", ")


Output:
Ideas , Won't, work, unless, we do...

print("Ideas ","Won't","work","unless","we do...", sep="$ ")


Output:
Ideas $ Won't$ work$ unless$ we do...

print("Ideas ","Won't","work","unless","we do...", sep="\n")


Output:
Ideas
Won't
work
unless
we do...

Write a python program to print the type of variable


SOURCE CODE:
i=2
f=12.2
c="Workhard"
print("Type of variable i=",type(i))
print("Type of variable i=",type(f))
print("Type of variable i=",type(c))

Output:
Type of variable i= <class 'int'>
Type of variable i= <class 'float'>
Type of variable i= <class 'str'>

57
GURU NANAK INSTITUTE OF TECHNOLOGY
Write a python program to convert temperature in Celsius to Fahrenheit
SOURCE CODE:
# 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:
37.5 degree Celsius is equal to 99.5 degree Fahrenheit

Implement math functions in python


SOURCE CODE:
import math
import math as m
print(m.sqrt(25))
x=math.sqrt(25)
print(x)
a=5.6
print(math.floor(a))
print(math.floor(12.4))
print(math.ceil(a))
print(math.ceil(3.4))
print(math.pow(5,3))
print(math.pi)
print(math.e )
print(m.factorial(5))
print(m.factorial(6))
print(m.factorial(0))
print(m.factorial(1))
print(m.fabs(-45.89))
print(m.fabs(-98))
print(m.sin(m.radians(30)))
print(m.cos(m.radians(60)))
print(m.tan(m.radians(45)))
print(m.log(1))
print(m.log(4))

Output:
5.0
5.0
5
12
6
4
125.0

58
GURU NANAK INSTITUTE OF TECHNOLOGY
3.141592653589793
2.718281828459045
120
720
1
1
45.89
98.0
0.49999999999999994
0.5000000000000001
0.9999999999999999
0.0
1.3862943611198906

Write a python program to print date, time for today and now.
SOURCE CODE:
import datetime
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)

Output:
2023-11-19 18:23:34.039234
2023-11-19 18:23:34.039234

Write a program that accepts the lengths of three sides of a triangle as input the program output
should indicate whether or not the triangle ,is 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)
SOURCE CODE:
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")
else:
print("Scalene triangle")

Output:
Input lengths of the triangle sides:
x: 6

59
GURU NANAK INSTITUTE OF TECHNOLOGY
y: 8
z: 12
Scalene triangle

Write a program to perform different arithmetic operations on numbers in python


SOURCE CODE:
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:
Enter First number: 10
Enter Second number 5
Sum of 10 and 5 is : 15
Difference of 10 and 5 is : 5
Product of 10 and 5 is : 50
Division of 10 and 5 is : 2.0
Floor Division of 10 and 5 is : 2
Exponent of 10 and 5 is : 100000
Modulus of 10 and 5 is : 0

Write a python program to print a number is even using simple if statement


SOURCE CODE:
n=int(input("Enter a number:"))
if(n%2==0):
print("n is even")

Output:
Enter a number:10
n is even
Enter a number:7

Write a python program to print a number is even using simple if –else statement

60
GURU NANAK INSTITUTE OF TECHNOLOGY
SOURCE CODE:
n=int(input("Enter a number:"))
if(n%2==0):
print("n is even")
else:
print("n is odd")

Output:
Enter a number:10
n is even
Enter a number:7
n is odd

Write a python program to find the greater number between two numbers.
SOURCE CODE:
A=int(input("enter A:"))
B=int(input("enter B:"))
if(A>B):
print("A is greater")
else:
rint("B is greater")

Output:
enter A:3
enter B:6
B is greater

Write a python program to print the factorial of a number using if-elif-else ladder
SOURCE CODE:
n=int(input("Enter a number:"))
factorial=1
i=1
if(n<0):
print("Sorry factorial numbers doesn't exist for negative numbers")
elif(n==0):
print("Factorial of 0 is 0")
else:
for i in range(1,n+1):
factorial = factorial * i
print("Factorial of", n, "is", factorial)

Output:
1)Enter a number:5
Factorial of 5 is 120

61
GURU NANAK INSTITUTE OF TECHNOLOGY
2) Enter a number:0
Factorial of 0 is 0
3) Enter a number:-2
Sorry factorial numbers doesn't exist for negative numbers

Write a python program to print the sum of digits of a number using while loop
SOURCE CODE:
n=int(input("enter a number"))
sum=0
while(n>0):
r = n % 10
sum = sum + r
n = n // 10
print("sod",sum)

Input& Output:
Enter a number:2356
sod= 16

Write a python program to print the reverse of a number using while loop
SOURCE CODE:
n=int(input("Enter a number:"))
rev=0
while(n>0):
r = n % 10
rev = rev*10 + r
n = n // 10
print("Reverse of number=",rev)
Input& Output:
Enter a number:234
Reverse of number= 432

Write a python program to print the palindrome of a number using while loop
SOURCE CODE:
n=int(input("Enter a number:"))
rev=0
temp=n
while(n>0):
r = n % 10
rev = rev*10 + r
n = n // 10
if (temp==rev):
print(rev,"is a palindrome")
else:
print(rev, "is not a palindrome")

62
GURU NANAK INSTITUTE OF TECHNOLOGY
Input& Output:
1) Enter a number:121

121 is a palindrome
2) Enter a number:234
432 is not a palindrome

Write a python program to print armstrong of a number using while loop


SOURCE CODE:
n=int(input("Enter a number:"))
sum=0
temp=n
while(n>0):
r = n % 10
sum = sum+r**3
n = n // 10
if (temp==sum):
print(temp,"is an Armstrong Number")
else:
print(temp,"is an Armstrong Number")

Input& Output:
1) Enter a number:125
125 is an Armstrong Number
2) Enter a number:153
153 is an Armstrong Number

Write a python program to print whether the given number is prime or not using for loop
SOURCE CODE1:
n=int(input("Enter a number:"))
for i in range(2,n):
if(n%i==0):
print(n,"is not a prime number")
break
else:
print(n, "is a prime number")

Input& Output:
1)Enter a number:6
6 is not a prime number
2) Enter a number:11
11 is a prime number

SOURCE CODE2:
n=int(input("Enter a number:"))
count=0

63
GURU NANAK INSTITUTE OF TECHNOLOGY
for i in range(1,n+1):
if(n%i==0):
count+=1
if(count>2):
print(n, "is not a prime number")
break
else:
print(n, "is a prime number")

Input& Output:
1)Enter a number:6
6 is not a prime number
2)Enter a number:7
7 is a prime number

Write a python script that prints prime numbers less than n


# Python program to display all the prime numbers up to n
# Setting the intial value with 1
Starting_value = 1
# Taking input from the user
n = int(input("Enter the number: "))
print("Prime numbers between", Starting_value, "and", n, "are:")
fornum in range(Starting_value, n + 1):
if (num> 1):
for i in range(2, int(num / 2) + 1):
if (num % i) == 0:
break
else:
print(num)

Output:
Enter the number: 20
Prime numbers between 1 and 20 are:
2
3
5
7
11
13
17
19

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

64
GURU NANAK INSTITUTE OF TECHNOLOGY
# 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:
Hello
Hello
Hello
Hello, welcome to
the world of Python

print string:
#concatenate
str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)

str = 'NagarajU'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

Output:
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
str = NagarajU
str[0] = N
str[-1] = U

65
GURU NANAK INSTITUTE OF TECHNOLOGY

Implement slicing operations on a string


s="PYTHON PROGRAMMING"
print(s[::-1])
print(s[::1])
print(s[::-2])
print(s[::-5])
print(s[2:3])
print(s[2:3:-1])
print(s[-15:-16])
print(s[-15:-16:-1])
print(s[-6:7:-2])
print(s[4:-8])
print(s[9:-10])
print(s[9:-10:-1])
print(s[22::-6])
print(s[2:-22:-1])
print(s[15::-2])
print(s[-15::-2])
print(s[7:-1])

Output:
GNIMMARGORP NOHTYP
PYTHON PROGRAMMING
GIMROPNHY
GAPT
T
H
AGR
ON PRO

66
GURU NANAK INSTITUTE OF TECHNOLOGY
O
GRN
TYP
IMROPNHY
HY
PROGRAMMIN

Create a list and perform the following methods


insert() 2) remove() 3) append() 4) len() 5) pop() 6) clear()

SOURCE CODE:
a=[1,3,5,6,7,[3,4,5],"hello"]
print(a)

a.insert(3,20)
print(a)

a.remove(7)
print(a)

a.append("hi")
print(a)

len(a)
print(a)

a.pop()
print(a)

a.pop(6)
print(a)

a.clear()
print(a)

Output:

67
GURU NANAK INSTITUTE OF TECHNOLOGY
[1, 3, 5, 6, 7, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, 7, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello', 'hi']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello', 'hi']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5]]
[]

68

You might also like