PYTHON LAB EXERCISES
1. Program using variables, constants, I/O statements in Python
# Constants
TAX_RATE = 0.15
# Input Statements
name = input("Enter your name: ")
salary = float(input("Enter your monthly salary: "))
# Calculate tax and net salary
tax_amount = salary * TAX_RATE
net_salary = salary - tax_amount
# Output Statements
print("\nEmployee Details")
print("Name:", name)
print("Monthly Salary: $", salary)
print("Tax Amount (15%): $", tax_amount)
print("Net Salary: $", net_salary)
2. Program using Operators in Python.
# Arithmetic Operators
a = 10
b=5
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
modulo = a % b
exponentiation = a ** b
floor_division = a // b
# Comparison Operators
greater_than = a > b
less_than = a < b
equal_to = a == b
not_equal_to = a != b
greater_than_or_equal_to = a >= b
less_than_or_equal_to = a <= b
# Logical Operators
x = True
y = False
logical_and = x and y
logical_or = x or y
logical_not_x = not x
logical_not_y = not y
# Output
print("Arithmetic Operators:")
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Modulo:", modulo)
print("Exponentiation:", exponentiation)
print("Floor Division:", floor_division)
print("\nComparison Operators:")
print("Greater Than:", greater_than)
print("Less Than:", less_than)
print("Equal To:", equal_to)
print("Not Equal To:", not_equal_to)
print("Greater Than or Equal To:", greater_than_or_equal_to)
print("Less Than or Equal To:", less_than_or_equal_to)
print("\nLogical Operators:")
print("Logical AND:", logical_and)
print("Logical OR:", logical_or)
print("Logical NOT (x):", logical_not_x)
print("Logical NOT (y):", logical_not_y)
3. Program using Conditional Statements.
# Input
num = float(input("Enter a number: "))
# Conditional Statements
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
4. Program using Loops in Python.
# For Loop Example - Printing numbers from 1 to 5
for num in range(1, 6):
print(num)
Output:
While Loop:
# While Loop Example - Printing numbers from 1 to 5
num = 1
while num <= 5:
print(num)
num += 1
Output:
5
5. Program using Jump Statements in Python.
Using the break statement:
# Program to find the first occurrence of a number in a list
numbers = [10, 20, 30, 40, 50]
search_number = int(input("Enter a number to search: "))
for num in numbers:
if num == search_number:
print(f"{search_number} found in the list.")
break
else:
print(f"{search_number} not found in the list.")
Using the continue statement:
# Program to print odd numbers from 1 to 10
for num in range(1, 11):
if num % 2 == 0:
continue
print(num)
Output:
9
6. Program using Functions in Python.
# Function to calculate the area of a rectangle
def calculate_rectangle_area(length, width):
return length * width
# Function to check if a number is even or odd
def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Function to print a message multiple times
def print_message(message, times):
for _ in range(times):
print(message)
# Main program
if __name__ == "__main__":
# Call the functions with some examples
length = 5
width = 3
area = calculate_rectangle_area(length, width)
print(f"The area of the rectangle with length {length} and width {width} is: {area}")
number = 7
result = check_even_odd(number)
print(f"The number {number} is {result}.")
message = "Hello, World!"
repeat_times = 3
print_message(message, repeat_times)
Output:
The area of the rectangle with length 5 and width 3 is: 15
The number 7 is Odd.
Hello, World!
Hello, World!
Hello, World!
7. Program using Recursion in Python.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Main program
if __name__ == "__main__":
num = int(input("Enter a number: "))
result = factorial(num)
print(f"The factorial of {num} is: {result}")
Output:
Enter a number: 5
The factorial of 5 is: 120
8. Program using Arrays in Python.
# Create an array (list) of numbers
numbers = [1, 2, 3, 4, 5]
# Accessing elements in the array
print("Array elements:")
for num in numbers:
print(num)
# Adding elements to the array
[Link](6)
print("\nAfter adding 6 to the array:")
print(numbers)
# Removing elements from the array
[Link](3)
print("\nAfter removing 3 from the array:")
print(numbers)
# Updating elements in the array
numbers[1] = 10
print("\nAfter updating the element at index 1 to 10:")
print(numbers)
# Finding the length of the array
length = len(numbers)
print("\nLength of the array:", length)
# Finding the maximum and minimum values in the array
maximum = max(numbers)
minimum = min(numbers)
print("Maximum value in the array:", maximum)
print("Minimum value in the array:", minimum)
Output:
Array elements:
After adding 6 to the array:
[1, 2, 3, 4, 5, 6]
After removing 3 from the array:
[1, 2, 4, 5, 6]
After updating the element at index 1 to 10:
[1, 10, 4, 5, 6]
Length of the array: 5
Maximum value in the array: 10
Minimum value in the array: 1
9. Program using Strings in Python.
# String Concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print("Full Name:", full_name)
# String Length
message = "Hello, World!"
length = len(message)
print("Length of the message:", length)
# String Indexing
first_char = message[0]
last_char = message[-1]
print("First Character:", first_char)
print("Last Character:", last_char)
# String Slicing
substring = message[7:12]
print("Substring:", substring)
# String Upper and Lower Case
uppercase_message = [Link]()
lowercase_message = [Link]()
print("Uppercase Message:", uppercase_message)
print("Lowercase Message:", lowercase_message)
# String Replace
replaced_message = [Link]("World", "Python")
print("Replaced Message:", replaced_message)
# String Split
words = [Link](",")
print("Words:", words)
Output:
Full Name: John Doe
Length of the message: 13
First Character: H
Last Character: !
Substring: World
Uppercase Message: HELLO, WORLD!
Lowercase Message: hello, world!
Replaced Message: Hello, Python!
Words: ['Hello', ' World!']
10. Program using Modules in Python.
In Python, modules are files containing Python definitions and statements that can be used in other
Python programs. Below is an example of a Python program that uses a module to perform
arithmetic operations:
Create a Python file named my_module.py with the following content:
# my_module.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Cannot divide by zero"
return a / b
Create another Python file in the same directory as my_module.py and name it [Link]. In this file,
we'll import and use the functions from the my_module module:
# [Link]
import my_module
# Using functions from my_module
a = 10
b=5
result_add = my_module.add(a, b)
result_subtract = my_module.subtract(a, b)
result_multiply = my_module.multiply(a, b)
result_divide = my_module.divide(a, b)
# Output
print(f"{a} + {b} = {result_add}")
print(f"{a} - {b} = {result_subtract}")
print(f"{a} * {b} = {result_multiply}")
print(f"{a} / {b} = {result_divide}")
Explanation:
We create a separate module my_module.py, which contains four functions: add(), subtract(),
multiply(), and divide(). Each function performs a specific arithmetic operation.
In the [Link] file, we import the my_module module using the import statement.
We use the functions from my_module by calling them with appropriate arguments. The results of
the arithmetic operations are stored in different variables.
Finally, we print the results of the arithmetic operations.
Output:
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0
11. Program using Lists in Python.
# Create a list of numbers
numbers = [10, 20, 30, 40, 50]
# Accessing elements in the list
print("List elements:")
for num in numbers:
print(num)
# Adding elements to the list
[Link](60)
print("\nAfter adding 60 to the list:")
print(numbers)
# Removing elements from the list
[Link](30)
print("\nAfter removing 30 from the list:")
print(numbers)
# Updating elements in the list
numbers[1] = 25
print("\nAfter updating the element at index 1 to 25:")
print(numbers)
# Finding the length of the list
length = len(numbers)
print("\nLength of the list:", length)
# Finding the maximum and minimum values in the list
maximum = max(numbers)
minimum = min(numbers)
print("Maximum value in the list:", maximum)
print("Minimum value in the list:", minimum)
# List Slicing
subset = numbers[1:4]
print("\nSubset of the list:", subset)
# List Concatenation
more_numbers = [70, 80, 90]
concatenated_list = numbers + more_numbers
print("\nConcatenated list:", concatenated_list)
Explanation:
We create a list numbers containing the elements [10, 20, 30, 40, 50].
We demonstrate accessing elements using a for loop to print each element.
We add a new element 60 to the list using the append() method.
We remove the element 30 from the list using the remove() method.
We update the element at index 1 (which is 20) to 25.
We use the len() function to find the length of the list.
We use the max() and min() functions to find the maximum and minimum values in the list,
respectively.
We demonstrate list slicing by extracting a subset of the original list using the slice [1:4].
We concatenate two lists numbers and more_numbers using the + operator.
output:
List elements:
10
20
30
40
50
After adding 60 to the list:
[10, 20, 30, 40, 50, 60]
After removing 30 from the list:
[10, 20, 40, 50, 60]
After updating the element at index 1 to 25:
[10, 25, 40, 50, 60]
Length of the list: 5
Maximum value in the list: 60
Minimum value in the list: 10
Subset of the list: [25, 40, 50]
Concatenated list: [10, 25, 40, 50, 60, 70, 80, 90]
12. Program using Tuples in Python.
# Create a tuple of colors
colors = ("red", "green", "blue", "yellow", "orange")
# Accessing elements in the tuple
print("Tuple elements:")
for color in colors:
print(color)
# Accessing elements using indexing
first_color = colors[0]
last_color = colors[-1]
print("\nFirst Color:", first_color)
print("Last Color:", last_color)
# Tuple Slicing
subset = colors[1:4]
print("\nSubset of the tuple:", subset)
# Finding the length of the tuple
length = len(colors)
print("\nLength of the tuple:", length)
# Finding the index of an element
index_yellow = [Link]("yellow")
print("Index of 'yellow':", index_yellow)
# Counting occurrences of an element
count_green = [Link]("green")
print("Occurrences of 'green':", count_green)
# Attempting to modify the tuple (this will raise an error)
try:
colors[0] = "pink"
except TypeError as e:
print("\nError:", e)
Explanation:
We create a tuple colors containing the elements ("red", "green", "blue", "yellow", "orange").
We demonstrate accessing elements using a for loop to print each color.
We access individual elements using indexing and print the first and last colors.
We demonstrate tuple slicing by extracting a subset of the original tuple using the slice [1:4].
We use the len() function to find the length of the tuple.
We use the index() method to find the index of a specific element ("yellow" in this case).
We use the count() method to count the occurrences of a specific element ("green" in this case).
We attempt to modify the tuple (assignment), which raises a TypeError since tuples are immutable.
Output:
Tuple elements:
red
green
blue
yellow
orange
First Color: red
Last Color: orange
Subset of the tuple: ('green', 'blue', 'yellow')
Length of the tuple: 5
Index of 'yellow': 3
Occurrences of 'green': 1
Error: 'tuple' object does not support item assignment
13. Program using Dictionaries in Python.
# Create a dictionary of student details
student = {
"name": "John Doe",
"age": 25,
"roll_number": "ABC123",
"marks": {
"math": 85,
"science": 90,
"english": 78
# Accessing elements in the dictionary
print("Student Details:")
print("Name:", student["name"])
print("Age:", student["age"])
print("Roll Number:", student["roll_number"])
print("Math Marks:", student["marks"]["math"])
# Adding elements to the dictionary
student["gender"] = "Male"
print("\nAfter adding gender to the dictionary:")
print(student)
# Updating elements in the dictionary
student["age"] = 26
print("\nAfter updating age to 26:")
print(student)
# Removing elements from the dictionary
removed_subject = student["marks"].pop("english")
print("\nAfter removing English marks from the dictionary:")
print(student)
print("Removed Subject:", removed_subject)
# Checking if a key exists in the dictionary
if "gender" in student:
print("\nGender:", student["gender"])
else:
print("\nGender not specified in the dictionary.")
# Finding the length of the dictionary
length = len(student)
print("\nNumber of items in the dictionary:", length)
Explanation:
We create a dictionary student containing various student details, including name, age, roll number,
and marks in different subjects.
We demonstrate accessing elements in the dictionary using their keys and nested dictionary access
for "math" marks.
We add a new key-value pair "gender" and its value "Male" to the dictionary using assignment.
We update the age of the student from 25 to 26.
We remove the "english" marks from the nested dictionary and store the removed value in the
variable removed_subject.
We check if the key "gender" exists in the dictionary using the in keyword.
We find the length of the dictionary using the len() function.
Output:
Student Details:
Name: John Doe
Age: 25
Roll Number: ABC123
Math Marks: 85
After adding gender to the dictionary:
{'name': 'John Doe', 'age': 25, 'roll_number': 'ABC123', 'marks': {'math': 85, 'science': 90, 'english':
78}, 'gender': 'Male'}
After updating age to 26:
{'name': 'John Doe', 'age': 26, 'roll_number': 'ABC123', 'marks': {'math': 85, 'science': 90, 'english':
78}, 'gender': 'Male'}
After removing English marks from the dictionary:
{'name': 'John Doe', 'age': 26, 'roll_number': 'ABC123', 'marks': {'math': 85, 'science': 90}, 'gender':
'Male'}
Removed Subject: 78
Gender: Male
Number of items in the dictionary: 5
14. Program for File Handling in Python.
Writing to a File:
# Writing data to a file
with open("[Link]", "w") as file:
[Link]("Hello, this is a file handling example.\n")
[Link]("We will write this text to the file.\n")
Reading from a File:
# Reading data from a file
with open("[Link]", "r") as file:
content = [Link]()
print("File Content:")
print(content)
Explanation:
In the first part, we use the open() function with the mode "w" to open the file [Link] in write
mode. The file is automatically closed after the with block is executed. We then use the write()
method to write two lines of text to the file.
In the second part, we use the open() function with the mode "r" to open the same file in read
mode. Again, the file is automatically closed after the with block is executed. We use the read()
method to read the entire content of the file and then print it to the console.
Output:
File Content:
Hello, this is a file handling example.
We will write this text to the file.