PYTHON PROGAMMING LAB
After Successful installation of Python – Open the IDLE Shell 3.10.4
Go to – ‘File’ and click on ‘New File’
‘Save’ the ‘New File’ on desktop with Your Short Name and 2 digits of roll no
Ex:- ravi23
Go to – ‘Options’ in your [Link] file and click on ‘Show Line Numbers’
Exercise-1: Python Interpreter as Calculator
1 2+2
2 50 - 5*6
3 (50 - 5*6) / 4
4 8 / 5 # division always returns a floating-point number
5 17 % 3 # the % operator returns the remainder of the division
6 5 ** 2 # 5 squared
7 2 ** 7 # 2 to the power of 7
8 width = 20
height = 5 * 9
width * height
9 tax = 12.5 / 100
price = 100.50
price * tax
Exercise-2: print() statement, type statement, variables and data types
1 # Print your name and a Statement using print().
print("My name is_____ ")
print("I Love Python Programming")
2 # Assign your name to a variable and print it.
name = "Your Name"
print("My name is", name)
print(type(name))
3 # Change the value of a variable and print before and after.
x=5
print("Before:", x)
print(type(x))
x = 10
print("After:", x)
4 # Create variables of different types and print them
integer_num = 42
float_num = 3.14
string_text = "Python"
boolean_val = True
Page 1 of 2
print(integer_num)
print(float_num)
print(string_text),
print(boolean_val)
5 # Check the type of each variable using type()
print(type(integer_num))
print(type(float_num))
print(type(string_text))
print(type(boolean_val))
6 # Convert between data types.
num_str = "100"
num_int = int(num_str)
print("String:", num_str, "Integer:", num_int)
Page 2 of 2
Week-2
[Link] a program to calculate compound interest when principal, rate and
number of periods are given.
Compound Interest Formula
As we have already discussed, the compound interest is the interest-based on
the initial principal amount and the interest collected over the period of
time. The compound interest formula is given below:
Compound Interest earned = Amount – Principal
Here, the amount is given by:
Where,
• A = amount
• P = principal
• r = rate of interest
• n = number of times interest is compounded per year
• t = time (in years)
Alternatively, we can write the formula as given below:
CI = A – P
# Python program to compute compound interest
p = int(input(" Enter the principal amount : "))
n = float(input(" Enter the time in years : " ))
r = float(input(" Enter the rate of interest : "))
# compute compound interest
# Using pow() for exponentiation
amount = p * (pow((1 + r / 100), n))
ci = amount - p
# print
print(" Compound Interest : " , ci)
print(" Compound Interest : " , f"{ci:.2f}")
1) Given coordinates (x1, y1), (x2, y2) find the distance between two points
import math ?
# Input coordinates
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
# Distance calculation
distance = [Link]((x2 - x1)**2 + (y2 - y1)**2)
# Output
print("Distance between the two points is:", distance)
Enter x1: 2
Enter y1: 3
Enter x2: 5
Enter y2: 7
Distance between the two points is: 5.0
2) Read the name, address, email and phone number of a person through the
keyboard and print the details. (input output)
Solution:
Name = input("Enter Person Name : ")
Address = input("Enter Person Address : ")
Email = input("Enter Person Email : ")
Phone_no = input("Enter Phone number : ")
print(" Please Confirm your provided Information\n " )
print(" Person Name : " ,Name )
print(" Person Address : " , Address )
print(" Person Email : " , Email )
print(" Person Phone_no : " , Phone_no )
OUTPUT:
Enter Person Name: Madhu
Enter Person Address : HYDERABAD
Enter Person Email : madhu@[Link]
Enter Person Phone_no : 9656123456
Please Confirm your provided Information
Person Name : Madhu
Person Address : HYDERABAD
Person Email : madhu@[Link]
Person Phone_no : 9656123456
Week-2
# [Link] a python program weather he/she is eligible to cast a vote based on the
age ?
======================================================
age = float(input("What is your age?: "))
if age >= 18:
print("Congrats! you are an adult. You can now cast vote!!!!")
print("Rest of the program")
2.# Print if a number (int) is odd or even
# even - when the number is divisible by 2. remainder is 0
# odd - the number is NOT divisible by 2. remainder is not 0
===============================================
num = int(input("Enter an integer: "))
if num % 2 == 0:
print("The number is even")
else:
print("The number is odd")
3.# if-elif-else
'''
>= 90 , grade A
80 and 89 , grade B
70 and 79 , grade C
60 and 69 , grade D
< 60, grade F
'''
Sol:
marks = float(input("Enter your marks: "))
if marks >= 90:
print("Grade is A")
elif marks >= 80 and marks < 90:
print("Grade is B")
elif marks >= 70 and marks < 80:
print("Grade is C")
elif marks >= 60 and marks < 70:
print("Grade is D")
else:
print("Grade is F")
Week-3: Python Programming Lab
1) Write a program that accepts a string from user and redisplays the same
string after removing vowels from it?
2) Python program to print all prime numbers in a given interval (use break)
3) Print the below triangle using for loop.
5
44
333
2222
11111
4). Write a program to change a given string to a new string where the first and
last characters have been exchanged.
5). Write a program to check whether the entered string is palindrome or not.
[Link] a function called remove duplicates that takes a list and returns a new
list with only the unique elements from the original. \
Hint: they don ‘t have to be in the same order.
def remove_duplicates(original_list):
# Converting to a set removes duplicates automatically
unique_set = set(original_list)
# Convert back to a list and return
return list(unique_set)
# Example usage:
my_list = [1, 2, 2, 3, 4, 4, 5, "apple", "apple"]
print(remove_duplicates(my_list))
# Output might be: [1, 2, 3, 4, 5, 'apple'] (order may vary)
[Link] a python Program to add a comma between the characters. If the given
word is 'Apple', it should become 'A,p,p,l,e'
def add_commas(word):
# The join method takes every character in 'word'
# and places a comma between them.
return ",”. join(word)
# Example usage:
input_word = "Apple"
result = add_commas(input_word)
print(result)
# Output: A,p,p,l,e
3. Write a python code to read dictionary values from the user. Construct a function to
invert its content. i.e., keys should be values and values should be keys
# 1. Read a dictionary string like {"a": 1, "b": 2} from user
data = eval(input("Enter dictionary: "))
# 2. Invert it using a comprehension
inverted = {v: k for k, v in [Link]()}
# 3. Print the result
print(inverted)
OUTPUT
Enter dictionary (e.g., {"a": 1, "b": 2}): {"m":5}
{5: 'm'}
[Link] Program to Print the Fibonacci sequence using recursive function
def fibonacci_recursive(n):
"""Function to return the nth Fibonacci number."""
if n <= 1:
return n
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# Get the number of terms from the user
terms = int(input ("How many terms? "))
# Check if the number of terms is valid
if terms <= 0:
print ("Please enter a positive integer.")
else:
print ("Fibonacci sequence:")
for i in range(terms):
print(fibonacci_recursive(i))
output How many terms? 6
Fibonacci sequence:
0
1
1
2
3
5
[Link] Python Program by using a lambda function to add and subtract two
variables
# 1. Define the lambda functions
add = lambda x, y: x + y
subtract = lambda x, y: x - y
# 2. Get input from the user
num1 = float(input("Enter first number: "))
num2 = float(input ("Enter second number: "))
# 3. Call the lambdas and display results
print(f"\nAddition Result: {add(num1, num2)}")
print(f"Subtraction Result: {subtract(num1, num2)}")
OUTPUT:
Enter first number: 5
Enter second number: 6
Addition Result: 11.0
Subtraction Result: -1.0
Week-6&7
[Link] a Python program to Define a function ‘get_BiggerNumber (x,y)’
to take in two numbers and just ‘print’ the bigger of them. Take the
arguments as (100,200)
# function to get the bigger number amongst Two
def get_BiggerNumber(x,y): # defining the function with parameters
if (x>y):
print(“Bigger no. is:”, x)
else:
print(“Bigger no. is:”, y)
get_BiggerNumber(100,20) # call the function with arguments
2. Write a script that asks users for the temperature in F and prints the
temperature in C. (Conversion: Celsius = (F - 32) * 5/9).
# function to convert celsius to Fahrenheit- return statement
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
#call function
temp_f = celsius_to_fahrenheit(25)
print(temp_f)
print("with return: ", type(temp_f))
3. Write a Python code to merge two given file contents into a third file.
# Opening first file in read mode
file1 = open('[Link]', 'r')
data1 = [Link]()
[Link]()
# Opening second file in read mode
file2 = open('[Link]', 'r')
data2 = [Link]()
[Link]()
# Opening third file in write mode
file3 = open('[Link]', 'w')
# Writing contents of both files into third file
[Link](data1)
[Link]("\n") # optional: adds a line gap between contents
[Link](data2)
[Link]()
print("Contents of file1 and file2 merged successfully into file3.")
4. Write a Python code to open a given file and construct a function to
check for given words present in it and display on found.
# Function to check whether a word is present in the file
def check_word(filename, word):
file = open(filename, 'r')
content = [Link]()
[Link]()
if word in content:
print("The word", word, "is FOUND in the file.")
else:
print("The word", word, "is NOT FOUND in the file.")
# Main program
filename = "[Link]"
search_word = input("Enter the word to search: ")
check_word(filename, search_word)
5. Write a python program to read and write the details of 3 students in a
file ‘[Link]’. Place details of Name, Gender, Age, Place in the file
Append the following details to the ‘[Link]’ file: Amar,
Male,19, Hyderabad
Print the details after appending
# 1. Creating and writing initial data
file = open('[Link]', 'w')
# Adding header
[Link]("Name,Gender,Age,Place\n")
# Writing 3 student records
[Link]("Anita,Female,20,Mumbai\n")
[Link]("Rahul,Male,21,Bangalore\n")
[Link]("Sana,Female,19,Chennai\n")
[Link]()
print("Initial file created successfully.")
# 2. Appending new student details
new_student = "Amar,Male,19,Hyderabad"
file = open('[Link]', 'a')
[Link](new_student + "\n")
[Link]()
print("Details of Amar appended successfully.\n")
# 3. Reading and printing the file contents
print("--- Contents of [Link] ---")
file = open('[Link]', 'r')
content = [Link]()
print(content)
[Link]()