0% found this document useful (0 votes)
69 views99 pages

Python Programming Lab Manual for B.Tech

The document is a laboratory manual for a Programming for Problem Solving Lab using Python, aimed at B.Tech. students in their first year. It outlines the course structure, including course outcomes, a list of experiments, and evaluation criteria. The manual emphasizes practical programming skills in Python, covering basic concepts, data types, control statements, and GUI development.

Uploaded by

Sukhjeet Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views99 pages

Python Programming Lab Manual for B.Tech

The document is a laboratory manual for a Programming for Problem Solving Lab using Python, aimed at B.Tech. students in their first year. It outlines the course structure, including course outcomes, a list of experiments, and evaluation criteria. The manual emphasizes practical programming skills in Python, covering basic concepts, data types, control statements, and GUI development.

Uploaded by

Sukhjeet Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Department of Applied Sciences

LABORATORY MANUAL

Programming for problem solving lab using Python


(25C1CSU-112)

st st nd
[Link]. 1 Year – I / II Semester
Common to all Branches

Chandigarh Engineering College-CGC, Landran, Mohali


Course title Programming for Problem Solving Lab using Python
Course Code: 25C1CSU-112
Scheme and Credits L T P C Semester – I/II
0021
Pre-requisite (if any)
Internal Marks 30
External Marks 20
Total Marks 50

Course Outcomes:
At the end of this course, students will be able to
CO1 solve basic engineering problems using Python programs

CO2 demonstrate the basic data types and operators in Python.

CO3 apply the use of selection control statements, iteration control statements and loop
control statements in Python.
CO4 Analyse user defined functions, modules, and packages for solving basic
engineering problems.
CO5 build python programs for file handling, exception handling
methods. and creating GUI in Python.

List of Experiments:
Note: Students are expected to perform at least 10 experiments from the following list.

[Link]. Name of the Experiment


1 a) Install and configure Python IDE.
b) Write a Python program to display messages on screen.
c) Write a Python program to input a string from a user and display it on the screen.
2 a) Write a program to check whether entered frequency is radio frequency or audio
frequency.
b) Write a program to display various radio frequency bands using if..else if ladder.
c) Write a program to display resistor color code using a switch statement.
3 a. Write a simple Python program to demonstrate use of control loops:
i) while
ii) do while
b. Create a simple program, to demonstrate use of: for loop in Python (e.g.: various pattern
building, printing multiplication table, checking palindrome number etc.)

4 Write Python program to perform following operations on List:


a) Create b) Access c) Update d) Delete elements from list.

5. Develop Python program to perform following operations on Tuples:


a) Create b) Access c) Update d) Delete Tuple elements

6. Write Python program to perform following operations on Set:


a) Create b) Access c) Update d) Delete Access Set elements

7 Create a program to perform following operations on Dictionaries in Python:


a) Create b) Access c) Update d) Delete e) Looping through Dictionary

8 a) Create a python program to demonstrate use of math built-in function.


b) Create a python program to demonstrate the use of string built-in function.

9 Write a program to define a function with default arguments.

10 Write Python Program to Count the Number of words and lines in a Text File.
Write Python Program to Read a String from the User and Append it into a File.

11 Create an array using NumPy.


Find the dimension of the array using NumPy inbuilt methods.

12 Write Python program to create Widgets using Tkinter.


COURSE OUTCOMES

Programming for Problem Solving u s i n g P y t h o n Lab ( 25C1CSU-112)

CO1 solve basic engineering problems using Python programs.

CO2 demonstrate the basic data types and operators in Python.

CO3 apply the use of selection control statements, iteration control statements and loop control
statements in Python.
CO4 analyse user defined functions, modules, and packages for solving basic engineering problems.
CO5
build python programs for file handling, exception handling
methods. and creating GUI in Python.

CO PO MAPPING

Programming for Problem Solving using Python Lab (25C1CSU-112)

Course Code PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO 1 3 3 2 - 2 - - - 1 - - 2

CO 2 3 2 1 - 2 - - - 1 - - 2

CO 3 3 3 2 - 2 - - - 1 - - 1

CO 4 3 3 3 - 3 - - - 1 - - 2

CO 5 3 3 3 - 3 - - - 1 1 - 2

3 2.8 2.2 2.4 1 1 1.8


Internal Marks : 30
External Marks : 20 L T P
Total Marks : 50 0 0 2

Programming for problem solving using Python lab


(25C1CSU-112)
Page Relevance
[Link] Content
no. to COs
a) Install and configure Python IDE. 1-5
b) Write a Python program to display messages on screen. 6-6
1 c) Write a Python program to input a string from a user and display it on 7-8 CO1, CO2
the screen.
a) Write a program to check whether entered frequency is radio 9-10
frequency or audio frequency.
b) Write a program to display various radio frequency bands using if..else 11-12
2 CO1,CO3
if ladder.
c) Write a program to display resistor color code using a switch 13-15
statement.
a. Write a simple Python program to demonstrate use of control loops:
i) while 16-20
ii) do while
b. Create a simple program, to demonstrate use of: for loop in Python
3 CO1,CO2, CO3
(e.g.: various pattern building, printing multiplication table, checking
palindrome number etc.) 21-25

Write Python program to perform following operations on List:


Create b) Access c) Update d) Delete elements from list.
4 26-33 CO1,CO2

Develop Python program to perform following operations on Tuples:


5. Create b) Access c) Update d) Delete Tuple elements CO1,CO2
34-41
Write Python program to perform following operations on Set:
6. a) Create b) Access c) Update d) Delete Access Set elements
42-52 CO1,CO2

Create a program to perform following operations on Dictionaries in


Python:
7 a) Create b) Access c) Update d) Delete e) Looping through 53-63 CO1,CO2,CO3,
Dictionary
a) Create a python program to demonstrate use of math built-in function.
b) Create a python program to demonstrate the use of string built-in
8 function. 64-69 CO1,CO4

Write a program to define a function with default arguments.


9 70-71 CO1,CO2,CO4

a)Write Python Program to Count the Number of words and lines in a


Text File.
CO1,CO2,
10 b) Write Python Program to Read a String from the User and Append it 72-75
CO5
into a File.

Create an array using NumPy.


11 Find the dimension of the array using NumPy inbuilt methods. 76-77 CO2,CO4

12 Write Python program to create Widgets using Tkinter.


78-80 CO4, CO5

PREPARED BY APPROVED BY
LAB INCHARGE HOD (APPLIED SCIENCES)
Programming for problem solving using Python lab
(25C1CSU-112)

Practical beyond Syllabus


13 Write a Python program to compute square root of a number. 81-82 CO2

Write a program to print largest of three numbers using if else


14 statement. 83-84 CO3

Write a program to sort list of n numbers.


15 85-86 CO1,CO2
Write a program to design simple calculator.
16 87-88 CO4
Write a program to create file which stores the following information:
17 Name, Roll No, Name of 5 Subjects and Marks of 5 subjects. 89-90 CO5

PREPARED BY APPROVED BY
LAB INCHARGE HOD (APPLIED SCIENCES)
Experiment No.1

a) Install and configure Python IDE.

Aim: To install and configure a Python Integrated Development Environment (IDE) for writing,
executing, and debugging Python programs efficiently.

What is a Python IDE?


A Python IDE (Integrated Development Environment) is a software application that provides
tools to make writing Python code easier and more efficient.

Tools Used

 PyCharm (Community Edition)


 Visual Studio Code (VS Code)
 Python (latest version from [Link])

Key Features of a Python IDE:

 Code editor with syntax highlighting


 Code completion and suggestions
 Debugging tools
 Integrated terminal or console

IDE Description Suitable For

IDLE Default IDE that comes with Python Beginners


VS Code Lightweight, powerful editor with extensions All levels
PyCharm Full-featured IDE for Python development Intermediate to Advanced
Thonny Simple and beginner-friendly Students and beginners
Jupyter Notebook Ideal for data science and visualization Data analysts, researchers

Steps to Install Visual Studio Code on Windows

1
Step 1: Visit the Official Website of the Visual Studio Code using any web browser like Google
Chrome, Microsoft Edge, etc.

Step-1

Step-2

Press the "Download for Windows" button on the website to start the download of the Visual Studio
Code Application.

2
Step-3

