Python Programming Lab Manual for B.Tech
Python Programming Lab Manual for B.Tech
LABORATORY MANUAL
st st nd
[Link]. 1 Year – I / II Semester
Common to all Branches
Course Outcomes:
At the end of this course, students will be able to
CO1 solve basic engineering problems using Python programs
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.
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.
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
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
PREPARED BY APPROVED BY
LAB INCHARGE HOD (APPLIED SCIENCES)
Programming for problem solving using Python lab
(25C1CSU-112)
PREPARED BY APPROVED BY
LAB INCHARGE HOD (APPLIED SCIENCES)
Experiment No.1
Aim: To install and configure a Python Integrated Development Environment (IDE) for writing,
executing, and debugging Python programs efficiently.
Tools Used
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.
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.
5
Experiment No.1
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
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.
Theory: In Python, the input() function is used to take input from the user. By default, it reads the input as a
Syntax:
Displaying output
print("Message", variable_name)
Algorithm:
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
Pre-requisite: Knowledge of basics Python programming with understanding of conditional (if, elif, else)
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
Pre-requisite: To understand the Python syntax for input (), if, elif, and else statements as well familiarity
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
Step 1: Start
Step 2: Prompt the user to enter the color name of the resistor band.
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
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
Theory: The factorial of a non-negative integer n is the product of all positive integers less than or equal to
Syntax:
# code block
while condition:
# code block
2. The loop must update the control variable to avoid infinite loops.
16
Algorithm:
Step-1 Start
Step-4 If num < 0, display “Factorial does not exist for negative numbers”
Step-5 Else,
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
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
Aim: To create a simple Python program demonstrating the use of the for loop by printing a multiplication
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
Syntax:
# code to execute
21
print("Palindrome")
else:
print("Not a palindrome")
result = num * i
Algorithm:
1 Pattern Building (Right-Angled Triangle)
Step 1: Start
Step 6: End
2 Multiplication Table
Step 1: Start
22
Step 4: Multiply num by i
Step 7: End
3 3. Palindrome Check
Step 1: Start
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:
Prerequisite: The knowledge of basic python syntax is needed. To create a list is as simple as putting
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
Example:
Step-5 End
26
Flowchart:
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
my_list[index]
Example: -1 accesses the last element and-2 accesses the second-last, and so on.
List2[1] 20
List2[1:3] [20,30]
List2[5]
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:
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
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
Step-6 END
30
Flowchart:
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
Syntax:
del list_name[index]
Syntax:
list_name.remove('value')
.pop(index) Method: Removes and returns the element at the specified index (default is the last element):
Syntax:
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:
Result: Python program to perform Delete operation from list has verified and executed
successfully.
33
Experiment No: 5
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.
Step-7 End
34
Flowchart:
Result: Develop Python program to perform create operation on Tuples has verifies and executed
successfully.
35
Experiment No: 5
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-6 End
36
Flowchart:
Result: Develop Python program to perform Access operation on Tuples has verified and executed
successfully.
37
Experiment No: 5
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
Result: Develop Python program to perform Update operation on Tuples has verified and executes
successfully.
39
Experiment No: 5
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 the tuple to a list, perform deletion, and then convert it back to a tuple.
Algorithm:
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
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
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
First Example:
42
my_set.add("apple") # Add element to the set
Second Example:
a = {1, 3, 5, 4, 2}
Algorithm:
Step-1: Start
Step-8: Stop
43
Flowchart
44
Experiment No: 6
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:
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:
[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:
48
Flowchart:
Ressult: Write python program to perform UPDATE operation on set has verified and executed
successfully.
49
Experiment No. 6
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.
First Example:
Num=set([10,20,30,40,50])
[Link](50)
Print(Num)
Output:
{10,20,30,40}
Second Example:
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:
51
Flowchart:
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:
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:
Output: Create a program to perform create operations on Dictionaries in Python has verified and executed
successfully.
54
Experiment No: 7
Algorithm:
55
Flowchart:
Result: Create a program to perform Access operation on Dictionaries in Python, has verified and executed
successfully.
56
Experiment No: 7
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:
58
Experiment No: 7
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)
else:
[Link]()
Algorithm:
60
Flowchart:
61
Experiment No:7
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
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:
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:
64
Example:
import math
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
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:
67
text = " Hello Python World "
Step 1: Start
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
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)
Example:
# Function with default argument
def greet(name, msg="Welcome!"):
print("Hello", name + "!", msg)
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:
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:
line_count = len(lines)
word_count = sum(len([Link]()) for line in lines)
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]])
Algorithm:
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
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 widgets
Label(root, text="Text").pack()
Entry(root).pack()
Button(root, text="Button", command=function_name).pack()
78
# Create and pack a Button
def greet():
name = [Link]()
[Link](text="Hello, " + name + "!")
Output:
Algorithm:
79
Flowchart
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
if num >= 0:
result = [Link](num)
else:
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:
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 5: Else if b is greater than or equal to both a and c, print b 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:
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:
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:
[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