Department of Artificial Intelligence and Machine Learning
INTRODUCTION TO PYTHON PROGRAMMING
LABORATORY PROGRAMS
Prepared By
Manasa M
Sonika C T
Harshitha V
Nitya Shree G D
Vanishree K
Divya T L
Prashanth K
Practice Programs
Write a Python Program to Print Hello world.
print ('Hello, World!')
1. Write a Python Program to add 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))
2. Write a Python Program to add Two Numbers
# 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))
3. Write a Python Program to find the Area of the Circle
import math
radius = input(“Enter the Radius of the Circle: ”)
area = [Link]* pow(float(radius), 2)
print ("Area is %.6f" % area);
4. Write a Python Program to Swap two Numbers
x = int(input("Enter the Value for X: "))
y = int(input("Enter the Value for Y: "))
# Swapping Technique
temp = y
y=x
x = temp
print("X and Y Values after Swapping \n")
print("x = ", x)
print("y = ", y)
5. Write a Program to Swap Two Variable without Using ‘temp Variable’
x = int(input("Enter the Value for X: "))
y = int(input("Enter the Value for Y: "))
x, y = y, x
print("x =", x)
print("y =", y)
6. Write a Python Program to find the ASCII Value of a Given Character
Character = input('Enter a Character: ')
print("The ASCII value of '" + Character + "' is",ord(Character))
7. Write a Python Program to Print a Character from their corresponding ASCII values
ASCII_VALUE = int(input(“Enter the ASCII VALUE: ”))
print("The Character Associated with the ASCII Value '"+str(ASCII_VALUE)+"' is",
chr(ASCII_VALUE))
8. Write a Python Program to remove a word from a String.
print("Enter the String: ")
text = input()
print("Enter a Word to Delete: ")
word = input()
text = [Link](word, "")
print()
print(text)
9. Write a Python Program to illustrate the Set Operations
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# Union Operation
print ("Union of E and N is",E | N)
# Intersection Operation
print("Intersection of E and N is",E & N)
# SET Difference
print("Difference of E and N is",E - N)
# Symmetric SET Difference
print("Symmetric difference of E and N is",E^N)
[Link] a Python Program to print the calendar of the given Month and Year
import calendar
YEAR = int(input("Enter the Year: ")) # year
MONTH = int(input("Enter the Month: ")) # month
# Display the Calendar
print([Link](YEAR, MONTH))
Laboratory Exercise
SL. No Program
1 Write a program to determine if a given number is a perfect number.
2 Write a program to calculate the Body Mass Index (BMI Calculator) and categorize BMI
results into different health categories (underweight, normal weight, overweight,
obesity).
3 Simulate a robotic arm transformation using matrix multiplication. Multiply a matrix of
joint positions(coordinates) with a transformation matrix and print the new coordinates.
4 Read a paragraph from the user and count the number of words, the frequency of words
appearing, and search for a specific word.
5 Take a sequence of numbers that has some missing entries. Write a Python program to
fill in those missing values, remove certain numbers from the sequence, and add
additional values to enhance the existing sequence.
6 Create a Simple Banking System using dictionaries and perform deposit, withdrawal,
and checking balance operations.
7 Write a program using sets to find the common words present in a list of sentences.
8 Given a list of students' records as tuples, sort the list by marks, and find the topper.
9 Create a text file called my_file.txt with some content, capitalize the first letter of every
word, and print the content of the file in reverse order.
Laboratory Exercise
SL. No Program
1 Write a program to determine if a given number is a perfect number.
num = int(input("Enter a number: "))
if num <= 1:
print(f"{num} is not a Perfect Number")
else:
divisor_sum = 1 # 1 is always a proper divisor
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
divisor_sum += i
if i != num // i: # Avoid adding square root twice
divisor_sum += num // i
if divisor_sum == num:
print(f"{num} is a Perfect Number")
else:
print(f"{num} is not a Perfect Number")
2 Write a program to calculate the Body Mass Index (BMI Calculator) and
categorize BMI results into different health categories (underweight, normal
weight, overweight, obesity).
weight = float(input("Enter your weight in kg: "))
height = float(input("Enter your height in meters: "))
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "Underweight"
elif bmi < 24.9:
category = "Normal weight"
elif bmi < 29.9:
category = "Overweight"
else:
category = "Obesity"
print(f"\nYour BMI is: {bmi:.2f}")
print(f"Category: {category}")
3 Simulate a robotic arm transformation using matrix multiplication. Multiply a
matrix of joint positions(coordinates) with a transformation matrix and print the
new coordinates.
# Function for matrix multiplication
def multiply_matrices(A, B):
result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
for i in range(len(A)): # rows of A
for j in range(len(B[0])): # columns of B
for k in range(len(B)): # columns of A / rows of B
result[i][j] += A[i][k] * B[k][j]
return result
# Define joint positions (homogeneous coordinates: [x, y, z, 1])
joints = [
[0, 0, 0, 1], # Base
[2, 0, 0, 1], # Joint 1
[4, 1, 0, 1], # Joint 2
[6, 1, 0, 1] # End-effector
]
print("Original Joint Coordinates:")
for row in joints:
print(row)
# Transformation matrix: rotate 90° around Z-axis + translate (1, 2, 0)
theta = 90 * 3.14159 / 180 # Convert degrees to radians
cos_t = round((3.14159/2 - (3.14159/2 - 0)), 5) # Approx cos(90°) = 0
cos_t = 0
sin_t = 1
transformation_matrix = [
[cos_t, -sin_t, 0, 1],
[sin_t, cos_t, 0, 2],
[0, 0, 1, 0],
[0, 0, 0, 1]
]
print("\nTransformation Matrix:")
for row in transformation_matrix:
print(row)
# Apply transformation: Joints × Transformation^T
# (We’ll transpose transformation_matrix for correct multiplication)
transposed_T = [[transformation_matrix[j][i] for j in range(4)] for i in range(4)]
new_joints = multiply_matrices(joints, transposed_T)
print("\nNew Joint Coordinates after Transformation:")
for row in new_joints:
print(row)
4 Read a paragraph from the user and count the number of words, the frequency
of words appearing, and search for a specific word.
# Store a paragraph in a string variable
str = "'New Delhi is the Capital of India.
Bangalore is the capital of Karnataka.
India is the world's largest Democratic country'"
# Print the entered paragraph
print("Entered Paragraph\n" + str)
# Split the paragraph into words and count the total number of words
wordCount = len([Link]())
print("Total Number of words:", wordCount)
# Create an empty dictionary to store word frequency counts
counts = dict()
# Split the string into a list of words
words = [Link]()
# Loop through each word in the list
for word in words:
if word in counts:
# If the word already exists in dictionary, increase its count by 1
counts[word] = counts[word] + 1
else:
# Otherwise, add the word to dictionary with initial count 1
counts[word] = 1
# Print each word and its frequency
for key in list([Link]()):
print(key, ":", counts[key])
# Ask the user to enter a word to search in the paragraph
searchWord = input("\n Enter the word to search: ")
# Use find() method to check if the word exists in the paragraph
result = [Link](searchWord)
if(result != -1):
# If found, print success message
print(searchWord + " Word found in Paragraph")
else:
# If not found, print failure message
print(searchWord + " !!!!!! Word not found in Paragraph")
5 Take a sequence of numbers that has some missing entries. Write a Python
program to fill in those missing values, remove certain numbers from the
sequence, and add additional values to enhance the existing sequence.
# Create a sequence with some missing values
sequence = [1, None, 3, 4, None, 6, 7, 8, None, 10]
print("Original Sequence:", sequence)
# Fill in missing values
#Replace None with 0
filled_sequence = []
for num in sequence:
if num is None: # if the value is missing
filled_sequence.append(0) # replace with 0
else:
filled_sequence.append(num) # keep the original value
print("After Filling Missing Values:", filled_sequence)
# Remove certain numbers from the sequence
# Let’s say we want to remove 4 and 7
numbers_to_remove = [4, 7]
cleaned_sequence = []
for num in filled_sequence:
if num not in numbers_to_remove:
cleaned_sequence.append(num)
print("After Removing Certain Numbers:", cleaned_sequence)
# Add additional values to enhance the sequence
# Let’s add [99, 100, 101] at the end
extra_values = [99, 100, 101]
enhanced_sequence = cleaned_sequence + extra_values
print("Final Enhanced Sequence:", enhanced_sequence)
6 Create a Simple Banking System using dictionaries and perform deposit, withdrawal,
and checking balance operations.
# Banking system using dictionary
bank = {"account_number": 12345, "name": "John Doe", "balance": 1000}
print("Welcome to Simple Bank System")
print("Account Holder:", bank["name"])
print("Account Number:", bank["account_number"])
print("Current Balance:", bank["balance"])
while True:
print("\nChoose an option:")
print("1. Deposit")
print("2. Withdraw")
print("3. Check Balance")
print("4. Exit")
choice = input("Enter choice (1-4): ")
if choice == "1":
amount = int(input("Enter deposit amount: "))
bank["balance"] += amount
print("Deposit successful! Updated Balance:", bank["balance"])
elif choice == "2":
amount = int(input("Enter withdrawal amount: "))
if amount <= bank["balance"]:
bank["balance"] -= amount
print("Withdrawal successful! Updated Balance:", bank["balance"])
else:
print("Insufficient balance!")
elif choice == "3":
print("Current Balance:", bank["balance"])
elif choice == "4":
print("Thank you for banking with us!")
break
else:
print("Invalid choice, please try again.")
7 Write a program using sets to find the common words present in a list of
sentences.
# Define the list of sentences
sentences = [
"New Delhi is the capital of India",
"Bangalore is the capital of Karnataka",
"Hyderabad is the capital of Telangana"
]
print("Given Sentences:")
for s in sentences:
print("-", s)
# Convert each sentence into a set of words
# We use lower() so that words like "India" and "india" are treated as the same
word_sets = []
for sentence in sentences:
words = set([Link]().split()) # split into words and convert into a set
word_sets.append(words)
# Display each set of words
print("\nWords in each sentence (as sets):")
for i, ws in enumerate(word_sets, start=1):
print(f"Sentence {i}:", ws)
# Find the common words among all sentences
# Using [Link] to find words that exist in every set
common_words = [Link](*word_sets)
# Display the result
print("\nCommon words present in all sentences are:", common_words)
8 Given a list of students' records as tuples, sort the list by marks, and find the
topper.
# List of students' records as tuples (Name, Marks)
students = [
("Ravi", 78),
("Sneha", 85),
("Arjun", 92),
("Meena", 88),
("Kiran", 95)
]
# Sort the list by marks in descending order
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
# Display the sorted list
print("Students sorted by marks:")
for name, marks in sorted_students:
print(name, ":", marks)
# Topper will be the first student in the sorted list
topper = sorted_students[0]
print("\nTopper is:", topper[0], "with", topper[1], "marks")
9 Create a text file called my_file.txt with some content, capitalize the first letter of
every word, and print the content of the file in reverse order.
def write():
String = input('Enter the paragraph: ')
file =
open('D:\\NS\\College\\Department\\CourcesHandled\\PythonProgramming\\LabPro
grams\\my_file.txt', 'w')
[Link](String)
[Link]()
def read():
with
open('D:\\NS\\College\\Department\\CourcesHandled\\PythonProgramming\\LabPro
grams\\my_file.txt') as file:
data = [Link]()
[Link]()
print('--------------------------------')
print('Original Content')
print('--------------------------------')
print(data)
print('--------------------------------')
print('Modified Content')
print('--------------------------------')
print([Link]())
print('--------------------------------')
write()
read()