When the download finishes, then the Visual Studio Code Icon appears in the downloads folder.

Step 4
Click on the Installer icon to start the installation process of the Visual Studio Code.

Step 5: After the Installer opens, it will ask you to accept the terms and conditions of the Visual Studio
Code. Click on I accept the agreement and then click the Next button.

A. Install Visual Studio Code (VS Code)


Open VS Code → Go to Extensions (Ctrl + Shift + X) → Search and install Python.

3
Step-6 Choose the location data for running the Visual Studio Code. It will then ask you to browse
the location. Then click on the Next button.

Step-7
Then it will ask to begin the installation setup. Click on the Install button.

Step 8

After clicking on Install, it will take about 1 minute to install the Visual Studio Code on your device.

4
Step 9

Step- 10
After the Installation setup for Visual Studio Code is finished, it will show a window like this below. Tick
the "Launch Visual Studio Code" checkbox and then click Next.

Step 11
After the previous step, the Visual Studio Code window opens successfully. Now you can create a new
file in the Visual Studio Code window.

Run the program using the Run button or terminal.

5
Experiment No.1

b) Write a Python program to display messages on screen.


Aim: To learn and understand how to display messages using the print() function in Python.

Pre-requisite: Knowledge of python programming concepts and familiarity with running Python code in an
IDE or command-line

Theory: In Python, displaying a message or output to the screen is typically done using the built-in print()
function. This function sends the specified message to the console or terminal. The message can be a string
(text), numbers, variables, or a combination of these.

Syntax:
print("message")

Algorithm:
Step-1 Start: Begin the program execution.

Step-2 Print String: Use the print() function to display the string "Hello, World!" to the standard output
(usually the console).
Step-3 End: Terminate the program execution.

Flow Chart

Fig 1.1 Flowchart of Python program to display messages on screen.

Result: The Python program to display messages on screen verified and successfully executed.

6
Experiment No. 1
c) Write a Python program to input a string from a user and display it on the screen.

Aim: To learn how to take string input from a user and display it using Python's built-in functions.

Pre-requisite: Basic understanding of Python syntax. Familiarity with input and output operations.

Knowledge of using the input () and print() functions in Python.

Theory: In Python, the input() function is used to take input from the user. By default, it reads the input as a

string. The print() function is used to display output on the screen.

Syntax:

 Taking input from the user

variable_name = input("Prompt message")

 Displaying output

print("Message", variable_name)

Algorithm:

Step 1: Start the program

Step 2: Prompt the user to enter a string using input()

Step 3: Store the input in a variable

Step 4: Use print() to display the stored string

Step 5: End the program

7
Flowchart:

Fig.1.2 Flowchart of program to input a string from a user and display it on the screen.

Result: Python program to input a string from a user and display it on the screen verified and
successfully executed.

Experiment No .2

8
a) Write a program to check whether entered frequency is radio frequency or audio frequency.

Aim: To develop a Python program that determines whether a user-entered frequency falls under Audio

Frequency, Radio Frequency, or Neither.

Pre-requisite: Knowledge of basics Python programming with understanding of conditional (if, elif, else)

statements required. Familiarity with frequency ranges required as follows:

 Audio Frequency: 20 Hz to 20,000 Hz

 Radio Frequency: 30,000 Hz to 300 GHz

Theory: Frequency refers to the number of oscillations (or cycles) per second of a wave and is measured in

Hertz (Hz).Types of frequency are Audio Frequency (AF) and Radio Frequency (RF). Audio frequency

ranges from 20 Hz to 20,000 Hz. These are frequencies audible to the human ear. Radio Frequency (RF):

ranges from 30,000 Hz (30 kHz) to 300 GHz. These are used in communication technologies like radio, TV,

mobile networks, etc. The program compares the entered frequency value against these ranges to determine

its category.

Algorithm:

Step-1 Start
Step-2 Input the frequency from the user (in Hz)
Step-3 If frequency is between 20 and 20,000
Display "Audio Frequency"
Step-4 Else
if frequency is between 30,000 and 300,000,000,000.
Display "Radio Frequency"
Step-5 Else:
Display "Neither Audio nor Radio Frequency"

Step-6 End

9
Flowchart:

Fig. 2.1 Program to check whether entered frequency is radio frequency or audio frequency.

Output: Python program that checks whether an entered frequency is in the audio or radio frequency
range, and prints the appropriate output is verified and successfully executed.

Experiment No.2

10
b) Write a program to display various radio frequency bands using if..else if ladder.

Aim: To write a Python program that displays the name of the radio frequency band based on the input

frequency (in Hz), using an if...elif...else ladder.

Pre-requisite: To understand the Python syntax for input (), if, elif, and else statements as well familiarity

with common radio frequency bands.

Common RF Bands (with frequencies):

Band Frequency Range (in Hz)

Very Low Frequency (VLF) 3 kHz – 30 kHz

Low Frequency (LF) 30 kHz – 300 kHz

Medium Frequency (MF) 300 kHz – 3 MHz

High Frequency (HF) 3 MHz – 30 MHz

Very High Frequency (VHF) 30 MHz – 300 MHz

Ultra High Frequency (UHF) 300 MHz – 3 GHz

Super High Frequency (SHF) 3 GHz – 30 GHz

Extremely High Frequency (EHF) 30 GHz – 300 GHz

Algorithm:

Step-1 Start
Step-2 Prompt the user to enter a frequency in Hz
Step-3 Read the input frequency
Step- 4Use if...elif...else ladder to match the frequency to its band:
Check if it falls in each range
Step-5 Display the corresponding RF band name
Step- 6 If it does not fall in any range, print “Not a radio frequency”
Step-7 End

Flowchart:

11
Fig.2.2 Program to display various radio frequency bands using if..else if ladder.

Result: program to display various radio frequency bands using if..else if ladder is verified and successfully
executed.

Experiment No.2

12
c) Write a program to display resistor color code using a switch statement.
Aim: To write a Python program to display the resistor color code using the match-case (switch-like)
statement.
Prerequisite: To successfully implement this program, one must understand the basic syntax and structure
of Python programming. It is essential to know how to use input and output functions like input() and print()
for user interaction. Familiarity with control flow mechanisms in Python, especially the match-case
statement introduced in Python 3.10, is necessary as it serves as an alternative to the traditional switch-case
structure found in other programming languages. Additionally, one should be able to interpret the resistor
color coding system, which is widely used in electronics to represent resistance values, multipliers, and
tolerance levels.
Theory: Resistors are fundamental electronic components used to limit current flow in circuits. Each
resistor has a set of colored bands printed on its body, known as the resistor color code, which denotes its
resistance value, multiplier, and tolerance. These bands use standardized color representations for the digits
0–9, multipliers (powers of ten), and tolerance percentages. For example, red represents the digit 2, a
multiplier of 100, and a tolerance of ±2%. In programming, such color-to-value mapping can be effectively
handled using control structures. While traditional programming languages use a switch statement for such
tasks, Python uses a modern match-case construct introduced in version 3.10. This structure allows
programmers to match specific values (like color names) and execute corresponding actions, making the
code more readable and structured. Implementing resistor color code logic using match-case in Python
provides both a practical understanding of color coding in electronics and the application of advanced
control flow in Python programming.
Syntax:
match variable:
case "value1":
# statements
case "value2":
# statements
case _:
# default case
Example:
# Function to display color code information
def display_resistor_color_code(color):
color = [Link]() # Convert to lowercase for consistency

match color:
case "black":
print("Digit: 0, Multiplier: 1Ω")
case "brown":
print("Digit: 1, Multiplier: 10Ω, Tolerance: ±1%")
case "red":
print("Digit: 2, Multiplier: 100Ω, Tolerance: ±2%")
case "orange":
print("Digit: 3, Multiplier: 1kΩ")
case "yellow":

13
print("Digit: 4, Multiplier: 10kΩ")
case "green":
print("Digit: 5, Multiplier: 100kΩ, Tolerance: ±0.5%")
case "blue":
print("Digit: 6, Multiplier: 1MΩ, Tolerance: ±0.25%")
case "violet":
print("Digit: 7, Multiplier: 10MΩ, Tolerance: ±0.1%")
case "grey":
print("Digit: 8, Multiplier: 100MΩ, Tolerance: ±0.05%")
case "white":
print("Digit: 9, Multiplier: 1GΩ")
case "gold":
print("Multiplier: 0.1Ω, Tolerance: ±5%")
case "silver":
print("Multiplier: 0.01Ω, Tolerance: ±10%")
case _:
print("Invalid color")
# Input from user

