100 python excercises
100 python excercises
1 Fondamentals 8
1.1 Basic Syntax & Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.1.1 Exercise 1: Declare and Print Variables . . . . . . . . . . . . . . . . . 8
1.1.2 Exercise 2: Swap Two Variables Without a Third Variable . . . . . . . 8
1.1.3 Exercise 3: Assign Multiple Variables in One Line . . . . . . . . . . . 9
1.1.4 Exercise 4: Check the Type of a Variable . . . . . . . . . . . . . . . . 9
1.1.5 Exercise 5: Concatenating Strings . . . . . . . . . . . . . . . . . . . . 9
1.2 Data Types & Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.2.1 Exercise 6: Convert String to Integer and Vice Versa . . . . . . . . . . 10
1.2.2 Exercise 7: Convert Float to Integer and Vice Versa . . . . . . . . . . 10
1.2.3 Exercise 8: Convert a Boolean to an Integer . . . . . . . . . . . . . . 10
1.2.4 Exercise 9: Convert List to a String and Back . . . . . . . . . . . . . . 11
1.2.5 Exercise 10: Convert Dictionary Keys and Values to Lists . . . . . . . 11
1.3 Operators & Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.1 Exercise 11: Perform Arithmetic Operations . . . . . . . . . . . . . . . 11
1.3.2 Exercise 12: Use Comparison Operators . . . . . . . . . . . . . . . . 12
1.3.3 Exercise 13: Use Logical Operators . . . . . . . . . . . . . . . . . . . 12
1.3.4 Exercise 14: Use Assignment Operators . . . . . . . . . . . . . . . . . 12
1.3.5 Exercise 15: Use Bitwise Operators . . . . . . . . . . . . . . . . . . . 13
1.4 Control Flow (Conditionals & Loops) . . . . . . . . . . . . . . . . . . . . . . . 13
1.4.1 Exercise 16: Check if a Number is Even or Odd . . . . . . . . . . . . 13
1.4.2 Exercise 17: Find the Largest Number . . . . . . . . . . . . . . . . . . 14
1.4.3 Exercise 18: Check if a Year is a Leap Year . . . . . . . . . . . . . . . 14
1.4.4 Exercise 19: Print Numbers from 1 to N . . . . . . . . . . . . . . . . . 14
1.4.5 Exercise 20: Print Even Numbers up to N . . . . . . . . . . . . . . . . 15
1.4.6 Exercise 21: Sum of First N Natural Numbers . . . . . . . . . . . . . . 15
1.4.7 Exercise 22: Factorial of a Number . . . . . . . . . . . . . . . . . . . . 15
1.4.8 Exercise 23: Reverse a Number . . . . . . . . . . . . . . . . . . . . . 16
1.4.9 Exercise 24: Multiplication Table . . . . . . . . . . . . . . . . . . . . . 16
1.4.10 Exercise 25: Count Digits in a Number . . . . . . . . . . . . . . . . . . 16
1.5 Functions & Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.5.1 Exercise 26: Define and Call a Function . . . . . . . . . . . . . . . . . 17
1.5.2 Exercise 27: Function with Parameters . . . . . . . . . . . . . . . . . 17
1.5.3 Exercise 28: Function Returning a Value . . . . . . . . . . . . . . . . 17
1.5.4 Exercise 29: Function with Default Parameter . . . . . . . . . . . . . . 18
1.5.5 Exercise 30: Function Using Global Variable . . . . . . . . . . . . . . 18
1.5.6 Exercise 31: Function Using Local Variable . . . . . . . . . . . . . . . 18
2
100 Python Exercises
2 Mini Projects 30
2.0.1 Project 66: Student Grade Management System . . . . . . . . . . . . 30
2.0.2 Project 67: Expense Tracker . . . . . . . . . . . . . . . . . . . . . . . 30
2.0.3 Project 68: Contact Book . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.0.4 Project 69: Temperature Converter . . . . . . . . . . . . . . . . . . . . 31
2.0.5 Project 70: Number Guessing Game . . . . . . . . . . . . . . . . . . . 32
2.0.6 Project 71: To-Do List App . . . . . . . . . . . . . . . . . . . . . . . . 32
2.0.7 Project 72: Banking System . . . . . . . . . . . . . . . . . . . . . . . . 32
2.0.8 Project 73: BMI Calculator . . . . . . . . . . . . . . . . . . . . . . . . 33
3
100 Python Exercises
3 Solutions 44
3.1 Basic Syntax & Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.1.1 Solution 1: Declare and Print Variables . . . . . . . . . . . . . . . . . 44
3.1.2 Solution 2: Swap Two Variables Without a Third Variable . . . . . . . 44
3.1.3 Solution 3: Assign Multiple Variables in One Line . . . . . . . . . . . . 45
3.1.4 Solution 4: Check the Type of a Variable . . . . . . . . . . . . . . . . 45
3.1.5 Solution 5: Concatenating Strings . . . . . . . . . . . . . . . . . . . . 45
3.2 Data Types & Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2.1 Solution 6: Convert String to Integer and Vice Versa . . . . . . . . . . 45
3.2.2 Solution 7: Convert Float to Integer and Vice Versa . . . . . . . . . . 46
3.2.3 Solution 8: Convert a Boolean to an Integer . . . . . . . . . . . . . . . 46
3.2.4 Solution 9: Convert List to a String and Back . . . . . . . . . . . . . . 47
3.2.5 Solution 10: Convert Dictionary Keys and Values to Lists . . . . . . . 47
3.3 Operators & Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.3.1 Solution 11: Perform Arithmetic Operations . . . . . . . . . . . . . . . 47
3.3.2 Solution 12: Use Comparison Operators . . . . . . . . . . . . . . . . . 48
3.3.3 Solution 13: Use Logical Operators . . . . . . . . . . . . . . . . . . . 48
3.3.4 Solution 14: Use Assignment Operators . . . . . . . . . . . . . . . . . 49
3.3.5 Solution 15: Use Bitwise Operators . . . . . . . . . . . . . . . . . . . 49
4
100 Python Exercises
5
100 Python Exercises
6
Introduction
At Lkhibra Academy, we empower learners with practical programming skills essential for
today’s evolving tech industry. Whether you’re new to coding or looking to advance your
expertise, we make programming education accessible, engaging, and effective.
This book provides curated Python exercises bridging theory and real-world applications,
enhancing your programming abilities and problem-solving skills.
We believe learning should be enjoyable and insightful—so get ready to learn, laugh, and
succeed!
Lkhibra is MORE !
To support your journey beyond this book, we provide additional learning resources through:
• Lkhibra Network – Join our community where we host free learning sessions every
month, helping learners connect, collaborate, and grow together: Join our Network.
7
Chapter 1
Fondamentals
Task:
• Declare variables for an instructor’s name, the number of students in a Python class,
and the course name.
Task:
Expected Output:
8
100 Python Exercises
Task:
• Assign values to three variables representing the number of Python, Java, and AI stu-
dents in a single line.
Expected Output:
Task:
• Declare different types of variables: an integer (age), a float (course rating), and a
string (course name).
Expected Output:
Task:
• Declare three separate string variables: instructor, academy name, and slogan.
Expected Output:
9
100 Python Exercises
Task:
• Convert the string "100" into an integer.
Task:
• Convert a float 9.75 into an integer.
Task:
• Convert the Boolean values True and False into integers.
10
100 Python Exercises
True as an integer: 1
False as an integer: 0
Task:
Expected Output:
Task:
Expected Output:
Task:
11
100 Python Exercises
Expected Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.5
Modulus: 0
Task:
• Compare two numbers using comparison operators.
• Print the results.
Expected Output:
10 > 5: True
10 < 5: False
10 == 10: True
10 != 5: True
10 >= 5: True
10 <= 5: False
Task:
• Use and, or, and not to evaluate logical expressions.
Expected Output:
Task:
12
100 Python Exercises
Expected Output:
Initial Value: 10
After += : 15
After -= : 12
After *= : 24
After /= : 8.0
After %= : 0.0
Task:
Expected Output:
5 & 3 = 1
5 | 3 = 7
5 ^ 3 = 6
5 << 1 = 10
5 >> 1 = 2
Task:
Expected Output:
Enter a number: 7
7 is an odd number.
13
100 Python Exercises
Task:
Expected Output:
Task:
Expected Output:
Task:
Expected Output:
Enter a number: 5
1 2 3 4 5
14
100 Python Exercises
Task:
Expected Output:
Enter a number: 10
2 4 6 8 10
Task:
Expected Output:
Enter a number: 5
Sum of first 5 numbers: 15
Task:
Expected Output:
Enter a number: 5
Factorial of 5 is 120.
15
100 Python Exercises
Task:
• Take an integer input.
Task:
• Take an integer input N.
Enter a number: 7
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
Task:
• Take an integer input.
16
100 Python Exercises
Task:
Expected Output:
Task:
Expected Output:
Task:
Expected Output:
17
100 Python Exercises
Task:
Expected Output:
Hello, Student!
Hello, Amine!
Task:
Expected Output:
Task:
Expected Output:
18
100 Python Exercises
Task:
Expected Output:
Factorial of 5 is 120.
Task:
Expected Output:
Sum: 8, Product: 15
Task:
Expected Output:
19
100 Python Exercises
Task:
• Given the list of scores [88, 92, 75, 100, 89], sort them in ascending order.
Expected Output:
Task:
• Given the list of prices [299, 159, 499, 120, 349], find and print the highest price.
Expected Output:
Task:
• Given the sentence: ”Python is great and Python is fun”, count how many times each
word appears.
Expected Output:
Task:
• Create a dictionary where student names are keys and their grades are values.
20
100 Python Exercises
Expected Output:
Sarah's grade: A
Task:
• Given two sets of students enrolled in Python and Java, find students taking both
courses.
Expected Output:
{'Alice', 'David'}
Task:
• Extract all unique words from the text: ”Python is amazing and Python is powerful”.
Expected Output:
Task:
• Create a menu where dish names are keys and prices are values.
Expected Output:
21
100 Python Exercises
Task:
• Create a dictionary where items are keys and stock quantities are values.
Expected Output:
Laptops in stock: 15
Task:
• Given a list of customer reviews, find the most frequently mentioned word.
Expected Output:
Task:
Expected Output:
Unique visitors: 3
Task:
22
100 Python Exercises
• Given two sets of customers who bought ”Laptops” and ”Monitors,” find those who
bought both.
Expected Output:
Task:
• Given a list of registered students and a list of those who attended, find the missing
students.
Expected Output:
Task:
• Given two dictionaries with product stock, merge them into one.
Expected Output:
Task:
Expected Output:
23
100 Python Exercises
Task:
Expected Output:
Domain: example.com
Objective: Count how many times a specific word appears in customer reviews.
Task:
Expected Output:
Objective: Properly align items and prices in an invoice using string formatting.
Task:
Expected Output:
Item Price
-------------------
Laptop $1200.99
Mouse $25.50
24
100 Python Exercises
Task:
Expected Output:
Task:
Expected Output:
Task:
• Ensure the password has at least 8 characters, including a number and special char-
acter.
Task:
Expected Output:
25
100 Python Exercises
Hello World !
Task:
Expected Output:
Task:
Expected Output:
Task:
Expected Output:
26
100 Python Exercises
Task:
• Write a formatted record (e.g., “Customer: John, Item: Laptop, Price: $1200”) to
sales.txt.
Expected Output:
1.8.3 Exercise 60: Read a File and Handle Missing File Errors
Objective: Handle file-related exceptions in Python.
Task:
Expected Output:
Task:
27
100 Python Exercises
Expected Output:
Task:
• If the input is not an integer, prompt again until a valid integer is entered.
Expected Output:
Task:
Expected Output:
Enter numerator: 10
Enter denominator: 0
Error logged to file.
28
100 Python Exercises
Task:
Expected Output:
Reading sales_data.csv...
Product: Laptop, Amount: 1200
Product: Mouse, Amount: 25
...
Task:
Expected Output:
29
Chapter 2
Mini Projects
Task:
• Create a dictionary where student names are keys and their grades are values.
• Allow users to: Add a new student. Update an existing grade. Retrieve a student’s
grade. Display all students.
Expected Output:
1. Add Student
2. Update Grade
3. Get Grade
4. Display All
5. Exit
Enter choice: 1
Enter student name: Alice
Enter grade: A
Student added successfully.
Task:
• Allow users to: Add expenses (amount & category). View total expenses by category.
Display all transactions. Save transactions to a file.
Expected Output:
30
100 Python Exercises
1. Add Expense
2. View Expenses by Category
3. Save & Exit
Enter choice: 1
Enter category (Food, Transport, etc.): Food
Enter amount: 12.5
Expense added.
Task:
• Allow users to: Add new contacts. Search for a contact. Display all contacts. Save
contacts to a file.
Expected Output:
1. Add Contact
2. Search Contact
3. Display Contacts
4. Save & Exit
Enter choice: 1
Enter name: Alice
Enter phone number: 123-456-7890
Contact saved.
Task:
• Allow users to: Convert from Celsius to Fahrenheit. Convert from Fahrenheit to
Celsius.
Expected Output:
Convert to (C/F): F
Enter temperature: 0
Temperature in Fahrenheit: 32.00°F
31
100 Python Exercises
Task:
Expected Output:
Task:
• Allow users to: Add a task. Remove a task. View all tasks.
Expected Output:
1. Add Task
2. Remove Task
3. View Tasks
4. Exit
Enter choice: 1
Enter task: Buy groceries
Task added.
Task:
Expected Output:
32
100 Python Exercises
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
Enter choice: 1
Enter deposit amount: 200
Deposited $200.00. New balance: $200.00
Task:
• Prompt the user for weight (in kilograms) and height (in meters).
weight
• Compute BMI = height2
.
Expected Output:
Task:
• Allow the user to choose between different conversions (e.g., km to miles, kg to lbs).
Expected Output:
1. KM to Miles
2. KG to Lbs
Enter choice: 1
Enter value in KM: 5
Miles: 3.11
33
100 Python Exercises
Expected Output:
Expected Output:
Expected Output:
34
100 Python Exercises
Enter width: 10
Enter height: 5
Maze:
##########
# ## #
# ## # #
# #
##########
Task:
Expected Output:
Expected Output:
1. Mark Attendance
2. View Attendance
3. Reset Attendance
4. Exit
Enter choice: 1
Enter student name: Alice
Alice's attendance marked.
35
100 Python Exercises
Expected Output:
Server:
Waiting for client...
Connection established.
Client:
Connected to server.
Type your message.
Hello from client -> received on server
Task:
• Allow users to: View available books. Borrow a book. Return a book.
Expected Output:
1. View Books
2. Borrow Book
3. Return Book
4. Exit
Enter choice: 1
Available Books:
- Python Basics
- Data Science
- AI Fundamentals
Task:
• Allow users to: Vote for a candidate. Prevent multiple votes from the same user.
Display results.
36
100 Python Exercises
Expected Output:
1. Vote
2. Show Results
3. Exit
Enter choice: 1
Enter your ID: user123
Vote for (Alice/Bob/Charlie): Alice
Vote recorded!
Task:
Expected Output:
-----------------------------
ALICE BROWN
-----------------------------
Skills: Python, Data Analysis
Experience: 3 years
Task:
• Take user input and check if it’s a palindrome (ignoring case & spaces).
Expected Output:
37
100 Python Exercises
Task:
Expected Output:
Task:
Expected Output:
1. Save Password
2. View Passwords
3. Exit
Enter choice: 1
Enter website: example.com
Enter password: mySecret123
Password saved!
Task:
Expected Output:
38
100 Python Exercises
Task:
• Validate an email using regex.
Expected Output:
Task:
• Fetch and display weather information for a given city.
Expected Output:
Task:
• Get the latest stock price of a given company.
Expected Output:
Task:
• Take user input and generate a 3-sentence summary.
39
100 Python Exercises
Expected Output:
Task:
Expected Output:
Task:
Expected Output:
File encrypted.
File decrypted.
Task:
Expected Output:
40
100 Python Exercises
Task:
• Add, remove, and list employees.
Expected Output:
1. Add Employee
2. View Employees
3. Exit
Enter choice: 1
Enter employee ID: E123
Enter employee name: John
Enter position: Developer
Employee added.
Task:
• Store predefined questions and answers in a dictionary.
Task:
• Collect user input for customer name, items, and prices.
41
100 Python Exercises
Expected Output:
Task:
Expected Output:
Task:
Expected Output:
42
100 Python Exercises
Task:
Expected Output:
43
Chapter 3
Solutions
instructor = "Alex"
students = 30
course = "Python"
Explanation:
• The f"" (formatted string) allows inserting variables directly into a string.
students_morning = 15
students_evening = 25
Explanation:
44
100 Python Exercises
Explanation:
• Python allows multiple assignments in a single line.
age = 21
rating = 4.9
course_name = "Python Programming"
Explanation:
• The type() function is used to determine the type of a variable.
Explanation:
• Strings can be concatenated using the ‘+‘ operator.
45
100 Python Exercises
num_str = "100"
num_int = int(num_str)
num_int2 = 42
num_str2 = str(num_int2)
Explanation:
num_float = 9.75
num_int = int(num_float)
num_int2 = 50
num_float2 = float(num_int2)
Explanation:
bool_true = True
bool_false = False
Explanation:
46
100 Python Exercises
• False is equivalent to 0.
Explanation:
keys_list = list(academy_info.keys())
values_list = list(academy_info.values())
print(f"Keys: {keys_list}")
print(f"Values: {values_list}")
Explanation:
47
100 Python Exercises
a = 10
b = 5
print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b}")
print(f"Modulus: {a % b}")
Explanation:
a = 10
b = 5
Explanation:
a = True
b = False
Explanation:
48
100 Python Exercises
x = 10
print(f"Initial Value: {x}")
x += 5
print(f"After += : {x}")
x -= 3
print(f"After -= : {x}")
x *= 2
print(f"After *= : {x}")
x /= 3
print(f"After /= : {x}")
x %= 2
print(f"After %= : {x}")
Explanation:
• +=, -=, *=, /=, and %= modify variables in place.
a = 5 # Binary: 101
b = 3 # Binary: 011
Explanation:
• & (AND) keeps common bits.
49
100 Python Exercises
if num % 2 == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")
Explanation:
Explanation:
50
100 Python Exercises
Explanation:
• A leap year is divisible by 4 but not by 100, except when divisible by 400.
Explanation:
• The range() function generates numbers from 1 to N.
• end=" " ensures output is printed on the same line.
Explanation:
• The loop starts at 2 and increments by 2 to print even numbers.
51
100 Python Exercises
Explanation:
• The loop iterates from 1 to N, adding each number to the sum.
Explanation:
• The loop multiplies numbers from 1 to N to compute factorial.
Explanation:
• Extracts the last digit using % 10 and builds the reversed number.
Explanation:
• The loop iterates from 1 to 10 and prints the multiplication result.
52
100 Python Exercises
Explanation:
• The loop removes the last digit and increments the count until the number becomes 0.
def greet():
print("Hello, Lkhibra Academy!")
greet()
Explanation:
def welcome(name):
print(f"Hello, {name}! Welcome to Lkhibra Academy!")
welcome("Sara")
welcome("Youssef")
Explanation:
53
100 Python Exercises
def square(num):
return num * num
result = square(5)
print(f"The square of 5 is {result}.")
Explanation:
def greet(name="Student"):
print(f"Hello, {name}!")
greet()
greet("Amine")
Explanation:
academy = "Lkhibra"
def show_academy():
print(f"The best academy is {academy}!")
show_academy()
Explanation:
54
100 Python Exercises
def say_something():
message = "Lkhibra Rocks!"
print(f"Inside function: {message}")
say_something()
print(message) # This will cause an error
Explanation:
• Local variables exist only inside the function where they are declared.
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(f"Factorial of 5 is {factorial(5)}.")
Explanation:
Explanation:
55
100 Python Exercises
print(shopping_list)
Explanation:
print(scores)
Explanation:
Explanation:
56
100 Python Exercises
print(word_count)
Explanation:
Explanation:
Explanation:
print(unique_words)
Explanation:
57
100 Python Exercises
Explanation:
• A dictionary allows quick access to menu prices.
Explanation:
• Dictionaries allow quick access to stock levels.
Explanation:
• Uses a dictionary to count occurrences and max() to find the most common word.
Explanation:
• Sets automatically remove duplicate elements.
58
100 Python Exercises
Explanation:
Explanation:
• The - operator finds elements that are in one set but not in the other.
Explanation:
59
100 Python Exercises
Explanation:
email = "[email protected]"
domain = email.split("@")[1]
print(f"Domain: {domain}")
Explanation:
review = "The quality of this product is great. Quality matters. We love the quality!"
word_count = review.lower().split().count("quality")
print(f"{'Item':<12}{'Price':>10}")
print("-" * 22)
60
100 Python Exercises
print(reversed_sentence)
import re
print(f"Hashtags: {hashtags}")
import re
password = "Secure@123"
is_valid = bool(re.match(r'^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
import re
print(clean_text)
61
100 Python Exercises
print(title_case_text)
print(updated_text)
try:
with open(file_name, "r") as file:
lines = file.readlines()
print(f"Total lines: {len(lines)}")
except FileNotFoundError:
print("Error: The file does not exist.")
Explanation:
• Uses open(...) in read mode and .readlines() to get all lines.
62
100 Python Exercises
Explanation:
3.8.3 Solution 60: Read a File and Handle Missing File Errors
Solution:
try:
with open(file_name, "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print(f"Error: {file_name} not found.")
Explanation:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Explanation:
63
100 Python Exercises
while True:
try:
num = int(input("Enter a number: "))
print(f"You entered: {num}")
break
except ValueError:
print("Invalid input. Please enter an integer.")
Explanation:
try:
num1 = float(input("Enter numerator: "))
num2 = float(input("Enter denominator: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError as e:
with open("error_log.txt", "a") as f:
f.write(f"Error: {str(e)}\n")
print("Error logged to file.")
Explanation:
• Shows how to catch an exception, log it to a file, and give user feedback.
import csv
print("Reading sales_data.csv...")
try:
with open("sales_data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
64
100 Python Exercises
if row:
product, amount = row
print(f"Product: {product}, Amount: {amount}")
except FileNotFoundError:
print("Error: CSV file not found.")
Explanation:
try:
with open("notes.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("Error: notes.txt not found.")
Explanation:
students = {}
def add_student():
name = input("Enter student name: ")
grade = input("Enter grade: ")
students[name] = grade
print("Student added successfully.")
def update_grade():
name = input("Enter student name: ")
if name in students:
65
100 Python Exercises
def get_grade():
name = input("Enter student name: ")
print(f"{name}'s grade: {students.get(name, 'Not found')}")
def display_all():
for name, grade in students.items():
print(f"{name}: {grade}")
while True:
print("\n1. Add Student\n2. Update Grade\n3. Get Grade\n4. Display All\n5. Exit")
choice = input("Enter choice: ")
if choice == "1":
add_student()
elif choice == "2":
update_grade()
elif choice == "3":
get_grade()
elif choice == "4":
display_all()
elif choice == "5":
break
else:
print("Invalid choice. Try again.")
Explanation:
• Users can add or update a student’s grade, retrieve a specific grade, and display all
entries.
• This simple CLI menu provides a real-world scenario for basic data storage.
expenses = {}
def add_expense():
category = input("Enter category (Food, Transport, etc.): ")
66
100 Python Exercises
def view_by_category():
for category, total in expenses.items():
print(f"{category}: \${total:.2f}")
def save_to_file():
with open("expenses.txt", "w") as file:
for category, total in expenses.items():
file.write(f"{category}: \${total:.2f}\n")
print("Expenses saved to file.")
while True:
print("\n1. Add Expense\n2. View Expenses by Category\n3. Save & Exit")
choice = input("Enter choice: ")
if choice == "1":
add_expense()
elif choice == "2":
view_by_category()
elif choice == "3":
save_to_file()
break
else:
print("Invalid choice. Try again.")
Explanation:
• The user can add a new expense, view totals by category, or save the data to a file.
• This project demonstrates basic file writing, dictionary usage, and floating-point oper-
ations.
contacts = {}
def add_contact():
name = input("Enter name: ")
phone = input("Enter phone number: ")
contacts[name] = phone
print("Contact saved.")
67
100 Python Exercises
def search_contact():
name = input("Enter name: ")
print(f"Phone: {contacts.get(name, 'Not found')}")
def display_contacts():
for name, phone in contacts.items():
print(f"{name}: {phone}")
def save_contacts():
with open("contacts.txt", "w") as file:
for name, phone in contacts.items():
file.write(f"{name}: {phone}\n")
print("Contacts saved.")
while True:
print("\n1. Add Contact\n2. Search Contact\n3. Display Contacts\n4. Save & Exit")
choice = input("Enter choice: ")
if choice == "1":
add_contact()
elif choice == "2":
search_contact()
elif choice == "3":
display_contacts()
elif choice == "4":
save_contacts()
break
else:
print("Invalid choice. Try again.")
Explanation:
• A dictionary maps each contact name to a phone number.
• The user can add, search, and display contacts; results are saved to a file for persis-
tence.
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
68
100 Python Exercises
if choice == "C":
print(f"Temperature in Celsius: {fahrenheit_to_celsius(temp):.2f}°C")
elif choice == "F":
print(f"Temperature in Fahrenheit: {celsius_to_fahrenheit(temp):.2f}°F")
else:
print("Invalid choice.")
Explanation:
import random
while True:
guess = int(input("Guess a number (1-100): "))
attempts += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed it in {attempts} tries.")
break
Explanation:
tasks = []
def add_task():
task = input("Enter task: ")
69
100 Python Exercises
tasks.append(task)
print("Task added.")
def remove_task():
task = input("Enter task to remove: ")
if task in tasks:
tasks.remove(task)
print("Task removed.")
else:
print("Task not found.")
def display_tasks():
print("\nTo-Do List:")
for index, task in enumerate(tasks, start=1):
print(f"{index}. {task}")
while True:
print("\n1. Add Task\n2. Remove Task\n3. View Tasks\n4. Exit")
choice = input("Enter choice: ")
if choice == "1":
add_task()
elif choice == "2":
remove_task()
elif choice == "3":
display_tasks()
elif choice == "4":
break
else:
print("Invalid choice. Try again.")
Explanation:
balance = 0
def deposit():
global balance
amount = float(input("Enter deposit amount: "))
balance += amount
print(f"Deposited \${amount:.2f}. New balance: \${balance:.2f}")
70
100 Python Exercises
def withdraw():
global balance
amount = float(input("Enter withdrawal amount: "))
if amount > balance:
print("Insufficient funds.")
else:
balance -= amount
print(f"Withdrew \${amount:.2f}. New balance: \${balance:.2f}")
while True:
print("\n1. Deposit\n2. Withdraw\n3. Check Balance\n4. Exit")
choice = input("Enter choice: ")
if choice == "1":
deposit()
elif choice == "2":
withdraw()
elif choice == "3":
print(f"Current balance: \${balance:.2f}")
elif choice == "4":
break
else:
print("Invalid choice. Try again.")
Explanation:
• Showcases function scope and a global balance variable.
• Basic error handling for insufficient funds.
71
100 Python Exercises
Explanation:
• Demonstrates the use of a custom function calculate_bmi().
• The BMI interpretation uses basic conditional checks.
• Showcases floating-point operations and function usage.
def km_to_miles(km):
return km * 0.621371
def kg_to_lbs(kg):
return kg * 2.20462
print("1. KM to Miles")
print("2. KG to Lbs")
choice = input("Enter choice: ")
if choice == "1":
km = float(input("Enter value in KM: "))
print(f"Miles: {km_to_miles(km):.2f}")
elif choice == "2":
kg = float(input("Enter value in KG: "))
print(f"Lbs: {kg_to_lbs(kg):.2f}")
else:
print("Invalid choice.")
Explanation:
• Each conversion is encapsulated in its own function.
• Demonstrates how to structure code for various units.
72
100 Python Exercises
merger.append(pdf.strip())
merger.write(output)
merger.close()
Explanation:
• Demonstrates how to parse user input, handle file paths, and create a combined PDF.
import requests
def get_ip_info(ip):
url = f"http://ip-api.com/json/{ip}"
response = requests.get(url)
data = response.json()
if data["status"] == "success":
print(f"City: {data['city']}")
print(f"Region: {data['regionName']}")
print(f"Country: {data['country']}")
else:
print("Could not retrieve IP info.")
Explanation:
import random
73
100 Python Exercises
for _ in range(height):
row = ["#" if random.random() < 0.2 else " "] * width
maze.append(row)
return maze
def print_maze(maze):
for row in maze:
print("".join(row))
Explanation:
• Randomly places walls (”#”) vs. open spaces (” ”) with a 20 percentage chance.
def get_file_md5(filepath):
hasher = hashlib.md5()
with open(filepath, 'rb') as f:
buf = f.read()
hasher.update(buf)
return hasher.hexdigest()
def find_duplicates(directory):
hash_map = {}
74
100 Python Exercises
duplicates_found = False
for h, paths in result.items():
if len(paths) > 1:
duplicates_found = True
print(", ".join(paths))
if not duplicates_found:
print("No duplicates found.")
Explanation:
• Groups files by hash, printing only entries that appear more than once.
attendance = {}
def mark_attendance():
name = input("Enter student name: ")
attendance[name] = attendance.get(name, 0) + 1
print(f"{name}'s attendance marked.")
def view_attendance():
if not attendance:
print("No attendance records.")
else:
for student, count in attendance.items():
print(f"{student}: {count} days")
def reset_attendance():
attendance.clear()
print("All attendance records reset.")
75
100 Python Exercises
while True:
print("\n1. Mark Attendance\n2. View Attendance\n3. Reset Attendance\n4. Exit")
choice = input("Enter choice: ")
if choice == "1":
mark_attendance()
elif choice == "2":
view_attendance()
elif choice == "3":
reset_attendance()
elif choice == "4":
break
else:
print("Invalid choice. Try again.")
Explanation:
• Demonstrates using a dictionary to accumulate attendance counts.
• Each student is a key, incremented whenever attendance is marked.
# server.py
import socket
while True:
data = conn.recv(1024)
if not data:
break
print("Client:", data.decode())
reply = input("Server: ")
conn.sendall(reply.encode())
conn.close()
server_socket.close()
# client.py
76
100 Python Exercises
import socket
while True:
message = input("You: ")
if not message:
break
client_socket.sendall(message.encode())
data = client_socket.recv(1024)
print("Server:", data.decode())
client_socket.close()
Explanation:
• The server waits for incoming connections; the client sends messages.
• Both read and write from the socket until the user quits.
books = {"Python Basics": True, "Data Science": True, "AI Fundamentals": True}
def display_books():
print("\nAvailable Books:")
for book, available in books.items():
if available:
print(f"- {book}")
def borrow_book():
book = input("Enter book name: ")
if books.get(book, False):
books[book] = False
print("Book borrowed successfully!")
else:
print("Book not available.")
def return_book():
book = input("Enter book name: ")
if book in books:
books[book] = True
77
100 Python Exercises
while True:
print("\n1. View Books\n2. Borrow Book\n3. Return Book\n4. Exit")
choice = input("Enter choice: ")
if choice == "1":
display_books()
elif choice == "2":
borrow_book()
elif choice == "3":
return_book()
elif choice == "4":
break
else:
print("Invalid choice. Try again.")
Explanation:
votes = {}
voted_users = set()
def vote():
user = input("Enter your ID: ")
if user in voted_users:
print("You have already voted!")
else:
candidate = input("Vote for (Alice/Bob/Charlie): ")
votes[candidate] = votes.get(candidate, 0) + 1
voted_users.add(user)
print("Vote recorded!")
def results():
print("\nVoting Results:")
for candidate, count in votes.items():
print(f"{candidate}: {count} votes")
while True:
print("\n1. Vote\n2. Show Results\n3. Exit")
choice = input("Enter choice: ")
78
100 Python Exercises
if choice == "1":
vote()
elif choice == "2":
results()
elif choice == "3":
break
else:
print("Invalid choice. Try again.")
Explanation:
resume = f"""
-----------------------------
{name.upper()}
-----------------------------
Skills: {", ".join(skills)}
Experience: {experience} years
"""
print(resume)
Explanation:
def is_palindrome(text):
text = text.replace(" ", "").lower()
return text == text[::-1]
Explanation:
79
100 Python Exercises
import csv
try:
with open("sales.csv", "r") as file:
reader = csv.reader(file)
total_sales = sum(float(row[1]) for row in reader if row)
print(f"Total Sales: \${total_sales:.2f}")
except FileNotFoundError:
print("Error: CSV file not found.")
Explanation:
key = Fernet.generate_key()
cipher = Fernet(key)
def save_password():
site = input("Enter website: ")
password = input("Enter password: ")
encrypted_pw = cipher.encrypt(password.encode())
def view_passwords():
with open("passwords.txt", "r") as file:
print(file.read())
while True:
80
100 Python Exercises
if choice == "1":
save_password()
elif choice == "2":
view_passwords()
elif choice == "3":
break
else:
print("Invalid choice. Try again.")
Explanation:
• Stores the encrypted passwords in a text file; the key must be kept safe.
import random
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
Explanation:
• Uses a combination of ASCII letters, digits, and punctuation to produce a secure pass-
word.
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
81
100 Python Exercises
Explanation:
import requests
response = requests.get(url)
data = response.json()
if data["cod"] != "404":
weather = data["main"]
temperature = weather["temp"]
description = data["weather"][0]["description"]
print(f"Temperature: {temperature}°C")
print(f"Weather: {description.capitalize()}")
else:
print("City not found.")
Explanation:
import requests
82
100 Python Exercises
Explanation:
import nltk
from nltk.tokenize import sent_tokenize
nltk.download("punkt")
Explanation:
books = {
"Fiction": ["The Great Gatsby", "To Kill a Mockingbird"],
"Science": ["A Brief History of Time", "The Selfish Gene"],
"Technology": ["The Pragmatic Programmer", "Clean Code"]
}
83
100 Python Exercises
Explanation:
key = Fernet.generate_key()
cipher = Fernet(key)
def encrypt_file(filename):
with open(filename, "rb") as file:
data = file.read()
encrypted_data = cipher.encrypt(data)
with open(f"{filename}.enc", "wb") as file:
file.write(encrypted_data)
print("File encrypted.")
def decrypt_file(filename):
with open(filename, "rb") as file:
encrypted_data = file.read()
decrypted_data = cipher.decrypt(encrypted_data)
with open("decrypted.txt", "wb") as file:
file.write(decrypted_data)
print("File decrypted.")
encrypt_file("example.txt")
decrypt_file("example.txt.enc")
Explanation:
84
100 Python Exercises
import random
def generate_2fa_code():
return random.randint(100000, 999999)
code = generate_2fa_code()
print(f"Your 2FA Code: {code}")
Explanation:
employees = {}
def add_employee():
id = input("Enter employee ID: ")
name = input("Enter employee name: ")
position = input("Enter position: ")
employees[id] = {"Name": name, "Position": position}
print("Employee added.")
def list_employees():
for id, details in employees.items():
print(f"{id}: {details['Name']} - {details['Position']}")
while True:
print("\n1. Add Employee\n2. View Employees\n3. Exit")
choice = input("Enter choice: ")
if choice == "1":
add_employee()
elif choice == "2":
list_employees()
elif choice == "3":
break
else:
print("Invalid choice. Try again.")
85
100 Python Exercises
Explanation:
faqs = {
"What is Lkhibra Academy?": "Lkhibra Academy is an online learning platform.",
"What courses are available?": "Python, Data Science, AI, and more!",
"How do I enroll?": "Visit our website and sign up for a course."
}
while True:
question = input("Ask a question: ")
if question.lower() == "exit":
break
print(faqs.get(question, "Sorry, I don't understand that question."))
Explanation:
86
100 Python Exercises
file.write(invoice)
Explanation:
import time
Explanation:
• Maps each task to a delay (in seconds). In a real system, scheduling libraries or OS-
level notifications can be used.
import random
import string
urls = {}
def shorten_url(long_url):
short = ''.join(random.choices(string.ascii_letters + string.digits, k=6))
urls[short] = long_url
return short
Explanation:
87
100 Python Exercises
def analyze_sentiment(text):
words = set(text.lower().split())
if words & positive_words:
return "Positive Sentiment"
elif words & negative_words:
return "Negative Sentiment"
else:
return "Neutral Sentiment"
Explanation:
88