SREE VENKATESWARA
COLLEGE OF ENGINEERING(AUTONOMOUS)
NORTH RAJUPALEM, NELLORE (DIST)
AFFILIATED TO SBTET, AP
PYTHON PROGRAMMING
LAB MANUAL
(C 20 REGULATION)
III DIPLOMA CME
V-SEMESTER
NAME OF THE STUDENT
ROLL.NO
YEAR
BRANCH
Name :
Roll No. :
Branch :
Year-Sem :
S.No Date Experiment Name Marks Instructor
Signature
Table of Contents
S. No Name of the Experiment Page No.
1 Task 1: Write and execute simple python program.
2 Task2: Develop minimum 2 programs using different data types
(numbers, string, tuple, list and dictionary)
3 Task 3: Develop minimum 2 programs using Arithmetic Operators
exhibiting data type conversion.
4 Task 4:
i. Write simple programs to convert U.S. dollars to Indian rupees.
ii. Write simple programs to convert bits to Megabytes, Gigabytes and
Terabytes.
5 Task 5: Write simple programs to calculate the area and perimeter of the
square and volume and perimeter of the cone.
6 Task 6: Write program to :
i. Determine wheather a given number is odd or even
ii. Find the greatest of the three numbers using conditional operators.
7 Task 7: Write a program to
i. Find the factorial of a given number
ii. Generate multiplication table up to 10 for numbers 1 to 5
8 Task 8: Write a program to
i. Find the factorial of a given number
ii. Generate multiplication table up to 10 for numbers 1 to 5
Using functions
9 Task 9: Write a program to:
i. Find factorial of a given number using recursion
ii. Generate Fibonacci sequence up to 100 using recursion
10 Task 10: Write a program to: Create a list, add element to list, delete element
from the lists.
11 Task 11: Write a program to: Sort the list, reverse the list and counting
elements in a list
12 Task 12: Write a program to: Create dictionary, add element to dictionary,
delete element from the dictionary.
13 Task 13: Write a program to: calculate average, mean, median and
standard deviation of numbers in a list.
14 Task 14: Write a program to print factors of a given number.
15 Task 15: File Input/output: Write a program to :
i. Create simple file and write “Hello World” in it.
ii. To open a file in write mode and append Hello world at the end of a file
16 Task 16: Write a program to
i. To open a file in read mode and write its contents to another file but
replace every occurrence of character ‘h’
ii. To open a file in read mode and print the number of occurrences of a
character ‘a’.
17 Task 17: Write a Program Add two complex number using classes and
objects.
18 Task 18: Write a program to Subtract two complex number using classes
and objects
19 Task 19: Write a program to Create a package and accessing a package.
EXPERIMENT - 1
Write and execute simple python program.
Aim: Write and execute simple python program
a. Printing “Hello World”
b. Addition of two numbers
Program:
a. Printing “Hello World”
# This program prints Hello, world!
print('Hello, world!')
Output:
b. Addition of two numbers
# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Input:
Output:
1
EXPERIMENT - 2
Develop minimum 2 programs using different data types (numbers, string, tuple, list and dictionary)
Aim: Develop minimum 2 programs using different data types (numbers, string, tuple, list and
dictionary)
a. Adding two numbers using user input
b. Adding two strings
Program:
a. Adding two numbers using user input
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Input:
Output:
b. Adding two strings
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Output:
2
EXPERIMENT - 3
Develop minimum 2 programs using Arithmetic Operators exhibiting data type conversion.
Aim: Develop minimum 2 programs using Arithmetic Operators exhibiting data type conversion.
a. Adding an integer to a float
b. Area Calculation with User Input (String to Float conversion)
Program:
a. Adding an integer to a float
# Define an integer and a float
integer_value = 10
float_value = 5.5
# Perform addition (integer will be converted to float)
result = integer_value + float_value
# Print the result and its type
print(f"Result: {result}, Type: {type(result)}")
Output:
b. Area Calculation with User Input (String to Float conversion)
# Get user input for length and width (strings)
length_str = input("Enter the length of the rectangle: ")
width_str = input("Enter the width of the rectangle: ")
# Convert strings to floats for calculation
length = float(length_str)
width = float(width_str)
# Calculate area (float multiplication)
area = length * width
# Print the result with a clear message
print(f"The area of the rectangle is: {area:.2f} square units")
Input:
Output:
3
EXPERIMENT - 4
i. Write simple programs to convert U.S. dollars to Indian rupees.
ii. Write simple programs to convert bits to Megabytes, Gigabytes and Terabytes
Program:
i. Convert U.S. dollars to Indian rupees
# Define the conversion rate from USD to INR
usd_to_inr_rate = 82.50 # Example conversion rate
# Input amount in USD
usd_amount = float(input("Enter amount in U.S. Dollars: "))
# Convert USD to INR
inr_amount = usd_amount * usd_to_inr_rate
# Print the result
print(f"{usd_amount} U.S. Dollars is equal to {inr_amount} Indian Rupees")
Input:
Output:
ii. Write simple programs to convert bits to Megabytes, Gigabytes and Terabytes
# Conversion factors
bits_in_megabyte = 8 * 1024 * 1024
bits_in_gigabyte = 8 * 1024 * 1024 * 1024
bits_in_terabyte = 8 * 1024 * 1024 * 1024 * 1024
# Input amount in bits
bits_amount = float(input("Enter amount in bits: "))
# Convert bits to Megabytes, Gigabytes, and Terabytes
megabytes = bits_amount / bits_in_megabyte
gigabytes = bits_amount / bits_in_gigabyte
terabytes = bits_amount / bits_in_terabyte
# Print the results
print(f"{bits_amount} bits is equal to {megabytes} Megabytes")
print(f"{bits_amount} bits is equal to {gigabytes} Gigabytes")
print(f"{bits_amount} bits is equal to {terabytes} Terabytes")
Input:
Output:
4
EXPERIMENT - 5
Write simple programs to calculate the area and perimeter of the square and volume and perimeter of the cone.
Program:
area and perimeter of the square
# Input the side length of the square
side_length = float(input("Enter the side length of the square: "))
# Calculate the area of the square
area = side_length ** 2
# Calculate the perimeter of the square
perimeter = 4 * side_length
# Print the results
print(f"Area of the square: {area}")
print(f"Perimeter of the square: {perimeter}")
Input:
Output:
volume and perimeter of the cone.
import math
# Input the radius and height of the cone
radius = float(input("Enter the radius of the cone: "))
height = float(input("Enter the height of the cone: "))
# Calculate the volume of the cone
volume = (1/3) * math.pi * radius ** 2 * height
# Calculate the slant height of the cone
slant_height = math.sqrt(radius ** 2 + height ** 2)
# Calculate the surface area of the cone
surface_area = math.pi * radius * (radius + slant_height)
# Print the results
print(f"Volume of the cone: {volume}")
print(f"Surface area of the cone: {surface_area}")
Input:
Output:
5
EXPERIMENT - 6
Write program to:
i. Determine whether a given number is odd or even
ii. Find the greatest of the three numbers using conditional operators.
Program:
Determine whether a given number is odd or even
# Input the number
number = int(input("Enter a number: "))
# Determine if the number is even or odd
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
Input:
Output:
Find the greatest of the three numbers using conditional operators
# Input three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# Determine the greatest number using conditional operators
greatest = num1 if (num1 > num2 and num1 > num3) else (num2 if num2 > num3 else num3)
# Print the result
print(f"The greatest number is: {greatest}")
Input:
Output:
6
EXPERIMENT - 7
Write a program to
i. Find the factorial of a given number
ii. Generate multiplication table up to 10 for numbers 1 to 5
Program:
Find the factorial of a given number
# Input the number
number = int(input("Enter a number: "))
# Initialize the factorial result
factorial = 1
# Calculate the factorial using a for loop
if number < 0:
print("Factorial is not defined for negative numbers.")
elif number == 0:
print(f"The factorial of 0 is 1.")
else:
for i in range(1, number + 1):
factorial *= i
print(f"The factorial of {number} is {factorial}.")
Input:
Output:
Generate multiplication table up to 10 for numbers 1 to 5
# Generate multiplication table for numbers 1 to 5
for num in range(1, 6):
print(f"Multiplication Table for {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
print("\n")
Output:
7
8
EXPERIMENT - 8
Write a program to
i. Find the factorial of a given number
ii. Generate multiplication table up to 10 for numbers 1 to 5
Using functions
Program:
Find the factorial of a given number
# Function to calculate the factorial
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
# Input the number
number = int(input("Enter a number: "))
# Calculate the factorial using the function
print(factorial(number))
Input:
Output:
Generate multiplication table up to 10 for numbers 1 to 5
def multiplication_table():
for i in range(1, 6): # Numbers from 1 to 5
print(f"Multiplication Table for {i}:")
for j in range(1, 11): # Multiplication up to 10
result = i * j
print(f"{i} * {j} = {result}")
print() # Adding a newline after each table
# Calling the function to generate tables
multiplication_table()
9
Output:
10
EXPERIMENT - 9
Write a program to:
i. Find factorial of a given number using recursion
ii. Generate Fibonacci sequence up to 100 using recursion
Program:
Find factorial of a given number using recursion
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: factorial of n is n times factorial of (n-1)
return n * factorial(n - 1)
num = int(input(“Enter a number to find factorial:”))
print(f"The factorial of {num} is: {factorial(num)}")
Input:
Output:
Generate Fibonacci sequence up to 100 using recursion
def fibonacci(n):
if n <= 1:
return n # Base case: Fibonacci of 0 is 0, Fibonacci of 1 is 1
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive case: Fibonacci of n is Fibonacci of (n-1) +
Fibonacci of (n-2)
# Generating Fibonacci sequence up to 100
max_value = 100
print("Fibonacci sequence up to 100:")
n=0
while fibonacci(n) <= max_value:
print(fibonacci(n))
n += 1
Input:
Output:
11
EXPERIMENT - 10
Write a program to: Create a list, add element to list, delete element from the lists.
Program:
# Creating an empty list
my_list = []
# Adding elements to the list
my_list.append(1)
my_list.append(2)
my_list.append(3)
print("List after adding elements:", my_list)
# Deleting elements from the list
my_list.remove(2) # Removing element '2'
print("List after deleting an element:", my_list)
# Another way to delete an element using index
del my_list[0] # Removing the first element (index 0)
print("List after deleting an element by index:", my_list)
Output:
12
EXPERIMENT - 11
Write a program to: Sort the list, reverse the list and counting elements in a list
Program:
# Creating a list with some elements
my_list = [5, 3, 8, 1, 2]
# Sorting the list
my_list.sort()
print("Sorted list:", my_list)
# Reversing the list
my_list.reverse()
print("Reversed list:", my_list)
# Counting the number of elements in the list
count = len(my_list)
print("Number of elements in the list:", count)
Output:
13
EXPERIMENT - 12
Write a program to: Create dictionary, add element to dictionary, delete element from the dictionary
Program:
# Creating an empty dictionary
my_dict = {}
# Adding elements to the dictionary
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
my_dict['key3'] = 'value3'
print("Dictionary after adding elements:", my_dict)
# Deleting an element from the dictionary by key
del my_dict['key2']
print("Dictionary after deleting an element:", my_dict)
Output:
14
EXPERIMENT - 13
Write a program to: calculate average, mean, median and standard deviation of numbers in a list.
Program:
import math
# Creating a list of numbers
numbers = [10, 20, 30, 40, 50]
# Calculating average (mean)
average = sum(numbers) / len(numbers)
print("Average (Mean):", average)
# Calculating median
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
if n % 2 == 0:
median = (sorted_numbers[n // 2 - 1] + sorted_numbers[n // 2]) / 2
else:
median = sorted_numbers[n // 2]
print("Median:", median)
# Calculating standard deviation
mean = average
variance = sum((x - mean) ** 2 for x in numbers) / (len(numbers) - 1)
std_deviation = math.sqrt(variance)
print("Standard Deviation:", std_deviation)
Output:
15
EXPERIMENT - 14
Write a program to print factors of a given number.
Program:
# Function to print factors of a given number
def print_factors(number):
print(f"Factors of {number} are:")
for i in range(1, number + 1):
if number % i == 0:
print(i)
num = int(input("Enter a number: "))
print_factors(num)
Input:
Output:
16
EXPERIMENT - 15
File Input/output: Write a program to :
i. Create simple file and write “Hello World” in it.
ii. To open a file in write mode and append Hello world at the end of a file
Programs:
i. Create simple file and write “Hello World” in it.
# Define the filename
filename = "hello_world.txt"
# Open the file in write mode and write "Hello World" to it
with open(filename, "w") as file:
file.write("Hello World")
print(f"Successfully written 'Hello World' to {filename}")
Output:
ii. To open a file in write mode and append Hello world at the end of a file
# Define the filename
filename = "hello_world.txt"
# Open the file in append mode and write "Hello World" to it
with open(filename, "a") as file:
file.write("\nHello World")
print(f"Successfully appended 'Hello World' to {filename}")
Output:
17
EXPERIMENT - 16
Write a program to
i. To open a file in read mode and write its contents to another file but replace every occurrence of
character ‘h’
ii. To open a file in read mode and print the number of occurrences of a character ‘a’.
Programs:
i. To open a file in read mode and write its contents to another file but replace every
occurrence of character ‘h’
# Define the input and output filenames
input_filename = "input_file.txt"
output_filename = "output_file.txt"
# Open the input file in read mode
with open(input_filename, "r") as input_file:
# Read the contents of the file
content = input_file.read()
# Replace every occurrence of 'h' with 'x'
modified_content = content.replace('h', 'x')
# Open the output file in write mode and write the modified content to it
with open(output_filename, "w") as output_file:
output_file.write(modified_content)
print(f"Successfully written modified content to {output_filename}")
Output:
18
ii. To open a file in read mode and print the number of occurrences of a character ‘a’.
# Define the filename
filename = "sample.txt"
# Character to count occurrences of
char_to_count = 'a'
# Initialize a counter
count = 0
# Open the file in read mode
with open(filename, "r") as file:
# Read the contents of the file
content = file.read()
# Count the occurrences of the character
count = content.count(char_to_count)
print(f"Number of occurrences of '{char_to_count}' in {filename}: {count}")
Output:
19
EXPERIMENT - 17
Write a Program Add two complex number using classes and objects
Program:
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
# Adding real parts and imaginary parts separately
new_real = self.real + other.real
new_imaginary = self.imaginary + other.imaginary
return ComplexNumber(new_real, new_imaginary)
def __str__(self):
# String representation of the complex number
if self.imaginary >= 0:
return f"{self.real} + {self.imaginary}i"
else:
return f"{self.real} - {-self.imaginary}i"
# Creating complex numbers
complex1 = ComplexNumber(2, 3)
complex2 = ComplexNumber(4, -1)
# Adding two complex numbers
result = complex1 + complex2
# Printing the result
print("Sum of complex numbers:", result)
Output:
20
EXPERIMENT - 18
Write a program to Subtract two complex number using classes and objects
Program:
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __sub__(self, other):
# Subtracting real parts and imaginary parts separately
new_real = self.real - other.real
new_imaginary = self.imaginary - other.imaginary
return ComplexNumber(new_real, new_imaginary)
def __str__(self):
# String representation of the complex number
if self.imaginary >= 0:
return f"{self.real} + {self.imaginary}i"
else:
return f"{self.real} - {-self.imaginary}i"
# Creating complex numbers
complex1 = ComplexNumber(5, 3)
complex2 = ComplexNumber(2, 1)
# Subtracting two complex numbers
result = complex1 - complex2
# Printing the result
print("Difference of complex numbers:", result)
Output:
21
EXPERIMENT - 19
Write a program to Create a package and accessing a package.
Program:
Directory structure
mypackage/
├── __init__.py
├── module1.py
├── module2.py
└── main.py
Contents of module1.py
def greet():
print("Hello from module1!")
Contents of module2.py
def calculate_square(num):
return num ** 2
Contents of main.py
from mypackage.module1 import greet
from mypackage.module2 import calculate_square
def main():
greet() # Output: Hello from module1!
result = calculate_square(5)
print("Square of 5 is:", result) # Output: Square of 5 is: 25
if __name__ == "__main__":
main()
Output:
22