Python Basic Exercises with Solutions
# 1. Accept two numbers and perform basic arithmetic operations
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print(f"Addition: {num1 + num2}")
print(f"Subtraction: {num1 - num2}")
print(f"Multiplication: {num1 * num2}")
if num2 != 0:
print(f"Division: {num1 / num2}")
else:
print("Division by zero is not allowed.")
# 2. Famous quote with escape characters
quote = "\"Imagination is more important than knowledge.\""
author = "Albert Einstein"
print(f"{author} once said, {quote}")
# 3. Check even or odd
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
# 4. Grade checker
score = int(input("Enter student's score (0-100): "))
if 0 <= score <= 100:
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
else:
print("Invalid score.")
# 5. Reverse a string
text = input("Enter a string: ")
print(f"Original: {text}, Length: {len(text)}")
print(f"Reversed: {text[::-1]}")
# 6. Check palindrome
word = input("Enter a string to check palindrome: ").lower()
if word == word[::-1]:
print("It's a palindrome.")
else:
print("Not a palindrome.")
# 7. Count words in a sentence
sentence = input("Enter a sentence: ")
words = sentence.split()
print(f"Word count: {len(words)}")
# 8. Find character count and first position
text = input("Enter a sentence: ")
char = input("Enter a character: ")
print(f"Character count: {text.count(char)}")
print(f"First occurrence at index: {text.find(char)}")
# 9. List operations
nums = [int(input(f"Enter number {i+1}: ")) for i in range(5)]
print("List:", nums)
new_num = int(input("Enter a number to add: "))
nums.append(new_num)
nums.sort()
print("Sorted list:", nums)
remove_num = int(input("Enter number to remove: "))
if remove_num in nums:
nums.remove(remove_num)
print("Updated list:", nums)
# 10. Tuple operations
elements = tuple(int(input(f"Enter element {i+1}: ")) for i in range(5))
print("Max:", max(elements))
print("Min:", min(elements))
print("Sum:", sum(elements))
print("Second element:", elements[1])
print("Fourth element:", elements[3])
# 11. Dictionary creation and access
my_dict = {}
for i in range(3):
key = input(f"Enter key {i+1}: ")
value = input(f"Enter value for {key}: ")
my_dict[key] = value
print("Keys:", list(my_dict.keys()))
print("Values:", list(my_dict.values()))
query_key = input("Enter key to access value: ")
print("Value:", my_dict.get(query_key, "Key not found"))
# 12. Modify student dictionary
student = {"name": "John", "roll_number": 101, "marks": 85}
student["marks"] = int(input("Enter updated marks: "))
student["grade"] = input("Enter grade: ")
del student["roll_number"]
print(student)
# 13. 1D array with sum and max
arr = [int(input(f"Enter element {i+1}: ")) for i in range(5)]
print("Array:", arr)
print("Sum:", sum(arr))
print("Max:", max(arr))
# 14. 2D array matrix operations
matrix = []
for i in range(3):
row = [int(input(f"Enter element [{i+1}][{j+1}]: ")) for j in range(3)]
matrix.append(row)
print("Matrix:")
for row in matrix:
print(row)
print("Row sums:", [sum(row) for row in matrix])
print("Column sums:", [sum(matrix[i][j] for i in range(3)) for j in range(3)])
# 15. Average of list using function
def calculate_average(numbers):
return sum(numbers) / len(numbers)
nums = list(map(int, input("Enter numbers separated by space: ").split()))
print("Average:", calculate_average(nums))
# 16. Fibonacci using recursion
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
n = int(input("Enter n terms for Fibonacci: "))
for i in range(n):
print(fibonacci(i), end=" ")
print()
# 17. Square using map and lambda
nums = list(map(int, input("Enter numbers: ").split()))
squares = list(map(lambda x: x**2, nums))
print("Original:", nums)
print("Squared:", squares)
# 18. Filter even numbers
nums = list(map(int, input("Enter numbers: ").split()))
evens = list(filter(lambda x: x % 2 == 0, nums))
print("Original:", nums)
print("Even numbers:", evens)
# 19. Reduce to find sum
from functools import reduce
nums = list(map(int, input("Enter numbers: ").split()))
sum_all = reduce(lambda x, y: x + y, nums)
print("Sum:", sum_all)
# 20. Reduce to find max
maximum = reduce(lambda x, y: x if x > y else y, nums)
print("Max:", maximum)
# 21. Book class
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def display_details(self):
print(f"{self.title} by {self.author}, Rs.{self.price}")
book1 = Book("Python Basics", "Guido", 499)
book2 = Book("AI Fundamentals", "Alan", 599)
book1.display_details()
book2.display_details()
# 22. Rectangle class
class Rectangle:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
def perimeter(self):
return 2 * (self.length + self.breadth)
rect = Rectangle(5, 3)
print("Area:", rect.area())
print("Perimeter:", rect.perimeter())
# 23. BankAccount class
class BankAccount:
def __init__(self, account_holder, account_number, balance):
self.account_holder = account_holder
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
def display_balance(self):
print("Balance:", self.balance)
account = BankAccount("Isha", "12345", 1000)
account.deposit(500)
account.withdraw(200)
account.display_balance()
# 24. Employee class with increment
class Employee:
def __init__(self, name, employee_id, salary):
self.name = name
self.employee_id = employee_id
self.salary = salary
def show_details(self):
print(self.name, self.employee_id, self.salary)
def increment_salary(self, percent):
self.salary += self.salary * (percent / 100)
e1 = Employee("Alice", 1, 50000)
e2 = Employee("Bob", 2, 60000)
e1.increment_salary(10)
e2.increment_salary(15)
e1.show_details()
e2.show_details()
# 25. Vehicle base class
class Vehicle:
def __init__(self, brand, year):
self.brand = brand
self.year = year
class Car(Vehicle):
def __init__(self, brand, year, model):
super().__init__(brand, year)
self.model = model
def show(self):
print(self.brand, self.year, self.model)
class Bike(Vehicle):
def __init__(self, brand, year, type):
super().__init__(brand, year)
self.type = type
def show(self):
print(self.brand, self.year, self.type)
Car("Toyota", 2020, "Innova").show()
Bike("Honda", 2021, "Sport").show()
# 26. Shape base class with polymorphism
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
print(Rectangle(4, 5).area())
print(Circle(3).area())
# 27. Polymorphism with Employee subclasses
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def show_role(self):
print("Employee")
class Manager(Employee):
def show_role(self):
print("Manager")
class Developer(Employee):
def show_role(self):
print("Developer")
Employee("A", 1000).show_role()
Manager("B", 2000).show_role()
Developer("C", 3000).show_role()
# 28. Inheritance with Bank Accounts
class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder
self.balance = balance
class SavingsAccount(BankAccount):
def interest(self):
return self.balance * 0.04
class CurrentAccount(BankAccount):
def overdraft_limit(self):
return 50000
print(SavingsAccount("A", 10000).interest())
print(CurrentAccount("B", 20000).overdraft_limit())
# 29. File write-read with exception
try:
content = input("Enter a string: ")
with open("output.txt", "w") as f:
f.write(content)
with open("output.txt", "r") as f:
print("File content:", f.read())
except (FileNotFoundError, IOError) as e:
print("File error:", e)
finally:
print("Done")
# 30. Count words in file
try:
with open("output.txt", "r") as f:
data = f.read()
print("Word count:", len(data.split()))
except Exception as e:
print("Error:", e)
# 31. Tkinter GUI for sum
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("Addition GUI")
def calculate():
try:
val1 = int(entry1.get())
val2 = int(entry2.get())
result = val1 + val2
messagebox.showinfo("Result", f"Sum: {result}")
except ValueError:
messagebox.showerror("Error", "Please enter valid numbers")
label1 = tk.Label(root, text="Number 1")
label1.pack()
entry1 = tk.Entry(root)
entry1.pack()
label2 = tk.Label(root, text="Number 2")
label2.pack()
entry2 = tk.Entry(root)
entry2.pack()
btn = tk.Button(root, text="Add", command=calculate)
btn.pack()
root.mainloop()
# 32. Login Form GUI
import tkinter as tk
from tkinter import messagebox
login_win = tk.Tk()
login_win.title("Login Form")
def login():
user = username.get()
pwd = password.get()
if user and pwd:
messagebox.showinfo("Login", "Login Successful")
else:
messagebox.showerror("Error", "All fields required")
username = tk.Entry(login_win)
username.pack()
password = tk.Entry(login_win, show="*")
password.pack()
tk.Button(login_win, text="Login", command=login).pack()
login_win.mainloop()
# 33. SQLite with students table
import sqlite3
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS students (name TEXT, age INTEGER, grade
TEXT)")
cursor.executemany("INSERT INTO students VALUES (?, ?, ?)", [
("Isha", 20, "A"),
("Amit", 22, "B"),
("Riya", 21, "C")
])
conn.commit()
cursor.execute("SELECT * FROM students")
print(cursor.fetchall())
conn.close()
# 34. SQLite with employee operations
conn = sqlite3.connect("employees.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS employees (id INTEGER, name TEXT, salary
INTEGER)")
cursor.execute("INSERT INTO employees VALUES (1, 'John', 30000)")
cursor.execute("INSERT INTO employees VALUES (2, 'Jane', 40000)")
cursor.execute("UPDATE employees SET salary = 45000 WHERE name = 'John'")
cursor.execute("DELETE FROM employees WHERE name = 'Jane'")
cursor.execute("SELECT * FROM employees")
print(cursor.fetchall())
conn.commit()
conn.close()
# 35. DataFrame with NumPy and Matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = {"Name": ["A", "B", "C", "D", "E"], "Marks": [70, 85, 90, 60, 75]}
df = pd.DataFrame(data)
print(df)
print("Average:", np.mean(df["Marks"]))
print("Max:", np.max(df["Marks"]))
print("Min:", np.min(df["Marks"]))
plt.bar(df["Name"], df["Marks"])
plt.show()
# 36. Monthly sales plot
sales_data = {"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], "Sales": [1000, 1500, 1200,
1300, 1600, 1700]}
df = pd.DataFrame(sales_data)
print("Total:", np.sum(df["Sales"]))
print("Average:", np.mean(df["Sales"]))
plt.plot(df["Month"], df["Sales"])
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()