color_input = input("Enter the resistor color: ")


display_resistor_color_code(color_input)
Algorithm:

Step 1: Start

Step 2: Prompt the user to enter the color name of the resistor band.

Step 3: Convert the input color to lowercase to ensure uniform comparison.

Step 4: Use a match-case statement to compare the color with predefined resistor color codes:

If the color matches a known case (e.g., black, brown, red, etc.), display the corresponding
digit, multiplier, and tolerance.

If the color does not match any defined case, display "Invalid color".

Step 5: End

Flowchart:

14
Fig 2.3: Program to display resistor color code using a switch statement
Result: Program to display resistor color code using a switch statement has verified and successfully
executed.

Experiment No.3

15
a. Write a simple Python program to demonstrate use of control loops:

i) while

ii) do while

1) To using while loop

i) Aim: To write a Python program to find the factorial of a number using a while loop.

Pre Requisite: Knowledge of while loop for repeated multiplication with loop control statement using a

counter variable (i) is required.

Theory: The factorial of a non-negative integer n is the product of all positive integers less than or equal to

[Link] is denoted by n! and defined as:n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n - 1) \times (n - 2) \times \cdots \

times 1n!=n×(n−1)×(n−2)×⋯×[Link] in mathematics and computer science problems.

Syntax:

for loop syntax:


for variable in range(start, stop):

# code block

1. range(start, stop) generates numbers from start to stop - 1.

2. Loop continues until variable reaches stop - 1.

while loop syntax:

while condition:

# code block

1. The loop runs as long as the condition is true.

2. The loop must update the control variable to avoid infinite loops.

16
Algorithm:

Step-1 Start

Step-2 Initialize fact = 1, i = 1

Step-3 Input a number num from the user

Step-4 If num < 0, display “Factorial does not exist for negative numbers”

Step-5 Else,

Repeat while i <= num:

Multiply fact = fact * i

Increment i = i + 1
Step-6 Display fact
Step-7 End

17
Flowchart:

Fig 3.1: Python program to find the factorial of a number using a while loop

Output: a Python program to find the factorial of a number using a while loop has executed and verified.

18
Experiment No.3
ii) To write a Python program to find the factorial of a number using a do while loop.

Aim: To write a Python program to find the factorial of a number using a do while loop.
Perquisite: The knowledge of Control Flow Loops and Conditional Statements is required.

Theory: The factorial of a non-negative integer n, written as n!, is the product of all positive integers less

than or equal to n. Mathematically, n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n - 1) \times (n - 2) \times \cdots \

times 1n!=n×(n−1)×(n−2)×⋯×1

Syntax :
while True:
# loop body (runs at least once)

if condition_to_stop:
break

Algorithm:

Step-1 Start
Step-2 Initialize fact = 1 and i = 1
Step-3 Input a number num from the user
Step-4 Check if num < 0
→ If true, display:
"Factorial does not exist for negative numbers"
→ Go to step 9
Step-5 Otherwise, proceed to step 6
Step-6 Begin loop (simulate do while using while True):
Multiply fact = fact * i
Increment i = i + 1
If i > num, break the loop
Step-7 End loop
Step-8 Display: "The factorial of num is fact"
Step-9 End

19
Flowchart:

Fig: 3.2 Python program to find the factorial of a number using a do while loop.

Output: Python program to find the factorial of a number using a do while loop has executed and verified.

20
Experiment No.3

b) Create a simple program, to demonstrate use of: for loop in Python (e.g.: various pattern

building, printing multiplication table, checking palindrome number etc.)

Aim: To create a simple Python program demonstrating the use of the for loop by printing a multiplication

table and checking for a palindrome number.

Prerequisite: To understand basic Python syntax, use of the for loop, simple string operations, and taking

user input/output.

Theory: To use the for loop in Python for iterating over a sequence, and apply it in tasks like

generating multiplication tables or checking if a number is a palindrome by reversing strings.

Syntax:

 For Pattern building :

for variable in range(start, stop):

# code to execute

 Palindrome Check Using for Loop

num = input("Enter a number: ") # Input number as string

original = num # Save original number

reversed_num = "" # Initialize empty string

for char in reversed(original): # Loop through reversed string

reversed_num += char # Append each character

if original == reversed_num: # Compare original and reversed

21
print("Palindrome")

else:

print("Not a palindrome")

 Multiplication Table Using for Loop

for i in range(1, 11):

result = num * i

print(f"{num} x {i} = {result}")

Algorithm:
1 Pattern Building (Right-Angled Triangle)

Step 1: Start

Step 2: Set the number of rows (e.g., rows = 5)

Step 3: Use a for loop from i = 1 to rows

Step 4: Print i asterisks (*) in a single line

Step 5: Repeat until loop ends

Step 6: End

2 Multiplication Table

Step 1: Start

Step 2: Input a number from the user and store it in num

Step 3: Use a for loop from i = 1 to 10

22
Step 4: Multiply num by i

Step 5: Print the result in the format: num x i = result

Step 6: Repeat until loop ends

Step 7: End

3 3. Palindrome Check

Step 1: Start

Step 2: Input a number and store it in num

Step 3: Convert num to a string and store as original

Step 4: Initialize reversed_num as an empty string

Step 5: Use a for loop to iterate through original in reverse order

Step 6: Append each character to reversed_num

Step 7: After loop ends, compare original and reversed_num

Step 8: If they are equal, print "Palindrome"

Step 9: Else, print "Not a palindrome"

Step 10: End

23
Flowchart:
a) For Pattern Building:

b) For Multiplication

24
c) For palindrome number

Fig 3.2 Create a simple program, to demonstrate use of: for loop in Python (e.g.: various pattern
building, printing multiplication table, checking palindrome number etc.)

Result: Create a simple program, to demonstrate use of: for loop in Python (e.g.: various pattern
building, printing multiplication table, checking palindrome number etc.) has verified and successfully
executed.

25
Experiment No: 4
Write Python program to perform following operations on List:

a) Create b) Access c) Update d) Delete elements from list.

a) Aim : Write a Python program to perform Create operations on List.

Prerequisite: The knowledge of basic python syntax is needed. To create a list is as simple as putting

different comma-separated values between square brackets.

Example: >>>List1=[‘Java’, ’Python’, ’Perl’] >>>List2=[10,20,30,40,50]

Theory: A list is a built-in data structure in Python that allows us to store an ordered collection of items.

Lists are mutable, meaning you can change their contents — add, update, or delete elements, after creation.

Python lists are defined using square brackets [], and elements are separated by commas.

Syntax :

Eaxmple:

Algorithm:

Step -1 Start

Step-2 Initialize an empty list or a list with predefined elements

Example:

Empty list: List = []

Predefined list: List = ['Java', 'Python', 'Perl']

Step-3 (Optional) Add elements to the list using:

append () to add at the end: List. Append ('C++')

insert() to add at a specific position: List. Insert(1, 'Ruby')

Step-4 Display the list using print(List)

Step-5 End

26
Flowchart:

Fig 4.1 Python program to perform create operations on List

Output: Python program to perform create operations on List is successfully executed.

27
Experiment No: 4
b) Aim: Write Python program to perform Access Operation on list.

Prerequisite: To understand and perform list access operations, we should have knowledge of basic python

syntax, list creation process, creation of indexing in lists and to display accessed elements.

Theory : A list in Python is an ordered, indexed, and mutable collection of items. Each element in a list can

be accessed using its index, where indexing starts at 0.

Syntax to access elements:

my_list[index]

Python also supports negative indexing:

Example: -1 accesses the last element and-2 accesses the second-last, and so on.

Let consider : List2 [10,20,30,40,50]

List2[1] 20

List2[1:3] [20,30]

List2[5]

Index Error: list index out of range

Algorithm:

Step -1 Start
Step-2 Create a list with some elements (e.g., List = ['Java', 'Python', 'Perl'])
Step-3 Access an element using a positive index (e.g., List[1])
Step-4 Access an element using a negative index (e.g., List[-1])
Step-5 Display the accessed elements
Step-6 End

