You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Congratulations — you have learned all the fundamental building blocks of Python! Now it is time to combine everything into real, working programs. In this final lesson, you will build three mini projects that use variables, data types, strings, control flow, loops, lists, dictionaries, functions, file handling, and exception handling.
A command-line application that lets you add, search, list, and delete contacts, with data saved to a JSON file.
import json
import os
CONTACTS_FILE = "contacts.json"
def load_contacts() -> list[dict]:
"""Load contacts from the JSON file."""
if not os.path.exists(CONTACTS_FILE):
return []
try:
with open(CONTACTS_FILE, "r") as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
print("Warning: Could not read contacts file. Starting fresh.")
return []
def save_contacts(contacts: list[dict]) -> None:
"""Save contacts to the JSON file."""
with open(CONTACTS_FILE, "w") as f:
json.dump(contacts, f, indent=2)
def add_contact(contacts: list[dict]) -> None:
"""Add a new contact."""
name = input("Name: ").strip()
if not name:
print("Name cannot be empty.")
return
phone = input("Phone: ").strip()
email = input("Email: ").strip()
# Check for duplicates
for contact in contacts:
if contact["name"].lower() == name.lower():
print(f"A contact named '{name}' already exists.")
return
contacts.append({
"name": name,
"phone": phone,
"email": email
})
save_contacts(contacts)
print(f"Contact '{name}' added successfully!")
def search_contacts(contacts: list[dict]) -> None:
"""Search contacts by name."""
query = input("Search: ").strip().lower()
results = [c for c in contacts if query in c["name"].lower()]
if results:
print(f"\nFound {len(results)} result(s):")
for c in results:
print(f" Name: {c['name']}")
print(f" Phone: {c['phone']}")
print(f" Email: {c['email']}")
print()
else:
print("No contacts found.")
def list_contacts(contacts: list[dict]) -> None:
"""List all contacts."""
if not contacts:
print("No contacts yet.")
return
print(f"\n{'Name':<20} {'Phone':<15} {'Email'}")
print("-" * 55)
for c in sorted(contacts, key=lambda x: x["name"]):
print(f"{c['name']:<20} {c['phone']:<15} {c['email']}")
def delete_contact(contacts: list[dict]) -> None:
"""Delete a contact by name."""
name = input("Name to delete: ").strip()
for i, c in enumerate(contacts):
if c["name"].lower() == name.lower():
contacts.pop(i)
save_contacts(contacts)
print(f"Deleted '{name}'.")
return
print(f"Contact '{name}' not found.")
def main():
"""Main application loop."""
contacts = load_contacts()
print("Contact Book")
print("=" * 30)
while True:
print("\nOptions: [a]dd [s]earch [l]ist [d]elete [q]uit")
choice = input("> ").strip().lower()
if choice == "a":
add_contact(contacts)
elif choice == "s":
search_contacts(contacts)
elif choice == "l":
list_contacts(contacts)
elif choice == "d":
delete_contact(contacts)
elif choice == "q":
print("Goodbye!")
break
else:
print("Invalid option. Try again.")
if __name__ == "__main__":
main()
while Trueif/elif/else.strip(), .lower() for input handlingA multiple-choice quiz with scoring, loaded from a dictionary:
import random
def create_quiz() -> list[dict]:
"""Define quiz questions."""
return [
{
"question": "What is the output of print(type(42))?",
"options": ["<class 'int'>", "<class 'float'>", "<class 'str'>", "<class 'number'>"],
"answer": 0
},
{
"question": "Which method removes the last element from a list?",
"options": ["remove()", "delete()", "pop()", "discard()"],
"answer": 2
},
{
"question": "What does 'len' stand for?",
"options": ["Length", "Lenient", "Lend", "Lengthy"],
"answer": 0
},
{
"question": "Which keyword defines a function in Python?",
"options": ["func", "function", "def", "define"],
"answer": 2
},
{
"question": "What is the result of 10 // 3?",
"options": ["3.33", "3", "4", "3.0"],
"answer": 1
},
{
"question": "Which data type is immutable?",
"options": ["list", "dict", "set", "tuple"],
"answer": 3
},
{
"question": "What does the 'in' keyword do?",
"options": [
"Creates a variable",
"Tests membership in a sequence",
"Imports a module",
"Defines a loop"
],
"answer": 1
},
{
"question": "What is the output of bool('')?",
"options": ["True", "False", "None", "Error"],
"answer": 1
},
]
def run_quiz(questions: list[dict]) -> tuple[int, int]:
"""Run the quiz and return (correct, total)."""
random.shuffle(questions)
correct = 0
total = len(questions)
for i, q in enumerate(questions, 1):
print(f"\nQuestion {i}/{total}: {q['question']}")
for j, option in enumerate(q["options"]):
print(f" {j + 1}. {option}")
while True:
try:
answer = int(input("Your answer (1-4): ")) - 1
if 0 <= answer <= 3:
break
print("Please enter 1, 2, 3, or 4.")
except ValueError:
print("Please enter a number.")
if answer == q["answer"]:
print("Correct!")
correct += 1
else:
print(f"Wrong! The answer was: {q['options'][q['answer']]}")
return correct, total
def main():
print("Python Quiz Game")
print("=" * 30)
questions = create_quiz()
correct, total = run_quiz(questions)
percentage = (correct / total) * 100
print(f"\nResults: {correct}/{total} ({percentage:.0f}%)")
if percentage == 100:
print("Perfect score!")
elif percentage >= 70:
print("Great job!")
elif percentage >= 50:
print("Not bad — keep practising!")
else:
print("Keep learning — you'll get there!")
if __name__ == "__main__":
main()
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.