Python Programs With Explanations
Python Programs With Explanations
1. Calculator Program
This program allows users to perform basic arithmetic operations (addition, subtraction,
multiplication, and division) on two numbers. It also includes error handling to manage
invalid inputs and ensures division by zero does not crash the program.
Code:
# Addition
print("{} + {} = ".format(n1, n2))
print(n1 + n2)
# Subtraction
print("{} - {} = ".format(n1, n2))
print(n1 - n2)
# Multiplication
print("{} * {} = ".format(n1, n2))
print(n1 * n2)
except ValueError:
print("Invalid input! Please enter numeric values.")
2. Student Data Processing
This program processes student data, calculates total marks and averages for each student,
and displays the results along with class averages. It uses lists to store and manipulate data,
and iterates through the sample data provided.
Code:
# Sample data
test_data = [
["John", 85, 90, 88],
["Emma", 92, 88, 95],
["Mike", 78, 85, 80],
["Sarah", 95, 92, 91],
["Tom", 88, 84, 89],
["Lisa", 90, 91, 87],
["David", 82, 88, 85],
["Anna", 94, 89, 92],
["James", 87, 83, 86],
["Mary", 91, 90, 88]
]
# Store in lists
names.append(name)
math_marks.append(math)
english_marks.append(english)
it_marks.append(it)
# Display results
print("\n--- Student Details ---")
print("Name\t\tMath\tEnglish\tIT\tTotal\tAverage")
print("-" * 50)
for i in range(len(names)):
print(f"{names[i]}\t\t{math_marks[i]}\t{english_marks[i]}\t{it_marks[i]}\t{totals[i]}\
t{averages[i]:.1f}")
3. Displaying Topper
This program identifies the student with the highest total marks from a list of students and
displays their details. It uses a loop to iterate through the student data and keeps track of
the highest total marks encountered.
Code:
# Sample data
students = [
["John", 85, 90, 88],
["Emma", 92, 88, 95],
["Mike", 78, 85, 80],
["Sarah", 95, 92, 91],
["Tom", 88, 84, 89],
["Lisa", 90, 91, 87],
["David", 82, 88, 85],
["Anna", 94, 89, 92],
["James", 87, 83, 86],
["Mary", 91, 90, 88]
]
print(f"{name}\t\t{math}\t{english}\t{it}\t{total}")