28
Flowchart:

Fig 4.2 Python program to perform Access Operation on list


Result: Python program to perform Access Operation on list has successfully verified.

29
Experiment No: 4
c) Aim: To write Python program to perform Update operation on list.

Prerequisite: Knowledge domain to assign indexing process, to assigning new value in list and to update

operations in list is mandatory.

Theory: A list in Python is mutable, meaning its elements can be changed or updated after creation. The

update operation is performed by assigning a new value to a specific index in the list.

Syntax:

list_name[index] = new_value

Example:

Algorithm:

Step-1 Start

Styep-2 Create a list with initial values

Example: List = ['Java', 'Python', 'Perl']

STEP-3 Access the element to be updated using its index

Step-4 Update the value using assignment

Example: List[2] = 'C++'

Step-5 Display the updated list

Step-6 END

30
Flowchart:

Fig4.3 Python program to perform Update operation on list.

Result: Python program to perform Update operation on list has verified and executed successfully.

31
Experiment No: 4
d) Aim: To write Python program to perform Delete operation from list.

Prerequisite: To perform delete operations in list ,knowledge of indexing and list creation with deleting

command is necessary.

Theory: Python provides multiple ways to delete elements from a list. There are existing multiple ways to

delete the elements from list:

Use of del Statement: Deletes an element at a specific index:

Syntax:

del list_name[index]

.remove(value) Method: Removes the first occurrence of a specified value:

Syntax:

list_name.remove('value')

.pop(index) Method: Removes and returns the element at the specified index (default is the last element):

Syntax:

ist_name.pop() # Removes last element

list_name.pop(1) # Removes element at index 1

Algorithm:

Step-1 Start
Step-2 Create a list with elements
Example: List = ['Java', 'Python', 'Perl']
Step-3 Delete an element by index using del List[1]
Step-4 Delete an element by value using [Link]('Java')
Step-5 Delete the last element using [Link]()
Step-6 Display the updated list
Step-7 End

32
Flowchart:

Fig: 4.4 Python program to perform Delete operation from list.

Result: Python program to perform Delete operation from list has verified and executed
successfully.

33
Experiment No: 5

Develop Python program to perform following operations on Tuples.


a) Create b) Access c) Update d) Delete Tuple elements

Aim: Develop Python program to perform Create operation on Tuples.

Prerequisite: The knowledge how to create basic syntax, assigning of values to variables, use of data types
and check type for the creation of tuple is necessary.

Theory: A tuple is an immutable, ordered collection in Python. Once created, the elements in a tuple
cannot be modified, added, or removed. Tuples are defined using parentheses (), and they can contain
items of different data types. Creating a tuple is as simple as putting different comma separated values.
Optionally you can put these comma-separated values between parentheses also.

Syntax & Example

tup1 = ('physics', 'chemistry', 1997, 2000); // Using parenthesis


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d"; // without using parenthesis
The empty tuple is written as two parentheses containing nothing
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is
only one value.
eg: tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Algorithm:
Step-1 Start
Step-2 Declare tuple tup1 with mixed data types (e.g., strings and integers)
tup1 = ('physics', 'chemistry', 1997, 2000)
Step-3 Declare tuple tup2 with only integers
tup2 = (1, 2, 3, 4, 5)
Step-4 Declare tuple tup3 without parentheses
tup3 = "a", "b", "c", "d" (still a tuple due to commas)
Step-5 Display each tuple using print ()
Step-6 Check and display the type of each tuple using type ()

Step-7 End

34
Flowchart:

Fig 5.1 Develop Python program to perform following operations on Tuples.

Result: Develop Python program to perform create operation on Tuples has verifies and executed
successfully.

35
Experiment No: 5

b) Aim: Develop Python program to perform Access operation on Tuples.

Prerequisite: To understand the working of Python tuple where Indexing starts from 0 and Negative
indexing starts from -1 (last element). To access values in tuple, use the square brackets for slicing along
with the index or indices to obtain value available at that index.

Theory: A tuple in Python is an ordered, immutable sequence. Each element can be accessed using its
index, where indexing starts at 0. Negative indexing is also allowed to access elements from the end of the
tuple.
Syntax:
tuple_name[index]
Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
Output:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Algorithm:

Step-1 Start

Step-2 Create a tuple with some elements


Example: tup = ('physics', 'chemistry', 1997, 2000)

Step-3 Access elements using positive indexes

 tup[0] → first element


 tup[2] → third element

Step-4 Access elements using negative indexes

 tup[-1] → last element


 tup[-2] → second last

Step-5 Display the accessed elements

Step-6 End

36
Flowchart:

Fig 5.2 Develop Python program to perform Access operation on Tuples.

Result: Develop Python program to perform Access operation on Tuples has verified and executed
successfully.

37
Experiment No: 5

C) Aim: Develop Python program to perform Update operation on Tuples.


Prerequisite: To understand that Tuples are immutable. To update a tuple need to get idea how to convert it
to a list using list()and then to Modify the desired element in the list after this to convert back to a tuple
using tuple(). Indexing is used to access specific elements.
Theory: : Tuples are immutable which means you cannot update or change the values of tuple elements. You
are able to take portions of existing tuples to create new tuples.
Syntax:
# Original tuple
tuple_name = (item1, item2, item3,….)

# Step 1: Convert tuple to list


temp_list = list(tuple_name)

# Step 2: Update the value in the list


temp_list[index] = new_value

# Step 3: Convert list back to tuple


tuple_name = tuple(temp_list)

Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Output:
(12, 34.56, 'abc', 'xyz')

38
Algorithm:
Step-1 Start
Step-2 Create a tuple with some elements
Example: tup = ('Java', 'Python', 'Perl')
Step-3 Convert the tuple to a list
temp_list = list(tup)
Step-4 Update the desired element in the list using indexing
Example: temp_list[2] = 'C++'
Step-5 Convert the list back to a tuple
updated_tup = tuple(temp_list)
Step-6 Display the updated tuple
Step-7 End
Flowchart

Fig 5.3: Develop Python program to perform Update operation on Tuples.

Result: Develop Python program to perform Update operation on Tuples has verified and executes
successfully.

39
Experiment No: 5

d) Develop Python program to perform Delete Tuple elements operations on Tuples.


Aim: To develop a Python program to perform delete operations on tuple elements by converting the tuple
into a list (since tuples are immutable) and then deleting the required elements.

Prerequisite: To delete elements from a tuple, you need to understand that tuples are immutable. This
means elements can’t be changed or removed directly. To perform deletion, convert the tuple to a list, delete
the element using remove() or del, then convert it back to a tuple.

Syntax:
# Convert tuple to list
temp_list = list(my_tuple)

# Remove element
temp_list.remove(value) # or use: del temp_list[index]

# Convert list back to tuple


my_tuple = tuple(temp_list)
Theory: Tuples are immutable, direct deletion of elements is not allowed. The standard method is to

convert the tuple to a list, perform deletion, and then convert it back to a tuple.

Algorithm:

Step 1: Start the program.


Step 2: Create a tuple with multiple elements.
Example: my_tuple = ('Java', 'Python', 'C++', 'Go')
Step 3: Display the original tuple using the print() function.
Step 4: Convert the tuple to a list using list() function.
Example: temp_list = list(my_tuple)
Step 5: Delete the desired element from the list.
Use either remove(value) or del temp_list[index] as needed.
Step 6: Convert the updated list back to a tuple using tuple() function.
Example: updated_tuple = tuple(temp_list)
Step 7: Display the updated tuple using the print() function.

Step 8: End the program

40
Flowchart:

Fig: 5.4 Python program to perform Delete Tuple elements operations on Tuples
Result: Develop Python program to perform Delete Tuple elements operations on Tuples has verified and
executed successfully.

41
Experiment No: 6

a)Aim : Write python program to perform CREATE operation on set.

Prerequisite: To perform the CREATE operation on a set in Python, one should understand basic Python

syntax, how to take user input with input(), and display output using print(). Knowledge of loops (especially

for loops) and the set data type, which stores unordered, unique elements is essential. Using the .add()

method is also required to insert elements into the set. A set is created by using the set() function or placing

all the elements within a pair of curly braces

Theory:

The CREATE operation refers to the process of initializing and storing data in a set. In Python, a set is an

