PYTHON PROGRAMMING
Practical No: 1
Aim: Install and set up the Python IDLE interpreter. Executing simple statements like expression
statements (numeric and Boolean types), assert, assignment, delete statements, and the print function
for output.
1. Rectangle: Area and Perimeter.
# Assigning dimensions of the rectangle
length = 15
width = 8
# Calculating area and perimeter
area = length * width
perimeter = 2 * (length + width)
# Printing the results
print("Length of the rectangle:", length)
print("Width of the rectangle:", width)
print("Area of the rectangle:", area)
print("Perimeter of the rectangle:", perimeter)
# Deleting variables
del length, width
# Uncommenting the next line will cause an error as variables are deleted
# print(length)
2. Temperature Conversion Celsius to Fahrenheit.
# Assigning a temperature in Celsius
temperature_celsius = 25
# Converting to Fahrenheit
temperature_fahrenheit = (temperature_celsius * 9/5) + 32
# Printing the results
print("Temperature in Celsius:", temperature_celsius)
print("Temperature in Fahrenheit:", temperature_fahrenheit)
# Deleting variables
del temperature_celsius, temperature_fahrenheit
3. Circle: Area and Circumference.
# User input for the radius
radius = float(input("Enter the radius of the circle: "))
# Calculating area and circumference
pi = 3.14159
area = pi * radius * radius
circumference = 2 * pi * radius
# Printing the results
print("\nRadius of the circle:", radius)
print("Area of the circle:", area)
print("Circumference of the circle:", circumference)
# Deleting variables
del radius, area, circumference
# Uncommenting the next line will cause an error as variables are deleted
# print(radius)
4. Boolean Expression: Checks if age is 18 or more
# Assigning values
age = 20
is_adult = age >= 18
# Printing the result
print("Age:", age)
print("Is the person an adult?", is_adult)
# Deleting variables
del age, is_adult
Practical No: 2
Aim: Programs based on lists, conditional constructs, the for statement, and the range function,
interactively using the built-in functions: len, sum, max, min, and string manipulation.
Example: Conditional Statements.
[Link] Largest Number of 3 numbers and 2 numbers
n1=float(input("Enter value of n1:"))
n2=float(input("Enter value of n2:"))
if n1>n2:
print("n1 is Largest.")
else:
print("n2 is Largest.")
n1=float(input("Enter value of n1:"))
n2=float(input("Enter value of n2:"))
n3=float(input("Enter value of n3:"))
if n1>n2 and n1>n3:
print("n1 is Largest.")
elif n2>n1 and n2>n3:
print("n2 is Largest.")
else:
print("n3 is Largest.")
[Link] the grade based on Marks
n=int(input("Enter Marks out of 100:"))
if n>=75:
print("Grade A.")
elif n>=60:
print("Grade B.")
elif n>=35:
print("Grade C.")
else:
print("Fail.")
3. For Loop
(a) Find the Factorial of the number
n = int(input("Enter a number:"))
f=1
for i in range(1, n+1):
f *= i
print("The factorial is:",f)
(b) sum of natural nos
n=int(input("Enter a number:"))
i=1
product = 0
for i in range(1,n+1):
product+=i
print("sum of natural nos:",product)
4. List with using built in functions
# Define a list of numbers
numbers = [10, 25, 7, 56, 32, 18, 5]
# Calculate the maximum, minimum, length, and sum
maximum = max(numbers)
minimum = min(numbers)
length = len(numbers)
total_sum = sum(numbers)
# Print the results
print("List of numbers:", numbers)
print("Maximum value:", maximum)
print("Minimum value:", minimum)
print("Number of elements:", length)
print("Sum of all elements:", total_sum)
# Additional: Calculate the average for context
average = total_sum / length
print("Average value:", average)
5. Write a program to count vowels and consonants in a string.
v=["A","E","I","O","U","a","e","i","o","u"]
count=0
con=0
b=input("Enter your name:")
for i in b:
if i in v:
count+=1
else:
con+=1
print("vowel:",count)
print("consonants:",con)
6. String Manipulation with Various Operation
# Convert to uppercase and lowercase
text = " Python Programming is FUN! "
uppercase_text = [Link]()
lowercase_text = [Link]()
print("Uppercase:", uppercase_text)
print("Lowercase:", lowercase_text)
# Remove leading and trailing whitespaces
stripped_text = [Link]()
print("Stripped Text:", stripped_text)
# Replace a substring
replaced_text = [Link]("FUN", "amazing")
print("Replaced Text:", replaced_text)
# Split the string into a list of words
words = [Link]()
print("Words:", words)
# Join a list of strings into a single string
joined_text = " ".join(words)
print("Joined Text:", joined_text)
# Check if a substring exists
contains_python = "Python" in text
print("Contains 'Python':", contains_python)
# Reverse the string
reversed_text = text[::-1]
print("Reversed Text:", reversed_text)
# Slice the string
sliced_text = text[2:12] # Get characters from index 2 to 11
print("Sliced Text:", sliced_text)
# Format a string dynamically
name = "Alice"
age = 25
formatted_text = f"My name is {name} and I am {age} years old."
print("Formatted Text:", formatted_text)
Practical No-3
Program based on while statement, importing and exceuting built-in functions from the time,math and random
modules,break and continue
Sum of Natural numbers
# n=int(input("Enter the number:"))
# i=1
# product=1
# while i<=n:
# product+=i
# i+=1
# print("sum of Natural ",n,"is",product)
Print series of natural nos with user input initial and final range
# i=int(input("Enter initial number:"))
# num=int(input("Enter final number:"))
# while i<=num:
# print(i)
# i+=1
# print("Exit")
Print fibonacci seq upto 10th term
i=0
a,b=0,1
num=10
print("fibonacci series:")
while i<num:
print(a,end=" ")
c=a+b
a=b
b=c
i+=1
Math module
import math
# Find the square root of a number
num = 16
print(f"Square root of {num} is {[Link](num)}")
# Calculate the sine of 90 degrees (convert to radians first)
angle = 90
print(f"Sine of {angle} degrees is {[Link]([Link](angle))}")
# Calculate factorial of a number
number = 5
print(f"Factorial of {number} is {[Link](number)}")
Random Module
import random
# Generate a random integer between 1 and 10
print("Random integer between 1 and 10:", [Link](1, 10))
# Generate a random float between 0 and 1
print("Random float between 0 and 1:", [Link]())
# Choose a random element from a list
colors = ["red", "blue", "green", "yellow"]
print("Randomly chosen color:", [Link](colors))
# Shuffle a list
numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print("Shuffled list:", numbers)
Time Module
import time
# Start the timer
start_time = [Link]()
# Perform a task (example: calculate sum of numbers from 1 to 1,000,000)
total = sum(range(1, 10000000001))
# End the timer
end_time = [Link]()
print(f"Total: {total}")
print(f"Time taken: {end_time - start_time:.2f} seconds")
Using Break
[Link] the loop once "banana" is found
fruits = ["apple", "orange", "banana", "cherry", "mango"]
for fruit in fruits:
if fruit == "banana":
print(f"Found {fruit}! Breaking the loop.")
break
print(f"Checked: {fruit}")
Q. Break the outer loop when a specific combination is found
for x in range(1, 4):
for y in range(1, 4):
if x == 2 and y == 2:
print(f"Breaking at x={x}, y={y}")
break
print(f"x={x}, y={y}")
if x == 2 and y == 2:
break
Using Continue
Q. Skip vowels in a string
text = "Python Programming"
for char in text:
if [Link]() in "aeiou":
continue
print(char, end="")
Q. Skip pairs where x equals y
for x in range(1, 4):
for y in range(1, 4):
if x == y:
continue
print(f"x={x}, y={y}")
Q. Using both Break & Continue create a number guessing game
while True:
guess = int(input("Guess the number (between 1 and 10): "))
if guess < 1 or guess > 10:
print("Out of range. Try again.")
continue
if guess == 7:
print("Congratulations! You guessed it.")
break
print("Wrong guess. Try again.")
Practical no -4
Program Related to Dictionaries
# Creating a dictionary
student = {
"name": "John Doe",
"age": 20,
"grade": "A",
"subjects": ["Math", "Science", "English"]
print("Student Dictionary:", student)
# Accessing values
print("Name:", student["name"])
print("Grade:", [Link]("grade"))
# Handling missing keys
print("Hobby:", [Link]("hobby", "Not specified"))
# Adding a new key-value pair
student["hobby"] = "Reading"
print("Updated Dictionary:", student)
# Updating an existing value
student["grade"] = "A+"
print("Updated Grade:", student)
# Using del
del student["hobby"]
print("After Deletion (del):", student)
# Using pop
age = [Link]("age")
print("Popped Age:", age)
print("After Deletion (pop):", student)
# Looping through keys
print("Keys:")
for key in [Link]():
print(key)
# Looping through values
print("\nValues:")
for value in [Link]():
print(value)
# Looping through key-value pairs
print("\nKey-Value Pairs:")
for key, value in [Link]():
print(f"{key}: {value}")
# Write a program to add a new key-value pair to a dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
new_key=input("Enter new key: ")
new_value=input("Enter new value: ")
thisdict[new_key]=new_value
print(thisdict)
# Write a program to remove a key-value pair from a dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
a=input("Enter key to remove : ")
[Link](a)
print(thisdict)
# # Create a dictionary that stores the population of three cities. Print the dictionary.
thisdict={}
print("City population",thisdict)
for i in range(0,3):
new_key=input("Enter the key:")
new_value=input("Enter the value:")
thisdict[new_key]=new_value
print("City Population :",thisdict)