0% found this document useful (0 votes)
13 views15 pages

Python Programming Exercises List

The document contains a comprehensive index of Python programs covering various topics such as user-defined modules, data structures, file handling, exceptions, and statistical analysis. Each program includes a brief description and code snippets demonstrating its functionality. The programs aim to provide practical examples for learning Python programming concepts.

Uploaded by

gauravrathor9103
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views15 pages

Python Programming Exercises List

The document contains a comprehensive index of Python programs covering various topics such as user-defined modules, data structures, file handling, exceptions, and statistical analysis. Each program includes a brief description and code snippets demonstrating its functionality. The programs aim to provide practical examples for learning Python programming concepts.

Uploaded by

gauravrathor9103
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

Sr. Program Name Date Signature


No.
1 Program to create a user-defined module and import it into
another Python file
2 Program to accept user details from the user and print a
formatted output
3 Program to determine the largest of three numbers using
nested if
4 Program to calculate student grade using if–elif–else
5 Program to count vowels, consonants, digits, and special
characters
6 Program to check whether a string is a palindrome
7 Program to perform list operations: insert, delete, search, sort

8 Program to store student records in a list and compute average


marks
9 Program to store immutable student data using tuples

10 Program to find the maximum and minimum marks stored in


tuple records
11 Program to perform set operations (union, intersection,
difference)
12 Program to remove duplicates from a list using sets

13 Program to implement a dictionary-based contact book


(CRUD)
14 Program to count occurrences of words in a text using a
dictionary
15 Program using a user-defined math module (prime, factorial,
gcd)
16 Program using standard libraries (random, math, string, sys)
17 Program to read contents from a file and print them

18 Program to write user-entered text into a file


19 Program to handle division-by-zero using try–except

20 Program to create and handle a custom exception


21 Program to compute mean, median, and mode without using
pandas
22 Program to analyze frequency distribution of numbers from
user input
23 Program to load a CSV file using Pandas and display basic
information
24 Program to clean data (handle missing values) and perform
group-by operations
1. Program to create a user-defined module and import it into another
Python file
Code:
# [Link]
defgreet(name):
returnf"Hello, {name}!"
defadd(a, b):
return a + b
# [Link]
importmymodule
print([Link]("Alice"))
print([Link](5, 3))

Output:

1. Program to accept user details from the user and print a formatted output.
Code:
name =input("Enter your name: ")
age =input("Enter your age: ")
city =input("Enter your city: ")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")

Output:
2. Program to determine the largest of three numbers using nested if.
Code:
a =float(input("Enter first number: "))
b =float(input("Enter second number: "))
c =float(input("Enter third number: "))
if a >= b:
if a >= c:
largest = a
else:
largest = c
else:
if b >= c:
largest = b
else:
largest = c
print(f"The largest number is: {largest}")
Output:

3. Program to calculate student grade using if–elif–else