unordered collection of unique elements. It is defined using the set() constructor or by enclosing elements

within curly braces {}.Sets do not allow duplicate values and do not maintain the order of elements. They

are mutable, meaning elements can be added or removed after creation. The .add() method is used to insert

elements into a set.

Syntax for CREATE

operation on Set in Python

Creating an Empty Set : my_set = set()

Creating a Set with Initial Values: my_set = {"apple", "banana", "cherry"}

Adding Elements to a Set: my_set.add("orange")

First Example:

my_set = set() # Create empty set

42
my_set.add("apple") # Add element to the set

print(my_set) # Output: {'apple'}

Second Example:

Creating a set with initial values

a = {1, 3, 5, 4, 2}

# Display the set

print("The set is:", a)

Output: The set is: {1, 2, 3, 4, 5}

Algorithm:

Step-1: Start

Step-2: Initialize an empty set

Step-3: Input the number of elements to be added (n)

Step-4: Repeat Step-5 and Step-6 for i = 1 to n

Step-5: Accept an element from the user

Step-6: Add the element to the set using .add() method

Step-7: Display the created set

Step-8: Stop

43
Flowchart

Fig. 6.1 Write python program to perform CREATE operation on set


Output: Write python program to perform CREATE operation on set has verified and executed
successfully.

44
Experiment No: 6

b) Aim: Write python program to perform ACCESS operation on set.


Prerequisite: To update a tuple, it must first be converted to a list using the list() function. Once converted,
the desired element can be updated using indexing. After the update, the list is converted back to a tuple
using the tuple() function. This method is a common workaround to modify tuple data while preserving its
structure.
Theory : tuples do not support direct update operations like reassigning values at a specific index. A
common workaround to simulate an update is to convert the tuple into a list, perform the modification, and
then convert the list back to a tuple. This approach leverages the mutability of lists while preserving the
final structure as a tuple. It allows changes to be made without violating the immutability rules of tuple
objects.
Syntax
 Check if an element exists in a set
element in my_set

 Iterate through all elements of a set


for item in my_set:
print(item)
These operations are used to access elements within a set — either by checking membership or by
looping through the set.
First Example:
# Define a set
a = {1, 2, 3, 4, 5}

# Check if 3 is in the set


if 3 in a:
print("3 is present in the set")
else:
print("3 is not present in the set")

# Iterate through the set and display elements


print("Elements in the set:")
45
for item in a:
print(item)
Output:
3 is present in the set
Elements in the set:
1
2
3
4
5

Second Eaxmple:
Example:
Num=set([10,20,30,40,50])
for n in Num:
print(n)
Output:
10
20
30
40
50
Algorithm:
Step 1: Start the program.
Step 2: Create a set with multiple elements.
Example: my_set = {'data 1', 'data 2', 'data 3'}
Step 3: Use a for loop to iterate over the set elements.
Step 4: Display each element using print().
Step 5 (Optional): Convert the set to a list using list(my_set) to access elements by index.
Step 6: Display specific elements using list indexing (e.g., list(my_set)[0]).
Step 7: End the program.

46
Flowchart:

Fig 6.2 python program to perform ACCESS operation on set.

Result: python program to perform ACCESS operation on set, has verified and successfully executed.

47
Experiment No: 6
c) Aim: Write python program to perform UPDATE operation on set.

Prerequisite: To perform an update operation on a set in Python, should understand that sets are unordered
collections of unique, immutable elements. We must be familiar with creating sets using curly braces {} or
the set() constructor. The update() method is used to add multiple elements from another iterable (such as
another set, list, or tuple) to the existing set. It’s also important to know that sets do not allow duplicate values,
so any repeated elements will be ignored during the update.

Theory: In Python, sets are unordered collections of unique elements. The update() method is used to add
multiple elements from another iterable (like a list, tuple, or another set) to an existing set.

Syntax:

[Link](iterable)

Example:

set1 = {'data 1', 'data 2'}


set2 = {'data 2', 'data 3'}

[Link](set2)
Output:
Original set1: {'data 1', 'data 2'}
Set to update from (set2): {'data 2', 'data 3'}
Updated set1: {'data 1', 'data 2', 'data 3'}
Algorithm:

Step 1: Start the program.


Step 2: Create the first set, e.g., set1 = {'data 1', 'data 2'}.
Step 3: Create the second set, e.g., set2 = {'data 2', 'data 3'}.
Step 4: Use the update() method to add elements of set2 to set1 using [Link](set2).
Step 5: Display the updated set1.
Step 6: End the program.

48
Flowchart:

Fig 6.3. python program to perform UPDATE operation on set

Ressult: Write python program to perform UPDATE operation on set has verified and executed
successfully.

49
Experiment No. 6

d) Aim: Write python program to perform DELETE operation on set.

Prerequisite: To delete elements from a set, we must understand that sets are unordered and contain unique
elements. Python provides methods like .remove(), .discard(), and .pop() for deletion. While .remove() raises
an error if the element is missing, .discard() does not. The .pop() method removes a random element. Basic
knowledge of set creation and using print() to display sets is also needed.

Theory: Sets in Python are unordered collections of unique elements. Although individual items in a set
cannot be accessed by index, they can be deleted using methods like remove(), discard(), and pop(). The
remove() method deletes a specific item but raises an error if it’s not found, while discard() deletes the item
without raising an error. The pop() method removes and returns a random element. These operations allow
flexible modification of set contents.

Syntax:

remove():set_name.remove(element) # Removes the element; raises an error if the element is not present.

discard():set_name.discard(element) # Removes the element; does not raise an error if the element is not
found.

pop():set_name.pop() #Removes and returns a random element from the set.

First Example:

Num=set([10,20,30,40,50])

[Link](50)

Print(Num)

Output:

{10,20,30,40}

Second Example:

my_set = {'data 1', 'data 2', 'data 3', 'data 4'}


print("Original set:", my_set)

50
my_set.remove('data 2')
print("After remove('data 2'):", my_set)
my_set.discard('data 5') # 'data 5' is not in the set
print("After discard('data 5'):", my_set)
removed_element = my_set.pop()
print("Element removed using pop():", removed_element)
print("Final set:", my_set)

Algorithm:

Step 1: Start the program.


Step 2: Create a set with multiple elements.
Example: my_set = {'data 1', 'data 2', 'data 3'}
Step 3: Use the remove() method to delete a specific element.
Example: my_set.remove('data 2')
Step 4 (Optional): Use discard() to safely remove an element without raising an error if the element does not
exist.
Example: my_set.discard('data 4')
Step 5 (Optional): Use pop() to remove and return a random element.
Example: my_set.pop()
Step 6: Display the updated set.
Step 7: End the program.

51
Flowchart:

Fig.6.4 python program to perform DELETE operation on set.

Output: Python program to perform DELETE operation on set, has verified and executed successfully.

52
Experiment No: 7
Create a program to perform following operations on Dictionaries in Python:

a) Create b) Access c) Update d) Delete e) Looping through Dictionary

a) Aim: Create a program to perform Create operation on Dictionaries in Python.


Prerequisite: To create a dictionary in Python, we should understand that it stores data as key-value pairs
using curly braces {}. Keys must be unique and immutable, and values can be of any type. We should also
know how to assign values and use print() to display the dictionary.
Theory: To Creating the Dictionary, the dictionary can be created by using multiple key-value pairs enclosed
with the small brackets () and separated by the colon (:). The collections of the key-value pairs are enclosed
within the curly braces {}.
Syntax:
# Creating a dictionary
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
# Accessing values using keys
print(dictionary_name[key1])
print(dictionary_name[key2])
Example:
student = {
'Name': 'Nikhil',
'Age': 28,
'Class': 'First'
}

print(student['Name']) # Output: Nikhil


print(student['Age']) # Output: 28

53
Algorithm:
Step 1: Start the program.
Step 2: Create a dictionary with key-value pairs.
Example: student = {'Name': 'Nikhil', 'Age': 28, 'Class': 'First'}
Step 3: Access values using specific keys.
Example: student['Name'], student['Age']
Step 4: Display the accessed values using the print() function.
Step 5: End the program.
Flowchart:

Fig 7.1 Create a program to perform Create operations on Dictionaries in Python

Output: Create a program to perform create operations on Dictionaries in Python has verified and executed
successfully.

54
Experiment No: 7

b) Aim: Create a program to perform Access operation on Dictionaries in Python.


Prerequisite:
Theory: Dictionaries in Python store data as key-value pairs. To access a value, you use the
corresponding key. If the key exists, it returns the value; if not, it raises a Key Error (unless handled with
methods like .get ()).
Syntax:
# Creating a dictionary
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}

# Accessing values using keys


dictionary_name[key1]
dictionary_name[key2]
Example: student = {
'Name': 'Nikhil',
'Age': 28,
'Class': 'First'
}

print(student['Name']) # Outputs: Nikhil


print(student['Age']) # Outputs: 28

Algorithm:

Step 1: Start the program.


Step 2: Create a dictionary with key-value pairs.
Example: student = {'Name': 'Nikhil', 'Age': 28, 'Class': 'First'}
Step 3: Access values from the dictionary using keys.
Example: student['Name'], student['Age'], student['Class']
Step 4: Display the accessed values using the print() function.
Step 5: End the program.

55
Flowchart:

Fig 7.2 Create a program to perform Access operation on Dictionaries in Python.

Result: Create a program to perform Access operation on Dictionaries in Python, has verified and executed
successfully.

56
Experiment No: 7

c) Aim: Create a program to perform Update operation on Dictionaries in Python.


Prerequisite: To perform the update operation on a dictionary, we should understand how to create
dictionaries using key-value pairs and how to access elements using keys. We should also know that
dictionaries are mutable, allowing values to be changed or new key-value pairs to be added using
assignment or the update()method.
Theory: Dictionaries in Python are mutable, meaning their values can be changed after creation. The
update operation allows modifying the value of an existing key or adding a new key-value pair if the key
doesn’t exist. This can be done using assignment (dict[key] = value) or the update() method.
Syntax:
Using assignment:
dictionary[key] = new_value
Using the update() method:
[Link]({key: new_value})
Example:
student = {'Name': 'Nikhil', 'Age': 28}
student['Age'] = 29 # Updates existing key
student['Section'] = 'A' # Adds new key-value pair
[Link]({'Class': 'First'}) # Adds or updates 'Class'

Algorithm:
Step 1: Start the program.
Step 2: Create a dictionary with key-value pairs.
Example: student = {'Name': 'Nikhil', 'Age': 28, 'Class': 'First'}
Step 3: Update the value of an existing key.
Example: student['Age'] = 29
Step 4: Add a new key-value pair to the dictionary.
Example: student['Section'] = 'A'
Step 5 (Optional): Use the update() method to update multiple values.
Example: [Link]({'Class': 'Second'})
Step 6: Display the updated dictionary using print().
Step 7: End the program.

57
Flowchart:

Fig 7.3 Create a program to perform Update operation on Dictionaries in Python.


Output: Create a program to perform Update operation on Dictionaries in Python, has verified and
successfully executed.

58
Experiment No: 7

d) Aim: Create a program to perform Delete operation on Dictionaries in Python.

Prerequisite: To perform delete operations on dictionaries in Python, we need to understand how to


create dictionaries, access values using keys, and use methods like del, .pop(), and .clear(). We must
also be familiar with the key-value structure of a dictionary.

Theory: To delete items from a dictionary in Python, we use specific methods that remove key-value
pairs. Dictionaries are mutable, so we can modify them by deleting entries. The del statement removes
a pair using the key directly, while the .pop() method deletes a key and returns its value. If we want to
remove all elements at once, the .clear() method is used. These operations help manage dictionary data
efficiently by removing unnecessary or outdated information.

Syntax:
del dictionary[key] # Deletes a specific key-value pair
[Link](key) # Removes the key and returns its value
[Link]() # Removes all key-value pairs from the dictionary

Example:
# Step 1: Create a dictionary
student = {'name': 'jenny', 'age': 31, 'course': 'cse'}
print("Original Dictionary:", student)

# Step 2: Delete a key using 'del'


if 'age' in student:
del student['age']
print("After deleting 'age' using del:", student)
else:
print("'age' key not found.")

# Step 3: Delete a key using pop()


59
removed_value = [Link]('course', None)

if removed_value is not None:

print("Removed value using pop():", removed_value)

print("After deleting 'course' using pop():", student)

else:

print("'course' key not found.")

# Step 4: Clear the dictionary

[Link]()

print("After clearing the dictionary:", student)

Algorithm:

Step 1: Create a dictionary

Step 2: Delete a key using del

Step 3: Delete a key using .pop()

Step 4: Clear all dictionary items using .clear()

Step 5: Display the dictionary after each operation

60
Flowchart:

Fig 7.4 Create a program to perform Delete operation on Dictionaries in Python.


Output: Create a program to perform Delete operation on Dictionaries in Python has verified and successfully
executed.

61
Experiment No:7

e) Aim: Create a program to perform Looping through Dictionary operations on Dictionaries in


Python.

Prerequisite: To loop through a dictionary, we must understand how dictionaries store data in key-
value pairs and be familiar with for loops and dictionary methods like .items(), .keys(), and .values().

Theory:
To loop through a dictionary in Python, we use for loops along with built-in dictionary methods like
.items(), .keys(), and .values(). These allow us to access keys, values, or both at the same time. When
we use for key in dictionary, we iterate through each key. Using [Link]() lets us access only
the values, and [Link]() gives us key-value pairs together. This approach is useful when we
need to display, process, or manipulate the contents of a dictionary efficiently in programs.

Syntax:
for key in dictionary:
print(key) # Loop through keys

for value in [Link]():


print(value) # Loop through values

for key, value in [Link]():


print(key, value) # Loop through key-value pairs

Example:
# Create a dictionary
student = {'name': 'Jenny', 'age': 21, 'course': 'CSE'}
# Loop through keys
print("Keys:")
for key in student:
print(key)
# Loop through values
print("\nValues:")
for value in [Link]():
print(value)
# Loop through key-value pairs
print("\nKey-Value Pairs:")
for key, value in [Link]():
62
print(f"{key}: {value}")

Algorithm:

Algorithm to Loop Through a Dictionary in Python:

Step 1: Start
Step 2: Create a dictionary with key-value pairs
Step 3: Loop through the dictionary using a for loop
a. Use for key in dictionary to access keys
b. Use for value in [Link]() to access values
c. Use for key, value in [Link]() to access both
Step 4: Display each key, value, or key-value pair as needed
Step 5: End

Flowchart:

Fig 7.5. Create a program to perform Looping through Dictionary operations on Dictionaries in
Python.

Result: Create a program to perform Looping through Dictionary operations on Dictionaries in Python has
verified and executed successfully.

63
Experiment No: 8
a) Create a python program to demonstrate use of math built-in function.
b) Create a python program to demonstrate the use of string built-in function.
Aim: To create a Python program that demonstrates the use of built-in mathematical functions using the

math module.

Prerequisite: To use math functions, we need to import Python's built-in math module which provides

access to mathematical operations like square root, power, trigonometry, logarithms, and constants

like π (pi).

Theory:

The math module provides mathematical functions such as sqrt() for square root, pow() for power, floor()

and ceil() for rounding, sin() and cos() for trigonometric operations, and constants like pi and e.

Syntax:

import math # Import the math module

[Link](x) # Returns the square root of x

[Link](x, y) # Returns x raised to the power y

[Link](x) # Rounds x down to the nearest integer

[Link](x) # Rounds x up to the nearest integer

[Link]([Link](x)) # Returns sine of x degrees

[Link]([Link](x)) # Returns cosine of x degrees

[Link](x) # Returns the natural logarithm of x

[Link] # Returns the value of π (pi)

64
Example:

import math

# Demonstrating math built-in functions

print("Square root of 16:", [Link](16))

print("3 raised to power 4:", [Link](3, 4))

print("Floor of 7.9:", [Link](7.9))

print("Ceil of 7.1:", [Link](7.1))

print("Sine of 30 degrees:", [Link]([Link](30)))

print("Cosine of 60 degrees:", [Link]([Link](60)))

print("Logarithm of e (natural log):", [Link](math.e))

print("Value of Pi:", [Link])