Code:
marks =float(input("Enter marks (0-100): "))
if marks >=90:
grade ="A"
elif marks >=80:
grade ="B"
elif marks >=70:
grade ="C"
elif marks >=60:
grade ="D"
else:
grade ="F"
print(f"Grade: {grade}")
Output:
4. Program to count vowels, consonants, digits, and special characters Code:
text =input("Enter a string: ")
vowels = consonants = digits = specials =0
for char in text:
[Link]():
[Link]() in'aeiou':
vowels +=1
else:
consonants +=1
[Link]():
digits +=1
else:
specials +=1
print(f"Vowels: {vowels}, Consonants: {consonants}, Digits:
{digits}, Special Characters: {specials}")

Output:

5. Program to check whether a string is a palindrome.


Code:
text =input("Enter a string: ").replace(" ", "").lower()
if text == text[::-1]:
print("It's a palindrome.")
else:
print("It's not a palindrome.")
Output:
6. Program to perform list operations: insert, delete, search, sort Code:
my_list= [3, 1, 4, 1, 5]
# Insert
my_list.insert(2, 9)
print("After insert:", my_list)
# Delete
my_list.remove(1) # Removes first occurrence of 1
print("After delete:", my_list)
# Search
if4inmy_list:
print("4 found at index:", my_list.index(4))
else:
print("4 not found")
# Sort
my_list.sort()
print("After sort:", my_list)
Output:

7. Program to store student records in a list and compute average marks


Code:
students = []
n =int(input("Enter number of students: "))
foriinrange(n):
name =input(f"Enter name of student {i+1}: ")
marks =float(input(f"Enter marks of {name}: "))
[Link]((name, marks))
total_marks=sum(marks for _, marks in students)
average =total_marks/ n
print(f"Average marks: {average:.2f}")

Output:
8. Program to store immutable student data using tuples
Code:
student1 = ("Alice", 85, "A")
student2 = ("Bob", 90, "A")
students = [student1, student2]
print("Student records:")
for student in students:
print(f"Name: {student[0]}, Marks: {student[1]}, Grade:
{student[2]}")
Output:

9. Program to find the maximum and minimum marks stored in tuple


records
Code:
students = [("Alice", 85), ("Bob", 90), ("Charlie", 78)]
marks = [student[1] for student in students]
print(f"Max marks: {max(marks)}, Min marks: {min(marks)}")
Output:

10. Program to perform set operations (union, intersection, difference).


Code
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
print("Difference (set1 - set2):", set1 - set2)

Output:
11. Program to remove duplicates from a list using setsCode:
my_list= [1, 2, 2, 3, 4, 4, 5]
unique_list=list(set(my_list))
print("Original list:", my_list)
print("List without duplicates:", unique_list)
Output:

12. Program toImplement a dictionary-based contact book (CRUD)


Code:
contacts = {}
defadd_contact(name, phone):
contacts[name] = phone
print(f"Added{name}")
defview_contacts():
for name, phone [Link]():
print(f"{name}: {phone}")
defupdate_contact(name, phone):
if name in contacts:
contacts[name] = phone
print(f"Updated{name}")
else:
print("Contact not found")
defdelete_contact(name):
if name in contacts:
del contacts[name]
print(f"Deleted{name}")
else:
print("Contact not found")
# Example usage
add_contact("Alice", "123-456")
add_contact("Bob", "789-012")
view_contacts()
update_contact("Alice", "111-222")
delete_contact("Bob")
view_contacts()
Output:

13. Program toCount occurrences of words in a text using a dictionary


Code:
text =input("Enter text: ").lower()
words =[Link]()
word_count= {}
for word in words:
word_count[word] =word_count.get(word, 0) +1
print("Word counts:")
for word, count inword_count.items():
print(f"{word}: {count}")
Output:

14. Program using a user-defined math module (prime, factorial, gcd)


Code:
# math_utils.py
defis_prime(n):
if n <=1:
returnFalse
foriinrange(2, int(n**0.5) +1):
if n %i==0:
returnFalse
returnTrue
deffactorial(n):
if n ==0:
return1
return n * factorial(n-1)
defgcd(a, b):
while b:
a, b = b, a % b
return a

# [Link]
importmath_utils
print("Is 7 prime?", math_utils.is_prime(7))
print("Factorial of 5:", math_utils.factorial(5))
print("GCD of 48 and 18:", math_utils.gcd(48, 18))

Output:

15. Program using standard libraries (random, math, string, sys)

Code:import random
import math
import string
import sys
# Random: Generate random number
print("Random number (1-10):", [Link](1, 10))
# Math: Square root
print("Square root of 16:", [Link](16))
# String: Generate random string
print("Random string:",
''.join([Link](string.ascii_letters, k=5)))
# Sys: Get Python version
print("Python version:", [Link])

Output:
16. Program toRead contents from a file and print them
Code:
withopen("[Link]", "r") asfile:
content =[Link]()
print(content)

Output:
File contents:
(Contents of [Link] printed here)

17. Program toWrite user-entered text into a file


Code:
text =input("Enter text to write to file: ")
withopen("[Link]", "w") asfile:
[Link](text)
print("Text written to [Link]")

Output:

18. Program toHandle division-by-zero using try–except


Code:
try:
num=int(input("Enter numerator: "))
den =int(input("Enter denominator: "))
result =num/ den
print(f"Result: {result}")
exceptZeroDivisionError:
print("Error: Division by zero is not allowed.")
exceptValueError:
print("Error: Please enter valid integers.")
Output:

19. Program toCreate and handle a custom exception


Code:
classCustomError(Exception):
pass
defcheck_age(age):
if age <0:
raiseCustomError("Age cannot be negative.")
returnf"Age is {age}"
try:
age =int(input("Enter age: "))
print(check_age(age))
exceptCustomErroras e:
print(f"Custom error: {e}")
exceptValueError:
print("Please enter a valid integer.")
Output:

20. Program toCompute mean, median, and mode without using pandas
Code:
from collections import Counter
# Input numbers
nums=list(map(float, input("Enter numbers separated by space:
").split()))
# Mean
mean =sum(nums) /len(nums)
# Median
[Link]()
n =len(nums)
median = (nums[n//2] if n %2!=0else (nums[n//2-1] +nums[n//2])
/2)
# Mode
count = Counter(nums)
mode =count.most_common(1)[0][0]
print(f"Mean: {mean:.2f}, Median: {median:.2f}, Mode: {mode}")
Output:

21. Program toAnalyze frequency distribution of numbers from user input


Code:
from collections import Counter
# Input numbers
nums=list(map(int, input("Enter numbers separated by space:
").split()))
# Frequency distribution
freq= Counter(nums)
print("Frequency distribution:")
fornum, count insorted([Link]()):
print(f"{num}: {count}")
Output:

22. Program toLoad a CSV file using Pandas and display basic information
Code:
: importpandasaspd

try:
# Attempt to load the CSV file
df = pd.read_csv('[Link]')
print("CSV loaded successfully.")
exceptFileNotFoundError:
# Fallback: Create a sample DataFrame if file doesn't
exist
print("Error: '[Link]' not found. Using sample data
instead.")
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [20, 21, 22],
'Score': [85, 90, 88]
}
df = [Link](data)

# Display basic information


print("\nFirst 5 rows:")
print([Link]())
print("\nShape:", [Link])
print("\nColumns:", list([Link]))
print("\nData types:")
print([Link])
Output:
23. Program toClean data (handle missing values) and perform group-by
operations

Code:
importpandasaspd
try:
# Attempt to load the CSV file
df = pd.read_csv('[Link]')
print("CSV loaded successfully.")
exceptFileNotFoundError:
# Fallback: Create a sample DataFrame with missing
values if file doesn't exist
print("Error: '[Link]' not found. Using sample data
with missing values instead.")
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Alice'],
'Age': [20, None, 22, 21], # None represents
missing values
'Score': [85, 90, None, 88]
}
df = [Link](data)
print("\nOriginalDataFrame:")
print(df)
# Handle missing values (fill with mean for numeric, mode
for categorical)
df['Age'] = df['Age'].fillna(df['Age'].mean())
df['Score'] = df['Score'].fillna(df['Score'].mean())
df['Name'] = df['Name'].fillna(df['Name'].mode()[0])
print("\nDataFrame after cleaning missing values:")
print(df)
# Group by 'Name' and compute mean score
grouped = [Link]('Name')['Score'].mean()
print("\nMean score by name:")
print(grouped)

Output:

You might also like