Algorithm:
Step 1: Start
Step 2: Import the math module
Step 3: Use [Link](x) to find the square root of a number
Step 4: Use [Link](x, y) to find x raised to the power y
Step 5: Use [Link](x) to round down a number
Step 6: Use [Link](x) to round up a number
Step 7: Use [Link]() and [Link]() to calculate sine and cosine values (convert degrees to radians using
[Link]())
Step 8: Use [Link](x) to find the natural logarithm
Step 9: Use [Link] to get the value of π
Step 10: Display all results
Step 11: End

65
Flowchart:

Fig 8.1 Create a python program to demonstrate use of math built-in function.

Result: Create a python program to demonstrate use of math built-in function has verified and executed
successfully.

66
Experiment No: 8

b) Create a python program to demonstrate the use of string built-in function.

Aim: To create a Python program that demonstrates the use of string built-in functions.

Prerequisite: To use string functions, we must understand what a string is and how methods like upper(), lower(),
replace(), find(), split(), and strip() work in Python.

Theory: Python provides many built-in string methods to perform common operations like changing case, searching
substrings, replacing characters, splitting strings into a list, and removing whitespace. These functions help in efficient
string manipulation.

Syntax:
[Link]() # Converts all characters to uppercase
[Link]() # Converts all characters to lowercase
[Link](a, b) # Replaces 'a' with 'b'
[Link](x) # Finds the position of substring 'x'
[Link]() # Splits the string into a list
[Link]() # Removes leading and trailing whitespace
Example:

# Step 1: Create a string


text = " Hello Python Programming "

# Step 2: Use string functions


print("Original string:", text)
print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Stripped:", [Link]())
print("Replaced 'Python' with 'Java':", [Link]("Python", "Java"))
print("Position of 'Python':", [Link]("Python"))
print("Split into words:", [Link]())
Example:
# Create a string

67
text = " Hello Python World "

# Apply string built-in functions

print("Original string:", text)


print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Stripped:", [Link]())
print("Replaced 'Python' with 'Java':", [Link]("Python", "Java"))
print("Find position of 'World':", [Link]("World"))
print("Split into words:", [Link]())

Algorithm to Demonstrate Use of String Built-in Functions in Python:

Step 1: Start

Step 2: Create a string variable with some text

Step 3: Use upper() to convert the string to uppercase

Step 4: Use lower() to convert the string to lowercase

Step 5: Use strip() to remove leading and trailing spaces

Step 6: Use replace() to replace a word or character in the string

Step 7: Use find() to locate the position of a substring

Step 8: Use split() to break the string into a list of words

Step 9: Display all the results

Step 10: End

68
Flowchart:

Fig 8.2 Create a python program to demonstrate the use of string built-in function.

Result: Create a python program to demonstrate the use of string built-in function has verified and
executed successfully.

69
Experiment No: 9

Aim: Write a program to define a function with default arguments.

Prerequisite: To use default arguments in Python, we should know how to define functions using def,
pass parameters, and assign default values to them. Basic knowledge of function calls is also required.

Theory:
In Python, default arguments allow a function to assume a value for a parameter if no argument is
provided during the call. These defaults are set in the function definition. This feature makes functions
more flexible and reduces the need to pass all arguments every time.

Syntax:
def function_name(param1, param2=default_value, ...):
# Function body
statement(s)

# Function call examples


function_name(arg1) # Uses default for param2
function_name(arg1, arg2) # Overrides default

Example:
# Function with default argument
def greet(name, msg="Welcome!"):
print("Hello", name + "!", msg)

# Calling with and without default argument


greet("Alice") # Uses default message
greet("Bob", "Good day!") # Uses custom message

Algorithm

Step 1: Start
Step 2: Define a function using the def keyword
Step 3: Assign a default value to one or more parameters in the function definition
Step 4: Inside the function, perform desired operations using the parameters
Step 5: Call the function with and without passing values for the default arguments

70
Step 6: Display the output
Step 7: End

Flowchart:

Fig 9.1 Write a program to define a function with default arguments.

Result: Write a program to define a function with default arguments has verified and executed
successfully.

71
Experiment No: 10

Write Python Program to Count the Number of words and lines in a Text File.

a)Aim: To write a Python program that counts the number of words and lines in a text file.

Prerequisite: We should know how to open and read files in Python using functions like open(), and
methods like .readlines() and .split().

Theory: To count lines, we read the file line by line. To count words, we split each line into words using the
split() method and count them. This helps in analyzing the text content efficiently.

Example:

Assume we have a file named [Link] with the following content:

Python is a powerful language.


It is widely used in many applications.
File handling is an important concept in Python.

with open("[Link]", "r") as file:


lines = [Link]()

line_count = len(lines)
word_count = sum(len([Link]()) for line in lines)

print("Number of lines:", line_count)


print("Number of words:", word_count)

Algorithm:

Step 1: Start
Step 2: Open the text file in read mode using open()
Step 3: Read all lines from the file using .readlines()
Step 4: Count the number of lines using len(lines)
Step 5: Initialize a word counter to 0
Step 6: For each line, split the line into words using .split() and add the number of words to the word counter
Step 7: Display the line count and word count

72
Step 8: Close the file (automatically done if using with)
Step 9: End

Flow chart:

Fig 10.1 Python Program to Count the Number of words and lines in a Text File.

Result: Python Program to Count the Number of words and lines in a Text File has verified and executed
successfully.

73
Experiment No: 10

a) Write Python Program to Read a String from the User and Append it into a File.

Aim: To write a Python program that reads a string from the user and appends it into a text file.

Prerequisite: To append a string to a file in Python, we need to understand how to take input using the input()
function and how to open a file in append mode using open() with the 'a' mode. We should also know how to
write data to a file using the .write() method.

Theory:

To append data to a file in Python, we use the open() function with the mode 'a', which stands for append. This
mode allows new content to be added to the end of the file without deleting existing data. The input() function
is used to take a string from the user, and the .write() method writes this string to the file. Adding \n ensures
the new text appears on a new line.

Algorithm to Read a String from the User and append it into a File:

Step 1: Start
Step 2: Prompt the user to enter a string using the input() function
Step 3: Open the target file in append mode using open(filename, 'a')
Step 4: Write the user's input to the file using the .write() method
Step 5: Add a newline character \n to ensure proper formatting
Step 6: Close the file (automatically done if using with statement)
Step 7: Display a success message
Step 8: End

74
Flowchart:

75
Fig 10.2 Write Python Program to Read a String from the User and append it into a File.

Result: Write Python Program to Read a String from the User and Append it into a File has verified and
executed successfully

Experiment No: 11
Create an array using [Link] the dimension of the array using NumPy inbuilt methods.

Aim: To create a NumPy array and find its dimension using NumPy inbuilt methods.
Prerequisite: To work with NumPy, we need to import it using import numpy as np. Arrays in NumPy can be
one-dimensional, two-dimensional, or higher. We can use the .ndim attribute to find the number of
dimensions.
Theory: NumPy arrays are used for efficient numerical computations. The .ndim property returns the number
of dimensions (axes) of an array.
Syntax:
import numpy as np
array = [Link]([elements])
[Link] # returns the number of dimensions
Example:
import numpy as np

# Create a 2D array
arr = [Link]([[1, 2, 3], [4, 5, 6]])

# Display the array


print("Array:\n", arr)

# Find and display the number of dimensions


print("Number of dimensions:", [Link])

Algorithm:

Algorithm to Create an Array Using NumPy and Find Its Dimension:

Step 1: Start
Step 2: Import the NumPy library using import numpy as np
Step 3: Create an array using [Link]() with a list or list of lists
Step 4: Use the .ndim attribute to get the number of dimensions of the array

76
Step 5: Display the array and its dimension
Step 6: End

Flowchart:

Fig 11.1 Create an array using [Link] the dimension of the array using NumPy inbuilt methods.

Result: Create an array using [Link] the dimension of the array using NumPy inbuilt methods has
verified and executed successfully.

77
Experiment No: 12

Write Python program to create Widgets using Tkinter.

Aim: To write a Python program that creates GUI widgets using the Tkinter library.

Prerequisite: To work with Tkinter, we must import it using from tkinter import *. Tkinter allows us to create various
widgets like labels, buttons, entries, and more.
Theory:
Tkinter provides a set of classes to create GUI applications. Common widgets include Label, Button, and Entry. These
widgets are placed in a window using layout managers like .pack(), .grid(), or .place().
Syntax:
from tkinter import *

# Create main window


root = Tk()

# Create widgets
Label(root, text="Text").pack()
Entry(root).pack()
Button(root, text="Button", command=function_name).pack()

# Run the GUI loop


[Link]()
Example:

from tkinter import *


# Create main window
root = Tk()
[Link]("Simple Tkinter Example")
[Link]("300x150")

# Create and pack a Label


label = Label(root, text="Enter your name:")
[Link](pady=5)

# Create and pack an Entry


entry = Entry(root)
[Link](pady=5)

78
# Create and pack a Button
def greet():
name = [Link]()
[Link](text="Hello, " + name + "!")

button = Button(root, text="Greet", command=greet)


[Link](pady=10)

# Run the GUI application


[Link]()

Output:

A window appears with:

 A label: “Enter your name:”


 An entry box for typing a name
 A button labeled “Greet”

When the button is clicked, the label updates to:


“Hello, [name]!”

Algorithm:

Short Algorithm with Steps:

Step 1: Import Tkinter.

Step 2: Initialize main window (root = Tk()).

Step 3: Create widgets (Label, Entry, Button).

Step 4: Pack or place widgets.

Step 5: Define callback functions (if needed).

Step 6: Start the GUI loop ([Link]()).

79
Flowchart

Fig 12.1 Write Python program to create Widgets using Tkinter.

Result: Write Python program to create Widgets using Tkinter has verified and executed successfully.

80
Experiment No: 13
Aim: Write a Python program to compute square root of a number.
Prerequisite: To compute the square root in Python, one should know how to take user input, use conditional
statements, and import the math module. Basic understanding of functions and number handling is also
required.
Theory: The square root of a number is a value that multiplies by itself to give the original number. In
Python, it can be calculated using [Link]() or number ** 0.5, but only for non-negative numbers.
Syntax:
import math # Import math module
num = float(input("Enter a number: ")) # Take input from user
if num >= 0:
result = [Link](num) # Calculate square root
print(result) # Display result
else:
print("Invalid input") # Handle negative numbers
Example:
import math

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

if num >= 0:

result = [Link](num)

print(f"The square root of {num} is {result}")

else:

print("Square root of a negative num

81
Algorithm:
Step 1: Start
Step 2: Import the math module
Step 3: Prompt the user to enter a number
Step 4: Read and store the input in a variable num
Step 5: Check if num is greater than or equal to 0
→ If true, proceed to Step 6
→ If false, display an error message and go to Step 8
Step 6: Compute the square root using [Link](num)
Step 7: Display the result
Step 8: End

Flowchart:

Fig 13.1 Write a Python program to compute square root of a number.


Result: Write a Python program to compute square root of a number is verified and successfully executed.

82
Experiment No: 14
Write a program to print largest of three numbers using if else statement.
Aim: To write a Python program that takes three numbers as input from the user and determines the largest
among them using if-else statements.
Prerequisite: To perform this practical, students should know how to take user input using input(), convert it
to numeric types, and use comparison operators. They should also understand decision-making using if, elif,
and else statements, and display output using the print() function.
Theory: In Python, if, elif, and else statements are used to make decisions based on conditions. To find the
largest of three numbers, we compare them using relational operators like >. The program checks each
condition and prints the number that satisfies the condition for being the greatest.
Syntax:
if condition1:
# code block if condition1 is true
elif condition2:
# code block if condition2 is true
else:
# code block if none of the above conditions are true
Example:
# Program to find the largest of three numbers

a = 15
b = 28
c = 12

if a >= b
Algorithm:

Step 1: Start

Step 2: Input three numbers and store them in variables a, b, and c

Step 3: Compare a with b and c

Step 4: If a is greater than or equal to both b and c, print a as the largest

Step 5: Else if b is greater than or equal to both a and c, print b as the largest

Step 6: Else, print c as the largest

Step 7: End

83
Flowchart:

Fig 14.1: Write a program to print largest of three numbers using if else statement.

Result: Write a program to print largest of three numbers using if else statement has verified and executed
successfully.

84
Experiment No: 15
Write a program to sort list of n numbers.

Aim: To write a Python program that accepts a list of n numbers from the user and sorts them in ascending
order using the built-in sort() method.

Prerequisite: To perform this practical, students should know how to take multiple inputs using loops, store
them in a list, and use Python’s built-in list methods such as append() and sort(). They should also understand
how to use for loops and the print() function.

Theory: In Python, a list is a collection of elements that can be modified. To sort a list, we can use the built-in
sort() method which arranges the elements in ascending order by default. The list is first populated using user
inputs and then passed to the sort() method, which internally applies a sorting algorithm to reorder the

Syntax:

list_name = [ ]
list_name.append(element) # To add elements to the list
list_name.sort() # To sort the list in ascending order
Example:
n = int(input("Enter number of elements: "))
numbers = []

for i in range(n):
num = float(input(f"Enter number {i+1}: "))
[Link](num)

[Link]()
print("Sorted list:", numbers)
Algorithm:
Step 1: Start
Step 2: Input the value of n (number of elements)
Step 3: Initialize an empty list
Step 4: Repeat steps 5–6 for i = 1 to n
Step 5: Input a number
Step 6: Append the number to the list
Step 7: Sort the list using sort()
Step 8: Display the sorted list
Step 9: End
85
Flowchart:

Fig 15.1 Write a program to sort list of n numbers.

Result: Write a program to sort list of n numbers has verified and executed successfully.

86
Experiment No: 16
Write a program to design simple calculator
Aim: To write a Python program that functions as a simple calculator to perform basic arithmetic operations
such as addition, subtraction, multiplication, and division based on user input.
Prerequisite: To perform this practical, students should know how to take input using input(), use arithmetic
operators, apply if-else statements, and define simple functions in Python.
Theory:
A calculator program uses arithmetic operators to perform basic mathematical operations like addition,
subtraction, multiplication, and division. In Python, this is achieved using +, -, *, and / operators. The program
takes input from the user, checks the selected operation using if-elif-else conditions, and performs the
corresponding calculation. Functions can be used to organize the code and improve readability.
Syntax:
def function_name(param1, param2, operator):
if operator == '+':
return param1 + param2
elif operator == '-':
return param1 - param2
elif operator == '*':
return param1 * param2
elif operator == '/':
return param1 / param2
else:
return "Invalid operator"

Algorithm:
Step 1: Start
Step 2: Define a function to perform calculation based on the operator
Step 3: Input the first number
Step 4: Input the second number
Step 5: Input the operator (+, -, *, /)
Step 6: Check the operator using if-elif-else
→ If +, perform addition
→ If -, perform subtraction
→ If *, perform multiplication
→ If /, check if the second number is not zero and perform division
→ Else, display invalid operator message
Step 7: Display the result
Step 8: End

87
Flowchart:

Fig.16.1 Flowchart to design simple calculator.


Result: Write a program to design simple calculator has verified and successfully executed.

88
Experiment No: 17

Write a program to create file which stores the following information: Name, Roll No, Name of 5
Subjects and Marks of 5 subjects.

Aim: To write a Python program that creates a file and stores student information including Name, Roll
Number, names of 5 subjects, and their corresponding marks.

Prerequisite:

To perform this practical, students should know how to take user input, use lists, and perform basic file
operations in Python such as opening, writing to, and closing a file using the open() and write() functions.

Theory:

File handling in Python allows data to be stored permanently on disk. Using functions like open(), write(), and
close(), we can create and manage files. In this program, we collect student details such as name, roll number,
names of 5 subjects, and their marks. These inputs are stored in lists and then written to a text file using write
mode ("w"). This helps in saving structured information for future use or processing.

Syntax:

with open("[Link]", "w") as file:

[Link]("Text to write\n")

Algorithm:

Step 1: Start
Step 2: Input student name and roll number
Step 3: Initialize two empty lists for subjects and marks
Step 4: Repeat steps 5–6 five times
Step 5: Input subject

89
Flowchart:

Fig 17.1 Program to create file which stores the following information: Name, Roll No, Name of 5
Subjects and Marks of 5 subjects.

Output: Write a program to create file which stores the following information: Name, Roll No, Name of 5
Subjects and Marks of 5 subjects, has verified and executed successfully.

90
91

You might also like