โ† Python Fundamentals Level One ยท Lesson 4 of 5

Module Three

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
1

Course Outline

Python Programming Level 1 โ€“ Course Outline

๐Ÿ Fundamentals of Python Programming โ€” Level 1 โ€“ Course Outline

1. Module Title

Fundamentals of Python Programming โ€” Level 1: Your First Steps into Coding


2. Module Introduction

Welcome, young coder! Have you ever wanted to talk to computers and tell them what to do? Python is a programming language that is easy to learn and very powerful. It is used by scientists, game developers, web builders, and even astronauts! This course will take you from absolutely zero knowledge to writing your own Python programs. We will use simple words, fun examples, and lots of practice. By the end of this course, you will be able to write code, solve problems, and create small projects. Let's start your coding adventure!


3. Learning Objectives

After completing this course, you will be able to:

  • Understand what programming is and why Python is a great language.
  • Set up and use a Python development environment.
  • Write and run your first Python program.
  • Use variables to store and work with data.
  • Understand and use different data types (numbers, text, lists).
  • Make decisions with conditional statements (if/else).
  • Repeat tasks with loops (for and while).
  • Write simple functions to organise your code.
  • Handle user input and display output.
  • Work with lists and dictionaries to store collections of data.
  • Understand and fix errors (debugging).
  • Build a simple project using all the skills you learned.

4. Warm-up Story

Ada's First Code

Ada was 10 years old and loved solving puzzles. One day, her older brother showed her something amazing โ€“ a program that could greet people by name. He typed: print("Hello, Ada!") and the computer said "Hello, Ada!" Ada was amazed. She asked, "How did it do that?" Her brother said, "This is Python โ€“ a language you can use to talk to computers." Ada wanted to learn more. She started with simple commands, then learned about variables and loops. Soon, she was writing small games and solving math problems with code. Ada discovered that programming is like giving instructions to a very fast, very smart friend. And now, you can learn too!


5. Main Lessons

Lesson 1: What is Programming?

Definition: Programming is giving instructions to a computer to make it do what you want. These instructions are written in a programming language.

Why it's important: Programming lets you create games, websites, apps, and solve problems.

Simple explanation: Programming is like writing a recipe for a robot โ€“ you tell it exactly what to do, step by step.

Real-life example: A weather app uses programming to show you the forecast.

School example: A student writes code to calculate the average of test scores.

Home example: A parent programs a smart light to turn on at sunset.

Nigerian example: A Lagos startup uses programming to build a delivery app.

Illustration:

  +--------------------------------------------------+
  |  PROGRAMMING = GIVING INSTRUCTIONS TO COMPUTER   |
  |  +----------------------------------------------+ |
  |  |  CODE: print("Hello, World!")                | |
  |  |  COMPUTER OUTPUT: Hello, World!              | |
  |  +----------------------------------------------+ |
  +--------------------------------------------------+

Mini summary: Programming is writing instructions for computers to follow.


Lesson 2: What is Python?

Definition: Python is a programming language that is easy to read and write. It is one of the most popular languages in the world.

Why it's important: Python is used in web development, data science, artificial intelligence, and more.

Simple explanation: Python is like a friendly language that computers understand, and it's very beginner-friendly.

Real-life example: YouTube and Instagram use Python!

School example: Many schools teach Python as the first programming language.

Home example: You can use Python to automate tasks on your computer.

Nigerian example: Nigerian developers use Python to build web apps and data tools.

Illustration:

  +--------------------------------------------------+
  |  PYTHON IS...                                     |
  |  +----------------------------------------------+ |
  |  |  โœ… Easy to read                             | |
  |  |  โœ… Fun to write                             | |
  |  |  โœ… Very powerful                            | |
  |  |  โœ… Used by big companies                    | |
  |  +----------------------------------------------+ |
  +--------------------------------------------------+

Mini summary: Python is a popular, easy-to-learn programming language.


Lesson 3: Setting Up Python

Definition: Setting up Python means installing it on your computer so you can write and run Python programs.

Why it's important: You need Python installed to start coding.

Simple explanation: It's like installing a game before you can play it.

Real-life example: A developer installs Python on their laptop.

School example: A student installs Python on a school computer.

Home example: A parent installs Python for their child to learn coding.

Nigerian example: A Nigerian tech student installs Python for a project.

Illustration โ€“ Installation Steps:

  1. Go to python.org
  2. Click "Download Python"
  3. Run the installer
  4. Check "Add Python to PATH"
  5. Click "Install"
  6. Verify by typing: python --version in the terminal

Mini summary: Install Python from python.org to start coding.


Lesson 4: Your First Program โ€“ Hello, World!

Definition: "Hello, World!" is the traditional first program you write in any programming language.

Why it's important: It verifies that everything is set up correctly and introduces you to the basic structure of a program.

Simple explanation: It's like saying "hello" to the computer to make sure it's listening.

Real-life example: Every programmer starts with Hello, World!

School example: A student writes their first Hello, World! program.

Home example: A parent helps their child write their first code.

Nigerian example: A coding beginner in Lagos writes Hello, World!

Illustration โ€“ Code:

  print("Hello, World!")

Mini summary: "Hello, World!" is the first program every coder writes.


Lesson 5: Variables โ€“ Storing Information

Definition: A variable is like a box where you can store information. You give it a name and put a value inside.

Why it's important: Variables let you save data and use it later.

Simple explanation: A variable is like a labelled jar โ€“ you put something in and you can take it out later.

Real-life example: `name = "Chidi"` stores the name "Chidi" in the variable called `name`.

School example: `score = 85` stores the number 85 in the variable `score`.

Home example: `age = 10` stores your age.

Nigerian example: `city = "Lagos"` stores "Lagos" in the variable `city`.

Illustration โ€“ Code:

  name = "Ada"
  age = 10
  print(name)
  print(age)

Mini summary: Variables store information for later use.


Lesson 6: Data Types โ€“ Numbers and Text

Definition: Data types tell Python what kind of data a variable holds. The two most common are integers (whole numbers) and strings (text).

Why it's important: Different data types are used differently โ€“ you can do math with numbers, but not with text.

Simple explanation: Data types are like different kinds of toys โ€“ you play with each one differently.

Real-life example: `age = 10` (integer) vs `name = "Ada"` (string).

School example: `score = 90` (integer) and `subject = "Maths"` (string).

Home example: `temperature = 28` (integer) and `weather = "sunny"` (string).

Nigerian example: `price = 5000` (integer) and `currency = "Naira"` (string).

Illustration โ€“ Code:

  age = 10        # This is an integer (whole number)
  name = "Ada"    # This is a string (text)
  price = 5000    # This is an integer
  city = "Lagos"  # This is a string

Mini summary: Integers are whole numbers; strings are text.


Lesson 7: User Input โ€“ Asking Questions

Definition: User input lets you ask the user to type something, and your program can use that information.

Why it's important: It makes your program interactive!

Simple explanation: It's like asking a friend a question and using their answer.

Real-life example: A program asks for your name and greets you.

School example: A quiz program asks for the user's answer.

Home example: A recipe program asks how many people you are cooking for.

Nigerian example: A bank app asks for your PIN.

Illustration โ€“ Code:

  name = input("What is your name? ")
  print("Hello, " + name + "!")

Mini summary: `input()` lets you ask the user for information.


Lesson 8: Conditional Statements โ€“ Making Decisions (if, else)

Definition: Conditional statements let your program make decisions. `if` checks a condition, and `else` runs if the condition is false.

Why it's important: They let your program respond differently to different situations.

Simple explanation: It's like saying "If it's raining, take an umbrella; otherwise, wear sunglasses."

Real-life example: If a user enters the correct password, let them in; otherwise, say "Wrong password!"

School example: If a test score is above 50, print "Pass"; otherwise, print "Fail".

Home example: If it's cold, wear a jacket; otherwise, wear a t-shirt.

Nigerian example: If the price is above โ‚ฆ10,000, print "Expensive"; otherwise, print "Cheap".

Illustration โ€“ Code:

  age = int(input("How old are you? "))
  if age >= 18:
      print("You are an adult.")
  else:
      print("You are a child.")

Mini summary: `if` and `else` help your program make decisions.


Lesson 9: Loops โ€“ Repeating Code (while loop)

Definition: A while loop repeats a block of code as long as a condition is true.

Why it's important: It lets you repeat tasks without writing the same code over and over.

Simple explanation: It's like a song that repeats until you tell it to stop.

Real-life example: A game continues as long as the player has lives left.

School example: A program asks for a password until the correct one is entered.

Home example: A timer that counts down until it reaches zero.

Nigerian example: A POS machine asks for your PIN until it's correct.

Illustration โ€“ Code:

  count = 0
  while count < 5:
      print("Count is: " + str(count))
      count = count + 1

Mini summary: `while` loops repeat code as long as a condition is true.


Lesson 10: Loops โ€“ Repeating Code (for loop)

Definition: A for loop repeats code a set number of times โ€“ like going through a list.

Why it's important: It's used when you know how many times you want to repeat.

Simple explanation: It's like counting from 1 to 10.

Real-life example: A program prints each item in a shopping list.

School example: A program adds up numbers from 1 to 100.

Home example: A program prints the days of the week.

Nigerian example: A program lists all the states in Nigeria.

Illustration โ€“ Code:

  for number in range(1, 6):
      print(number)

Mini summary: `for` loops repeat code a specific number of times.


Lesson 11: Lists โ€“ Storing Many Items

Definition: A list is a collection of items. You can store multiple values in one variable.

Why it's important: Lists help you organise and manage multiple pieces of data.

Simple explanation: A list is like a basket with many fruits โ€“ you can put lots of things in one basket.

Real-life example: `fruits = ["Mango", "Orange", "Banana"]`

School example: `scores = [85, 90, 78, 92]`

Home example: `shopping = ["Milk", "Bread", "Eggs"]`

Nigerian example: `states = ["Lagos", "Abuja", "Kano"]`

Illustration โ€“ Code:

  fruits = ["Mango", "Orange", "Banana"]
  print(fruits[0])  # Prints "Mango"
  print(fruits[1])  # Prints "Orange"

Mini summary: Lists store multiple items in one variable.


Lesson 12: Functions โ€“ Reusable Code Blocks

Definition: A function is a block of code that you can reuse. You define it once and call it whenever you need it.

Why it's important: Functions help you organise your code and avoid repetition.

Simple explanation: A function is like a recipe โ€“ you write it once and can use it many times.

Real-life example: A function that calculates the area of a rectangle.

School example: A function that greets a user by name.

Home example: A function that converts temperature from Celsius to Fahrenheit.

Nigerian example: A function that converts Naira to Dollars.

Illustration โ€“ Code:

  def greet(name):
      print("Hello, " + name + "!")

  greet("Ada")   # Prints: Hello, Ada!
  greet("Chidi") # Prints: Hello, Chidi!

Mini summary: Functions are reusable code blocks.


Lesson 13: Comments โ€“ Explaining Your Code

Definition: Comments are notes in your code that Python ignores. They help you (and others) understand what your code does.

Why it's important: Comments make your code easier to read and understand.

Simple explanation: Comments are like sticky notes you leave for yourself.

Real-life example: `# This line prints a greeting`

School example: `# Calculate the average score`

Home example: `# Convert temperature`

Nigerian example: `# This function calculates tax`

Illustration โ€“ Code:

  # This is a comment
  print("Hello, World!")  # This prints a message

Mini summary: Comments are notes to explain your code.


Lesson 14: Debugging โ€“ Fixing Errors

Definition: Debugging is the process of finding and fixing errors in your code.

Why it's important: Every programmer makes mistakes โ€“ debugging helps you fix them.

Simple explanation: Debugging is like being a detective and finding clues to solve a mystery.

Real-life example: A programmer fixes a typo in their code.

School example: A student fixes a syntax error in their program.

Home example: A parent finds a missing colon in their code.

Nigerian example: A developer fixes a bug in a banking app.

Illustration โ€“ Common Errors:

  # Syntax Error: Missing colon
  if age >= 18
      print("Adult")  # Error! Missing colon after 18

  # Name Error: Variable not defined
  print(score)  # Error! score is not defined

  # Type Error: Wrong data type
  print("Your age is " + age)  # Error! age is an integer, not a string

Mini summary: Debugging is finding and fixing errors.


Lesson 15: Review โ€“ What We Learned

In this course, we learned:

  • What programming and Python are.
  • How to set up Python and write a "Hello, World!" program.
  • How to use variables to store data.
  • Data types (integers, strings).
  • How to get user input.
  • Conditional statements (if, else).
  • Loops (while and for).
  • Lists to store multiple items.
  • Functions to reuse code.
  • Comments and debugging.

You are now ready to start your coding journey!


6. Key Vocabulary

  • Programming: Writing instructions for computers.
  • Python: A popular programming language.
  • Variable: A container for storing data.
  • Integer: A whole number (e.g., 10, 25).
  • String: A piece of text (e.g., "Hello").
  • Input: Data given to a program by the user.
  • Output: Data displayed by a program.
  • Conditional: A statement that makes a decision (if/else).
  • Loop: Code that repeats.
  • List: A collection of items.
  • Function: A reusable block of code.
  • Comment: A note in the code.
  • Debugging: Fixing errors.

7. Important Concepts

  • Code is read by humans too: Write clean, understandable code with comments.
  • Practice is key: The more you code, the better you become.
  • Errors are okay: Every programmer makes mistakes โ€“ debugging is part of the process.
  • Start small: Build simple programs first and gradually add more features.
  • Have fun: Coding should be enjoyable!

8. Step-by-step Explanations

How to write a simple program:

  1. Open your code editor or IDE.
  2. Type your code.
  3. Save the file with a `.py` extension.
  4. Run the program by typing `python filename.py` in the terminal.
  5. See the output and debug if needed.

9. Real-life Examples

  • A program that calculates your age based on your birth year.
  • A program that converts currency.
  • A program that checks if a number is even or odd.
  • A program that asks for your name and greets you.
  • A program that calculates the total price of items.

10. Nigerian Examples

  • A program that converts Naira to Dollars.
  • A program that lists all the states in Nigeria.
  • A program that calculates the total cost of items in a Lagos market.
  • A program that checks if someone is eligible to vote in Nigeria.
  • A program that greets you in Yoruba, Hausa, or Igbo.

11. Fun Examples Children Can Relate To

  • A program that asks for your favourite cartoon and says "I like that too!"
  • A program that counts down from 10 to 1 and says "Blast off!"
  • A program that asks for your age and says "You are X years old!"
  • A program that stores your favourite foods in a list and prints them.
  • A program that tells a joke.

12. Everyday Examples

  • ๐Ÿ“ฑ A calculator app.
  • ๐Ÿ“ A to-do list manager.
  • ๐Ÿ“… A birthday reminder.
  • ๐Ÿ›’ A shopping list.
  • ๐Ÿ“Š A grade calculator.

13. Teacher Notes

Start with simple examples and gradually increase complexity. Encourage students to type code themselves, not just copy. Use pair programming โ€“ let students work together. Celebrate small successes. Use Nigerian examples to make learning relatable. Emphasise that errors are a natural part of learning.


14. Parent Tips

Help your child set up Python. Sit with them as they write their first programs. Ask questions like "What do you think this code does?" and "What happens if you change this number?" Encourage curiosity and experimentation. Celebrate their progress and don't worry about mistakes โ€“ they are learning!


15. Interesting Facts

  • ๐Ÿ Python was named after the TV show Monty Python's Flying Circus, not the snake!
  • ๐Ÿ“Š Python is used by Google, NASA, and Instagram.
  • ๐ŸŽฎ Many popular games use Python for scripting.
  • ๐Ÿ’ก Python was created by Guido van Rossum in 1991.
  • ๐ŸŒ Python is one of the most popular languages in the world.

16. Did You Know?

  • Python is used by data scientists to analyse large amounts of data.
  • Python can be used to create artificial intelligence and machine learning models.
  • Python is a great first language because it reads like English.
  • You can build websites with Python using frameworks like Django and Flask.
  • Python is used by Nigerian tech companies and startups.

17. Remember This

  • โœ… Python is a programming language.
  • โœ… Variables store data.
  • โœ… Strings are text, integers are numbers.
  • โœ… `input()` gets user input.
  • โœ… `if/else` makes decisions.
  • โœ… Loops repeat code.
  • โœ… Lists store multiple items.
  • โœ… Functions reuse code.

18. Common Mistakes

  • โŒ Forgetting colons `:` after `if`, `else`, `while`, and `for`.
  • โŒ Forgetting to indent code (Python uses indentation).
  • โŒ Mixing data types โ€“ e.g., adding a string to an integer.
  • โŒ Using `=` for comparison instead of `==`.
  • โŒ Not closing parentheses or quotes.

19. Best Practices

  • โœ… Use meaningful variable names (e.g., `age`, `name`).
  • โœ… Add comments to explain your code.
  • โœ… Use consistent indentation (4 spaces is standard).
  • โœ… Test your code frequently.
  • โœ… Start small and add features gradually.

20. Illustrations

Python Setup Flowchart

  +-------------+     +-------------+     +-------------+     +-------------+
  |  GO TO      | --> |  DOWNLOAD   | --> |  RUN        | --> |  TEST WITH  |
  |  PYTHON.ORG |     |  INSTALLER  |     |  INSTALLER  |     |  "python --version" |
  +-------------+     +-------------+     +-------------+     +-------------+

Comparison Table โ€“ Data Types

Data TypeWhat It IsExample
IntegerWhole number10, 25, 100
StringText"Hello", "Ada"
FloatDecimal number3.14, 2.5
BooleanTrue/FalseTrue, False
ListCollection of items[1, 2, 3]

Comparison Table โ€“ Loops

Loop TypeWhen to UseExample
whileWhen you don't know how many times`while count < 5:`
forWhen you know how many times`for i in range(5):`

Comparison Table โ€“ Conditional Statements

StatementWhen it RunsExample
ifWhen condition is true`if age >= 18:`
elseWhen condition is false`else:`
elifWhen first condition is false and another is true`elif age >= 13:`

Timeline โ€“ Course Learning Path

  +------------------------------------------------------------------+
  |  Lesson 1: What is Programming?                                  |
  |  Lesson 2: What is Python?                                      |
  |  Lesson 3: Setting Up Python                                    |
  |  Lesson 4: Your First Program โ€“ Hello, World!                   |
  |  Lesson 5: Variables โ€“ Storing Information                      |
  |  Lesson 6: Data Types โ€“ Numbers and Text                        |
  |  Lesson 7: User Input โ€“ Asking Questions                        |
  |  Lesson 8: Conditional Statements โ€“ Making Decisions (if, else) |
  |  Lesson 9: Loops โ€“ Repeating Code (while loop)                  |
  |  Lesson 10: Loops โ€“ Repeating Code (for loop)                   |
  |  Lesson 11: Lists โ€“ Storing Many Items                          |
  |  Lesson 12: Functions โ€“ Reusable Code Blocks                    |
  |  Lesson 13: Comments โ€“ Explaining Your Code                     |
  |  Lesson 14: Debugging โ€“ Fixing Errors                           |
  |  Lesson 15: Review                                              |
  +------------------------------------------------------------------+

23. End-of-Module Summary

In this course, we have taken our first steps into the world of Python programming. We learned what programming is and why Python is a great language to start with. We set up Python on our computers and wrote our first "Hello, World!" program. We learned about variables, data types, user input, conditional statements, loops, lists, and functions. We also learned about comments and debugging. You now have a solid foundation in Python programming. Remember, the key to learning programming is practice โ€“ keep coding, keep exploring, and have fun!


24. Frequently Asked Questions

  1. What is Python? A popular programming language that is easy to learn.
  2. Do I need to know math to learn Python? Basic math is helpful, but you don't need to be a math expert.
  3. What can I build with Python? Games, websites, data tools, and much more.
  4. Is Python free? Yes, Python is free and open source.
  5. What is a variable? A container for storing data.
  6. What is a string? A piece of text.
  7. What is a loop? Code that repeats.
  8. What is a function? A reusable block of code.
  9. What is debugging? Finding and fixing errors.
  10. Where can I learn more Python? Practice, online tutorials, and courses!

25. Review Questions

  1. What is programming?
  2. What is Python?
  3. How do you set up Python?
  4. What is the "Hello, World!" program?
  5. What is a variable?
  6. What is an integer?
  7. What is a string?
  8. How do you get user input?
  9. What does `if/else` do?
  10. What is a while loop?
  11. What is a for loop?
  12. What is a list?
  13. What is a function?
  14. What is a comment?
  15. What is debugging?

26. Fill-in-the-Blank

  1. _____ is writing instructions for computers. (Programming)
  2. _____ is a popular programming language. (Python)
  3. A _____ stores data. (variable)
  4. An _____ is a whole number. (integer)
  5. A _____ is a piece of text. (string)
  6. `_____` gets user input. (input())
  7. `_____` makes decisions. (if)
  8. A _____ loop repeats code. (while)
  9. A _____ is a collection of items. (list)
  10. A _____ is a reusable block of code. (function)

27. True or False

  1. Python is a programming language. (True)
  2. Variables store data. (True)
  3. An integer is text. (False โ€“ it's a number)
  4. A string is a number. (False โ€“ it's text)
  5. `input()` asks the user for information. (True)
  6. `if` makes decisions. (True)
  7. A while loop runs forever. (False โ€“ it runs while a condition is true)
  8. A for loop repeats code a specific number of times. (True)
  9. A list can store multiple items. (True)
  10. A function is not reusable. (False โ€“ it is reusable)

28. Multiple Choice Questions

  1. What is Python?
    A) A game B) A programming language C) A food D) A car Answer: B
  2. What is a variable?
    A) A container for data B) A game C) A food D) A car Answer: A
  3. What is an integer?
    A) A whole number B) A piece of text C) A list D) A function Answer: A
  4. What is a string?
    A) A piece of text B) A whole number C) A list D) A function Answer: A
  5. What does `input()` do?
    A) Gets user input B) Prints output C) Makes a decision D) Repeats code Answer: A
  6. What does `if` do?
    A) Makes a decision B) Repeats code C) Stores data D) Gets user input Answer: A
  7. What is a while loop?
    A) Repeats code while a condition is true B) Repeats code a set number of times C) Stores data D) Makes a decision Answer: A
  8. What is a for loop?
    A) Repeats code a set number of times B) Repeats code while a condition is true C) Stores data D) Makes a decision Answer: A
  9. What is a list?
    A) A collection of items B) A piece of text C) A whole number D) A function Answer: A
  10. What is a function?
    A) A reusable block of code B) A collection of items C) A piece of text D) A whole number Answer: A
  11. What is a comment?
    A) A note in the code B) A variable C) A loop D) A function Answer: A
  12. What is debugging?
    A) Fixing errors B) Writing code C) Storing data D) Making decisions Answer: A
  13. Which is a Nigerian example?
    A) A program converting Naira to Dollars B) A program in London C) A program in New York D) A program in Tokyo Answer: A
  14. Is Python free?
    A) Yes B) No Answer: A
  15. Can you build games with Python?
    A) Yes B) No Answer: A

29. Matching Exercises

TermDefinition
PythonA) Stores multiple items
VariableB) Reusable block of code
ListC) Programming language
FunctionD) Container for data
CommentE) Note in the code

Answers: Python-C, Variable-D, List-A, Function-B, Comment-E


30. Short Answer Questions

  1. What is Python?
  2. What is a variable?
  3. What is the difference between an integer and a string?
  4. What does `if/else` do?
  5. What is a loop?
  6. What is a list?
  7. What is a function?

31. Scenario-based Exercises

Scenario 1: You want to write a program that asks the user for their name and age, then prints a message saying "Hello, [name]! You are [age] years old."

Task: Write the code to do this.

Answer:

  name = input("What is your name? ")
  age = input("How old are you? ")
  print("Hello, " + name + "! You are " + age + " years old.")

Scenario 2: You want to write a program that checks if a number is even or odd.

Task: Write the code to do this.

Answer:

  number = int(input("Enter a number: "))
  if number % 2 == 0:
      print(number, "is even.")
  else:
      print(number, "is odd.")

32. Group Activity

In groups of three, write a program that asks each group member for their name and favourite food. Store the names and foods in lists. Then, print a message like "Ada likes Jollof Rice." Share your program with the class.


33. Individual Activity

Write a program that asks the user for a number and prints the multiplication table for that number (from 1 to 10).


34. Classroom Discussion Questions

  • What is the most interesting thing you learned about Python?
  • What program would you like to build with Python?
  • How can Python help Nigerian businesses?
  • What is one challenge you faced when learning Python?
  • How do you fix errors in your code?

35. Mini Project

Build a simple "Quiz Game" program. The program should:

  1. Ask the user 5 multiple-choice questions.
  2. Check if the answers are correct.
  3. Keep score and display the final score at the end.

36. Practical Assignment

Write a program that acts as a simple calculator. It should:

  1. Ask the user for two numbers.
  2. Ask the user for an operation (+, -, *, /).
  3. Perform the calculation and print the result.

37. Challenge Exercise

Write a program that stores the names and scores of 5 students. Then, calculate and print the average score, the highest score, and the lowest score. Also, print the name of the student with the highest score.


38. Quiz Answers

Fill-in-the-blank: 1. Programming, 2. Python, 3. variable, 4. integer, 5. string, 6. input(), 7. if, 8. while, 9. list, 10. function

True/False: 1T, 2T, 3F, 4F, 5T, 6T, 7F, 8T, 9T, 10F

Multiple Choice: 1B, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A, 10A, 11A, 12A, 13A, 14A, 15A

Matching: Python-C, Variable-D, List-A, Function-B, Comment-E


39. Key Takeaways

  • ๐Ÿ”น Python is a beginner-friendly programming language.
  • ๐Ÿ”น Variables store data for later use.
  • ๐Ÿ”น Data types include integers (numbers) and strings (text).
  • ๐Ÿ”น `if/else` statements make decisions.
  • ๐Ÿ”น Loops (`while` and `for`) repeat code.
  • ๐Ÿ”น Lists store collections of items.
  • ๐Ÿ”น Functions are reusable code blocks.
  • ๐Ÿ”น Comments explain your code.
  • ๐Ÿ”น Debugging is fixing errors.
  • ๐Ÿ”น Practice is the key to becoming a great programmer.

40. Preparation for the Next Module

In Level 2, we will build on what you have learned. You will explore more advanced topics like:

  • Working with dictionaries and sets.
  • File input and output (reading/writing files).
  • Error handling with `try/except`.
  • Writing more complex functions.
  • Introduction to object-oriented programming.
  • Building larger projects.

Keep practicing and exploring. You are on your way to becoming a Python expert!


๐ŸŽ‰ Congratulations! You have completed the Fundamentals of Python Programming โ€” Level 1 course outline! ๐ŸŽ‰

You are now ready for Level 2 โ€“ Advanced Python Concepts!

2

Module One

Module 1 ยท Python Programming Level 1

๐Ÿ Module One: Welcome to Python Programming โ€“ Your First Steps into Coding

1. Module Title

Module One: Welcome to Python Programming โ€“ Your First Steps into Coding


2. Module Introduction

Hello, young coder! Welcome to the wonderful world of programming. Have you ever wanted to make a computer do what you want? Have you ever wondered how video games, apps, and websites are made? The secret is programming โ€“ and Python is one of the best languages to start with.

Python is a programming language that is easy to read, easy to write, and very powerful. It is used by scientists, game developers, web builders, and even astronauts! In this first module, we will start from the very beginning. We will learn what programming is, why Python is so popular, and how to write our very first programs. We will use simple words, fun examples, and lots of practice. By the end of this module, you will be able to write your own Python programs and understand the basic building blocks of coding. Let's start your coding adventure!


3. Learning Objectives

After completing this module, you will be able to:

  • Explain what programming is and why Python is a great language.
  • Set up and use a Python development environment on your computer.
  • Write and run your very first Python program โ€“ "Hello, World!"
  • Use variables to store and work with data.
  • Understand and use different data types (numbers, text, decimals).
  • Ask the user for input and display output.
  • Make decisions with conditional statements (if and else).
  • Repeat tasks with loops (while and for).
  • Store many items in a list and work with them.
  • Write simple functions to organise your code.
  • Understand and fix errors (debugging).

4. Warm-up Story

Ada's First Code

Ada was 10 years old and loved solving puzzles. One day, her older brother showed her something amazing โ€“ a program that could greet people by name. He typed: print("Hello, Ada!") and the computer said "Hello, Ada!" Ada was amazed. She asked, "How did it do that?" Her brother said, "This is Python โ€“ a language you can use to talk to computers."

Ada wanted to learn more. She started with simple commands, then learned about variables and loops. She wrote a program that asked for her name and said "Hello" back. She was so proud! Soon, she was writing small games and solving math problems with code. Ada discovered that programming is like giving instructions to a very fast, very smart friend. And now, you can learn too!


5. Main Lessons

Lesson 1: What is Programming?

Definition: Programming is giving instructions to a computer to make it do what you want. These instructions are written in a programming language.

Why it's important: Programming lets you create games, websites, apps, and solve problems. It is like having a superpower!

Simple explanation: Programming is like writing a recipe for a robot โ€“ you tell it exactly what to do, step by step.

Real-life example: A weather app uses programming to show you the forecast.

School example: A student writes code to calculate the average of test scores.

Home example: A parent programs a smart light to turn on at sunset.

Nigerian example: A Lagos startup uses programming to build a delivery app.

Illustration:

  +--------------------------------------------------+
  |  PROGRAMMING = GIVING INSTRUCTIONS TO COMPUTER   |
  |  +----------------------------------------------+ |
  |  |  CODE: print("Hello, World!")                | |
  |  |  COMPUTER OUTPUT: Hello, World!              | |
  |  +----------------------------------------------+ |
  +--------------------------------------------------+

Mini summary: Programming is writing instructions for computers to follow.


Lesson 2: What is Python?

Definition: Python is a programming language that is easy to read and write. It is one of the most popular languages in the world.

Why it's important: Python is used in web development, data science, artificial intelligence, and more. It is a great first language to learn.

Simple explanation: Python is like a friendly language that computers understand, and it's very beginner-friendly.

Real-life example: YouTube and Instagram use Python!

School example: Many schools teach Python as the first programming language.

Home example: You can use Python to automate tasks on your computer.

Nigerian example: Nigerian developers use Python to build web apps and data tools.

Illustration:

  +--------------------------------------------------+
  |  PYTHON IS...                                     |
  |  +----------------------------------------------+ |
  |  |  โœ… Easy to read                             | |
  |  |  โœ… Fun to write                             | |
  |  |  โœ… Very powerful                            | |
  |  |  โœ… Used by big companies                    | |
  |  |  โœ… Beginner-friendly                        | |
  |  +----------------------------------------------+ |
  +--------------------------------------------------+

Mini summary: Python is a popular, easy-to-learn programming language.


Lesson 3: Setting Up Python

Definition: Setting up Python means installing it on your computer so you can write and run Python programs.

Why it's important: You need Python installed to start coding.

Simple explanation: It's like installing a game before you can play it.

Real-life example: A developer installs Python on their laptop.

School example: A student installs Python on a school computer.

Home example: A parent installs Python for their child to learn coding.

Nigerian example: A Nigerian tech student installs Python for a project.

Illustration โ€“ Installation Steps:

  1. Go to python.org
  2. Click "Download Python"
  3. Run the installer
  4. Check "Add Python to PATH"
  5. Click "Install"
  6. Verify by typing: python --version in the terminal

Mini summary: Install Python from python.org to start coding.


Lesson 4: Your First Program โ€“ Hello, World!

Definition: "Hello, World!" is the traditional first program you write in any programming language.

Why it's important: It verifies that everything is set up correctly and introduces you to the basic structure of a program.

Simple explanation: It's like saying "hello" to the computer to make sure it's listening.

Real-life example: Every programmer starts with Hello, World!

School example: A student writes their first Hello, World! program.

Home example: A parent helps their child write their first code.

Nigerian example: A coding beginner in Lagos writes Hello, World!

Illustration โ€“ Code:

  print("Hello, World!")

Mini summary: "Hello, World!" is the first program every coder writes.


Lesson 5: Variables โ€“ Storing Information

Definition: A variable is like a box where you can store information. You give it a name and put a value inside.

Why it's important: Variables let you save data and use it later.

Simple explanation: A variable is like a labelled jar โ€“ you put something in and you can take it out later.

Real-life example: name = "Chidi" stores the name "Chidi" in the variable called name.

School example: score = 85 stores the number 85 in the variable score.

Home example: age = 10 stores your age.

Nigerian example: city = "Lagos" stores "Lagos" in the variable city.

Illustration โ€“ Code:

  name = "Ada"
  age = 10
  print(name)
  print(age)

Mini summary: Variables store information for later use.


Lesson 6: Data Types โ€“ Numbers and Text

Definition: Data types tell Python what kind of data a variable holds. The most common are integers (whole numbers), floats (decimal numbers), and strings (text).

Why it's important: Different data types are used differently โ€“ you can do math with numbers, but not with text.

Simple explanation: Data types are like different kinds of toys โ€“ you play with each one differently.

Real-life example: age = 10 (integer) vs name = "Ada" (string).

School example: score = 90 (integer) and subject = "Maths" (string).

Home example: temperature = 28 (integer) and weather = "sunny" (string).

Nigerian example: price = 5000 (integer) and currency = "Naira" (string).

Illustration โ€“ Code:

  age = 10        # This is an integer (whole number)
  price = 2500.50 # This is a float (decimal number)
  name = "Ada"    # This is a string (text)
  city = "Lagos"  # This is a string

Mini summary: Integers are whole numbers, floats are decimals, and strings are text.


Lesson 7: Getting User Input

Definition: User input lets you ask the user to type something, and your program can use that information.

Why it's important: It makes your program interactive!

Simple explanation: It's like asking a friend a question and using their answer.

Real-life example: A program asks for your name and greets you.

School example: A quiz program asks for the user's answer.

Home example: A recipe program asks how many people you are cooking for.

Nigerian example: A bank app asks for your PIN.

Illustration โ€“ Code:

  name = input("What is your name? ")
  print("Hello, " + name + "!")

Mini summary: input() lets you ask the user for information.


Lesson 8: Conditional Statements โ€“ Making Decisions (if, else)

Definition: Conditional statements let your program make decisions. if checks a condition, and else runs if the condition is false.

Why it's important: They let your program respond differently to different situations.

Simple explanation: It's like saying "If it's raining, take an umbrella; otherwise, wear sunglasses."

Real-life example: If a user enters the correct password, let them in; otherwise, say "Wrong password!"

School example: If a test score is above 50, print "Pass"; otherwise, print "Fail".

Home example: If it's cold, wear a jacket; otherwise, wear a t-shirt.

Nigerian example: If the price is above โ‚ฆ10,000, print "Expensive"; otherwise, print "Cheap".

Illustration โ€“ Code:

  age = int(input("How old are you? "))
  if age >= 18:
      print("You are an adult.")
  else:
      print("You are a child.")

Mini summary: if and else help your program make decisions.


Lesson 9: Loops โ€“ Repeating Code (while loop)

Definition: A while loop repeats a block of code as long as a condition is true.

Why it's important: It lets you repeat tasks without writing the same code over and over.

Simple explanation: It's like a song that repeats until you tell it to stop.

Real-life example: A game continues as long as the player has lives left.

School example: A program asks for a password until the correct one is entered.

Home example: A timer that counts down until it reaches zero.

Nigerian example: A POS machine asks for your PIN until it's correct.

Illustration โ€“ Code:

  count = 0
  while count < 5:
      print("Count is: " + str(count))
      count = count + 1

Mini summary: while loops repeat code as long as a condition is true.


Lesson 10: Loops โ€“ Repeating Code (for loop)

Definition: A for loop repeats code a set number of times โ€“ like going through a list.

Why it's important: It's used when you know how many times you want to repeat.

Simple explanation: It's like counting from 1 to 10.

Real-life example: A program prints each item in a shopping list.

School example: A program adds up numbers from 1 to 100.

Home example: A program prints the days of the week.

Nigerian example: A program lists all the states in Nigeria.

Illustration โ€“ Code:

  for number in range(1, 6):
      print(number)

Mini summary: for loops repeat code a specific number of times.


Lesson 11: Lists โ€“ Storing Many Items

Definition: A list is a collection of items. You can store multiple values in one variable.

Why it's important: Lists help you organise and manage multiple pieces of data.

Simple explanation: A list is like a basket with many fruits โ€“ you can put lots of things in one basket.

Real-life example: fruits = ["Mango", "Orange", "Banana"]

School example: scores = [85, 90, 78, 92]

Home example: shopping = ["Milk", "Bread", "Eggs"]

Nigerian example: states = ["Lagos", "Abuja", "Kano"]

Illustration โ€“ Code:

  fruits = ["Mango", "Orange", "Banana"]
  print(fruits[0])  # Prints "Mango"
  print(fruits[1])  # Prints "Orange"

Mini summary: Lists store multiple items in one variable.


Lesson 12: Functions โ€“ Reusable Code Blocks

Definition: A function is a block of code that you can reuse. You define it once and call it whenever you need it.

Why it's important: Functions help you organise your code and avoid repetition.

Simple explanation: A function is like a recipe โ€“ you write it once and can use it many times.

Real-life example: A function that calculates the area of a rectangle.

School example: A function that greets a user by name.

Home example: A function that converts temperature from Celsius to Fahrenheit.

Nigerian example: A function that converts Naira to Dollars.

Illustration โ€“ Code:

  def greet(name):
      print("Hello, " + name + "!")

  greet("Ada")   # Prints: Hello, Ada!
  greet("Chidi") # Prints: Hello, Chidi!

Mini summary: Functions are reusable code blocks.


Lesson 13: Comments โ€“ Explaining Your Code

Definition: Comments are notes in your code that Python ignores. They help you (and others) understand what your code does.

Why it's important: Comments make your code easier to read and understand.

Simple explanation: Comments are like sticky notes you leave for yourself.

Real-life example: # This line prints a greeting

School example: # Calculate the average score

Home example: # Convert temperature

Nigerian example: # This function calculates tax

Illustration โ€“ Code:

  # This is a comment
  print("Hello, World!")  # This prints a message

Mini summary: Comments are notes to explain your code.


Lesson 14: Debugging โ€“ Fixing Errors

Definition: Debugging is the process of finding and fixing errors in your code.

Why it's important: Every programmer makes mistakes โ€“ debugging helps you fix them.

Simple explanation: Debugging is like being a detective and finding clues to solve a mystery.

Real-life example: A programmer fixes a typo in their code.

School example: A student fixes a syntax error in their program.

Home example: A parent finds a missing colon in their code.

Nigerian example: A developer fixes a bug in a banking app.

Illustration โ€“ Common Errors:

  # Syntax Error: Missing colon
  if age >= 18
      print("Adult")  # Error! Missing colon after 18

  # Name Error: Variable not defined
  print(score)  # Error! score is not defined

  # Type Error: Wrong data type
  print("Your age is " + age)  # Error! age is an integer, not a string

Mini summary: Debugging is finding and fixing errors.


Lesson 15: Review โ€“ What We Learned in Module One

In this module, we learned:

  • What programming is and why Python is a great language.
  • How to set up Python and write a "Hello, World!" program.
  • How to use variables to store data.
  • Data types (integers, floats, strings).
  • How to get user input with input().
  • Conditional statements (if/else) to make decisions.
  • Loops (while and for) to repeat code.
  • Lists to store multiple items.
  • Functions to reuse code.
  • Comments and debugging.

You are now ready to continue your Python journey!


6. Key Vocabulary

  • Programming: Writing instructions for computers.
  • Python: A popular programming language.
  • Variable: A container for storing data.
  • Integer: A whole number (e.g., 10, 25).
  • Float: A decimal number (e.g., 3.14, 2.5).
  • String: A piece of text (e.g., "Hello").
  • Input: Data given to a program by the user.
  • Output: Data displayed by a program.
  • Conditional: A statement that makes a decision (if/else).
  • Loop: Code that repeats.
  • List: A collection of items.
  • Function: A reusable block of code.
  • Comment: A note in the code.
  • Debugging: Fixing errors.

7. Important Concepts

  • Code is read by humans too: Write clean, understandable code with comments.
  • Practice is key: The more you code, the better you become.
  • Errors are okay: Every programmer makes mistakes โ€“ debugging is part of the process.
  • Start small: Build simple programs first and gradually add more features.
  • Have fun: Coding should be enjoyable!

8. Step-by-step Explanations

How to write and run a Python program:

  1. Open your code editor (like IDLE, VS Code, or any text editor).
  2. Type your Python code.
  3. Save the file with a .py extension (e.g., hello.py).
  4. Open a terminal or command prompt.
  5. Navigate to the folder where you saved the file.
  6. Type python filename.py and press Enter.
  7. See the output and debug if needed.

9. Real-life Examples

  • A program that calculates your age based on your birth year.
  • A program that converts currency.
  • A program that checks if a number is even or odd.
  • A program that asks for your name and greets you.
  • A program that calculates the total price of items.

10. Nigerian Examples

  • A program that converts Naira to Dollars.
  • A program that lists all the states in Nigeria.
  • A program that calculates the total cost of items in a Lagos market.
  • A program that checks if someone is eligible to vote in Nigeria.
  • A program that greets you in Yoruba, Hausa, or Igbo.

11. Fun Examples Children Can Relate To

  • A program that asks for your favourite cartoon and says "I like that too!"
  • A program that counts down from 10 to 1 and says "Blast off!"
  • A program that asks for your age and says "You are X years old!"
  • A program that stores your favourite foods in a list and prints them.
  • A program that tells a joke.

12. Everyday Examples

  • ๐Ÿ“ฑ A calculator app.
  • ๐Ÿ“ A to-do list manager.
  • ๐Ÿ“… A birthday reminder.
  • ๐Ÿ›’ A shopping list.
  • ๐Ÿ“Š A grade calculator.

13. Teacher Notes

Start with simple examples and gradually increase complexity. Encourage students to type code themselves, not just copy. Use pair programming โ€“ let students work together. Celebrate small successes. Use Nigerian examples to make learning relatable. Emphasise that errors are a natural part of learning.


14. Parent Tips

Help your child set up Python. Sit with them as they write their first programs. Ask questions like "What do you think this code does?" and "What happens if you change this number?" Encourage curiosity and experimentation. Celebrate their progress and don't worry about mistakes โ€“ they are learning!


15. Interesting Facts

  • ๐Ÿ Python was named after the TV show Monty Python's Flying Circus, not the snake!
  • ๐Ÿ“Š Python is used by Google, NASA, and Instagram.
  • ๐ŸŽฎ Many popular games use Python for scripting.
  • ๐Ÿ’ก Python was created by Guido van Rossum in 1991.
  • ๐ŸŒ Python is one of the most popular languages in the world.

16. Did You Know?

  • Python is used by data scientists to analyse large amounts of data.
  • Python can be used to create artificial intelligence and machine learning models.
  • Python is a great first language because it reads like English.
  • You can build websites with Python using frameworks like Django and Flask.
  • Python is used by Nigerian tech companies and startups.

17. Remember This

  • โœ… Python is a programming language.
  • โœ… Variables store data.
  • โœ… Strings are text, integers are whole numbers, floats are decimals.
  • โœ… input() gets user input.
  • โœ… if/else makes decisions.
  • โœ… Loops repeat code.
  • โœ… Lists store multiple items.
  • โœ… Functions reuse code.
  • โœ… Comments explain code.
  • โœ… Debugging fixes errors.

18. Common Mistakes

  • โŒ Forgetting colons : after if, else, while, and for.
  • โŒ Forgetting to indent code (Python uses indentation).
  • โŒ Mixing data types โ€“ e.g., adding a string to an integer.
  • โŒ Using = for comparison instead of ==.
  • โŒ Not closing parentheses or quotes.

19. Best Practices

  • โœ… Use meaningful variable names (e.g., age, name).
  • โœ… Add comments to explain your code.
  • โœ… Use consistent indentation (4 spaces is standard).
  • โœ… Test your code frequently.
  • โœ… Start small and add features gradually.

20. Illustrations

Python Setup Flowchart

  +-------------+     +-------------+     +-------------+     +-------------+
  |  GO TO      | --> |  DOWNLOAD   | --> |  RUN        | --> |  TEST WITH  |
  |  PYTHON.ORG |     |  INSTALLER  |     |  INSTALLER  |     |  "python --version" |
  +-------------+     +-------------+     +-------------+     +-------------+

Comparison Table โ€“ Data Types

Data TypeWhat It IsExample
IntegerWhole number10, 25, 100
FloatDecimal number3.14, 2.5, 0.99
StringText"Hello", "Ada", "Lagos"
BooleanTrue/FalseTrue, False
ListCollection of items[1, 2, 3]

Comparison Table โ€“ Loops

Loop TypeWhen to UseExample
whileWhen you don't know how many timeswhile count < 5:
forWhen you know how many timesfor i in range(5):

Comparison Table โ€“ Conditional Statements

StatementWhen it RunsExample
ifWhen condition is trueif age >= 18:
elseWhen condition is falseelse:
elifWhen first condition is false and another is trueelif age >= 13:

Timeline โ€“ Module One Learning Path

  +------------------------------------------------------------------+
  |  Lesson 1: What is Programming?                                  |
  |  Lesson 2: What is Python?                                      |
  |  Lesson 3: Setting Up Python                                    |
  |  Lesson 4: Your First Program โ€“ Hello, World!                   |
  |  Lesson 5: Variables โ€“ Storing Information                      |
  |  Lesson 6: Data Types โ€“ Numbers and Text                        |
  |  Lesson 7: User Input โ€“ Asking Questions                        |
  |  Lesson 8: Conditional Statements โ€“ Making Decisions (if, else) |
  |  Lesson 9: Loops โ€“ Repeating Code (while loop)                  |
  |  Lesson 10: Loops โ€“ Repeating Code (for loop)                   |
  |  Lesson 11: Lists โ€“ Storing Many Items                          |
  |  Lesson 12: Functions โ€“ Reusable Code Blocks                    |
  |  Lesson 13: Comments โ€“ Explaining Your Code                     |
  |  Lesson 14: Debugging โ€“ Fixing Errors                           |
  |  Lesson 15: Review                                              |
  +------------------------------------------------------------------+

23. End-of-Module Summary

In this first module, we have taken our first steps into the world of Python programming. We learned what programming is and why Python is a great language to start with. We set up Python on our computers and wrote our first "Hello, World!" program. We learned about variables and how they store data. We explored different data types โ€“ integers, floats, and strings. We discovered how to get user input with input() and how to make decisions with if/else statements. We learned about loops โ€“ while and for โ€“ to repeat code. We also learned about lists to store many items, functions to reuse code, comments to explain our code, and debugging to fix errors.

Remember, learning to code is like learning a new language โ€“ it takes practice. Every programmer started where you are now. Keep coding, keep exploring, and have fun! You are now ready to move on to Module Two, where we will learn even more exciting things about Python.


24. Frequently Asked Questions

  1. What is Python? A popular programming language that is easy to learn.
  2. Do I need to know math to learn Python? Basic math is helpful, but you don't need to be a math expert.
  3. What can I build with Python? Games, websites, data tools, and much more.
  4. Is Python free? Yes, Python is free and open source.
  5. What is a variable? A container for storing data.
  6. What is a string? A piece of text.
  7. What is a loop? Code that repeats.
  8. What is a function? A reusable block of code.
  9. What is debugging? Finding and fixing errors.
  10. Where can I learn more Python? Practice, online tutorials, and more courses!

25. Review Questions

  1. What is programming?
  2. What is Python?
  3. How do you set up Python?
  4. What is the "Hello, World!" program?
  5. What is a variable?
  6. What is an integer?
  7. What is a float?
  8. What is a string?
  9. How do you get user input?
  10. What does if/else do?
  11. What is a while loop?
  12. What is a for loop?
  13. What is a list?
  14. What is a function?
  15. What is debugging?

26. Fill-in-the-Blank

  1. _____ is writing instructions for computers. (Programming)
  2. _____ is a popular programming language. (Python)
  3. A _____ stores data. (variable)
  4. An _____ is a whole number. (integer)
  5. A _____ is a decimal number. (float)
  6. A _____ is a piece of text. (string)
  7. _____ gets user input. (input())
  8. _____ makes decisions. (if)
  9. A _____ loop repeats code. (while)
  10. A _____ is a collection of items. (list)

27. True or False

  1. Python is a programming language. (True)
  2. Variables store data. (True)
  3. An integer is text. (False โ€“ it's a number)
  4. A float is a whole number. (False โ€“ it's a decimal)
  5. A string is a number. (False โ€“ it's text)
  6. input() asks the user for information. (True)
  7. if makes decisions. (True)
  8. A while loop runs forever. (False โ€“ it runs while a condition is true)
  9. A for loop repeats code a specific number of times. (True)
  10. A list can store multiple items. (True)

28. Multiple Choice Questions

  1. What is Python?
    A) A game B) A programming language C) A food D) A car Answer: B
  2. What is a variable?
    A) A container for data B) A game C) A food D) A car Answer: A
  3. What is an integer?
    A) A whole number B) A piece of text C) A decimal number D) A list Answer: A
  4. What is a float?
    A) A whole number B) A piece of text C) A decimal number D) A list Answer: C
  5. What is a string?
    A) A piece of text B) A whole number C) A decimal number D) A list Answer: A
  6. What does input() do?
    A) Gets user input B) Prints output C) Makes a decision D) Repeats code Answer: A
  7. What does if do?
    A) Makes a decision B) Repeats code C) Stores data D) Gets user input Answer: A
  8. What is a while loop?
    A) Repeats code while a condition is true B) Repeats code a set number of times C) Stores data D) Makes a decision Answer: A
  9. What is a for loop?
    A) Repeats code a set number of times B) Repeats code while a condition is true C) Stores data D) Makes a decision Answer: A
  10. What is a list?
    A) A collection of items B) A piece of text C) A whole number D) A decimal number Answer: A
  11. What is a function?
    A) A reusable block of code B) A collection of items C) A piece of text D) A whole number Answer: A
  12. What is a comment?
    A) A note in the code B) A variable C) A loop D) A function Answer: A
  13. What is debugging?
    A) Fixing errors B) Writing code C) Storing data D) Making decisions Answer: A
  14. Which is a Nigerian example?
    A) A program converting Naira to Dollars B) A program in London C) A program in New York D) A program in Tokyo Answer: A
  15. Is Python free?
    A) Yes B) No Answer: A

29. Matching Exercises

TermDefinition
PythonA) Stores multiple items
VariableB) Reusable block of code
ListC) Programming language
FunctionD) Container for data
CommentE) Note in the code

Answers: Python-C, Variable-D, List-A, Function-B, Comment-E


30. Short Answer Questions

  1. What is Python?
  2. What is a variable?
  3. What is the difference between an integer and a string?
  4. What does if/else do?
  5. What is a loop?
  6. What is a list?
  7. What is a function?

31. Scenario-based Exercises

Scenario 1: You want to write a program that asks the user for their name and age, then prints a message saying "Hello, [name]! You are [age] years old."

Task: Write the code to do this.

Answer:

  name = input("What is your name? ")
  age = input("How old are you? ")
  print("Hello, " + name + "! You are " + age + " years old.")

Scenario 2: You want to write a program that checks if a number is even or odd.

Task: Write the code to do this.

Answer:

  number = int(input("Enter a number: "))
  if number % 2 == 0:
      print(number, "is even.")
  else:
      print(number, "is odd.")

32. Group Activity

In groups of three, write a program that asks each group member for their name and favourite food. Store the names and foods in lists. Then, print a message like "Ada likes Jollof Rice." Share your program with the class.


33. Individual Activity

Write a program that asks the user for a number and prints the multiplication table for that number (from 1 to 10).


34. Classroom Discussion Questions

  • What is the most interesting thing you learned about Python?
  • What program would you like to build with Python?
  • How can Python help Nigerian businesses?
  • What is one challenge you faced when learning Python?
  • How do you fix errors in your code?

35. Mini Project

Build a simple "Quiz Game" program. The program should:

  1. Ask the user 5 multiple-choice questions.
  2. Check if the answers are correct.
  3. Keep score and display the final score at the end.

36. Practical Assignment

Write a program that acts as a simple calculator. It should:

  1. Ask the user for two numbers.
  2. Ask the user for an operation (+, -, *, /).
  3. Perform the calculation and print the result.

37. Challenge Exercise

Write a program that stores the names and scores of 5 students. Then, calculate and print the average score, the highest score, and the lowest score. Also, print the name of the student with the highest score.


38. Quiz Answers

Fill-in-the-blank: 1. Programming, 2. Python, 3. variable, 4. integer, 5. float, 6. string, 7. input(), 8. if, 9. while, 10. list

True/False: 1T, 2T, 3F, 4F, 5F, 6T, 7T, 8F, 9T, 10T

Multiple Choice: 1B, 2A, 3A, 4C, 5A, 6A, 7A, 8A, 9A, 10A, 11A, 12A, 13A, 14A, 15A

Matching: Python-C, Variable-D, List-A, Function-B, Comment-E


39. Key Takeaways

  • ๐Ÿ”น Python is a beginner-friendly programming language.
  • ๐Ÿ”น Variables store data for later use.
  • ๐Ÿ”น Data types include integers (whole numbers), floats (decimals), and strings (text).
  • ๐Ÿ”น if/else statements make decisions.
  • ๐Ÿ”น Loops (while and for) repeat code.
  • ๐Ÿ”น Lists store collections of items.
  • ๐Ÿ”น Functions are reusable code blocks.
  • ๐Ÿ”น Comments explain your code.
  • ๐Ÿ”น Debugging is fixing errors.
  • ๐Ÿ”น Practice is the key to becoming a great programmer.

40. Preparation for the Next Module

In Module Two, we will build on what you have learned. You will explore more advanced topics like:

  • Working with dictionaries and sets.
  • File input and output (reading/writing files).
  • Error handling with try/except.
  • Writing more complex functions with parameters and return values.
  • Introduction to object-oriented programming.
  • Building larger projects.

Keep practicing and exploring. You are on your way to becoming a Python expert!


๐ŸŽ‰ Congratulations! You have completed Module One: Welcome to Python Programming ๐ŸŽ‰

You are now ready for Module Two โ€“ Advanced Python Concepts!

3

Module Two

Module 2 ยท Python Programming Level 1

๐Ÿ Module Two: Diving Deeper into Python โ€“ Dictionaries, Files, and More!

1. Module Title

Module Two: Diving Deeper into Python โ€“ Dictionaries, Files, and More!


2. Module Introduction

Welcome back, young coder! You did an amazing job in Module One. You learned the basics โ€“ variables, data types, input, if/else statements, loops, lists, and functions. Now, in Module Two, we will go deeper and explore even more exciting things in Python.

We will learn about dictionaries โ€“ a special way to store information using keys and values. We will learn about sets โ€“ a collection that only keeps unique items. We will discover how to read from and write to files so that our programs can save data forever. We will learn how to handle errors so our programs don't crash. We will also learn how to write functions that return values and even create our own classes to build our own objects! This module is full of new and exciting concepts. Let's dive in!


3. Learning Objectives

After completing this module, you will be able to:

  • Understand and use dictionaries to store key-value pairs.
  • Use sets to store unique items.
  • Read from and write to files (file input/output).
  • Handle errors using try and except.
  • Write functions that take parameters and return values.
  • Understand the basics of classes and objects.
  • Use list methods to manipulate lists.
  • Loop through different data structures.
  • Build a small project that uses all the new concepts.

4. Warm-up Story

Chidi's Phone Book

Chidi had a problem. He had many friends and family members, and he kept forgetting their phone numbers. He tried using a list, but it was hard to find the right number quickly. He had to remember which position each person was in.

His teacher said, "Chidi, Python has something called a dictionary. It lets you store information using a key (like a person's name) and a value (like their phone number). You can find the number just by knowing the name!"

Chidi was amazed. He wrote:

  phone_book = {
      "Ada": "080-1234-5678",
      "Chidi": "080-8765-4321",
      "Bola": "080-5555-5555"
  }
  print(phone_book["Ada"])  # Prints the phone number

He could now find anyone's number instantly! Chidi learned that dictionaries are like real phone books โ€“ they let you find information using a key.


5. Main Lessons

Lesson 1: Review of Module One

Before we start new things, let's quickly review what we learned in Module One.

We learned:

  • Programming is giving instructions to a computer.
  • Python is a beginner-friendly programming language.
  • Variables store data.
  • Data types: integers (whole numbers), floats (decimals), and strings (text).
  • We used input() to get user input.
  • We used if/else to make decisions.
  • We used while and for loops to repeat code.
  • We used lists to store many items.
  • We wrote functions using def.
  • We added comments with #.
  • We debugged errors.

You have a strong foundation. Now, let's build on it!


Lesson 2: What is a Dictionary?

Definition: A dictionary is like a real-life dictionary or phone book. It stores information using a key and a value. You give it a key, and it gives you the value.

Why it's important: Dictionaries make it easy to find information quickly. You don't have to search through a list โ€“ you just use the key!

Simple explanation: Think of a dictionary like a locker room. Each locker has a number (the key) and inside the locker is something (the value). You use the number to open the right locker.

Real-life example: A phone book: name (key) โ†’ phone number (value).

School example: Student ID (key) โ†’ student name (value).

Home example: Person's name (key) โ†’ their age (value).

Nigerian example: A market vendor's stall number (key) โ†’ the products they sell (value).

Illustration โ€“ Code:

  # A dictionary uses curly braces { } and colons :
  phone_book = {
      "Ada": "080-1234-5678",
      "Chidi": "080-8765-4321",
      "Bola": "080-5555-5555"
  }
  print(phone_book["Ada"])  # Prints: 080-1234-5678

Mini summary: Dictionaries store key-value pairs for fast lookups.


Lesson 3: Working with Dictionaries

Definition: You can add, change, and delete items in a dictionary.

Why it's important: Dictionaries are flexible โ€“ you can update them as your data changes.

Simple explanation: It's like having a whiteboard where you can write, erase, and change information.

Real-life example: Adding a new friend to your phone book.

School example: Adding a new student to a class list.

Home example: Changing a family member's phone number.

Nigerian example: A shop owner updates the price of an item.

Illustration โ€“ Code:

  phone_book = {}  # Empty dictionary

  # Adding items
  phone_book["Ada"] = "080-1234-5678"
  phone_book["Chidi"] = "080-8765-4321"

  # Changing an item
  phone_book["Ada"] = "080-9999-9999"

  # Deleting an item
  del phone_book["Chidi"]

  # Getting all keys and values
  print(phone_book.keys())   # Prints all keys
  print(phone_book.values()) # Prints all values

Mini summary: You can add, change, and delete items in a dictionary.


Lesson 4: Looping Through a Dictionary

Definition: You can use a for loop to go through all the items in a dictionary.

Why it's important: Looping helps you process all the data in a dictionary.

Simple explanation: It's like reading every entry in a phone book from start to finish.

Real-life example: Printing all contacts in a phone book.

School example: Printing all student names and their grades.

Home example: Listing all family members and their ages.

Nigerian example: Printing all products and their prices from a market list.

Illustration โ€“ Code:

  phone_book = {
      "Ada": "080-1234-5678",
      "Chidi": "080-8765-4321"
  }

  # Loop through keys
  for name in phone_book:
      print(name + " -> " + phone_book[name])

  # Loop through both keys and values
  for name, number in phone_book.items():
      print(name + " has number " + number)

Mini summary: Use for loops to go through all items in a dictionary.


Lesson 5: What is a Set?

Definition: A set is a collection of items that are unique โ€“ it doesn't allow duplicates. A set uses curly braces { } but without colons.

Why it's important: Sets are useful when you want to remove duplicates or check if an item exists.

Simple explanation: A set is like a bag of marbles where each marble is unique โ€“ you can't have two identical marbles.

Real-life example: A list of the unique classes you have in a week.

School example: All the different subjects taught in your school.

Home example: All the different types of fruit in your kitchen.

Nigerian example: All the different states you have visited.

Illustration โ€“ Code:

  # A set uses curly braces with no colons
  fruits = {"Mango", "Orange", "Banana", "Mango"}

  # Duplicates are removed automatically
  print(fruits)  # Prints: {"Mango", "Orange", "Banana"}

  # Adding an item
  fruits.add("Apple")

  # Checking if an item exists
  if "Mango" in fruits:
      print("Mango is in the set!")

  # Removing an item
  fruits.remove("Orange")

Mini summary: Sets store unique items and remove duplicates automatically.


Lesson 6: Working with Sets

Definition: You can perform operations on sets โ€“ like union (combine), intersection (common items), and difference (items in one but not the other).

Why it's important: These operations help you compare and combine collections.

Simple explanation: It's like comparing two lists of friends to see who is in both.

Real-life example: Finding common members of two clubs.

School example: Finding students who are in both the music club and the art club.

Home example: Finding common items in two shopping lists.

Nigerian example: Finding markets that sell both yams and cassava.

Illustration โ€“ Code:

  set_a = {1, 2, 3, 4}
  set_b = {3, 4, 5, 6}

  # Union - all items from both sets
  print(set_a | set_b)  # {1, 2, 3, 4, 5, 6}

  # Intersection - items in both sets
  print(set_a & set_b)  # {3, 4}

  # Difference - items in set_a but not set_b
  print(set_a - set_b)  # {1, 2}

Mini summary: Sets allow union, intersection, and difference operations.


Lesson 7: Reading from Files

Definition: Reading from a file means getting data that is stored on your computer and bringing it into your program.

Why it's important: Files let you save data permanently. When you close your program, the data is still there.

Simple explanation: It's like opening a book and reading what's written inside.

Real-life example: A program reads a list of names from a file.

School example: A program reads student grades from a file.

Home example: A program reads a shopping list from a file.

Nigerian example: A program reads a price list from a file.

Illustration โ€“ Code:

  # Reading from a file
  file = open("data.txt", "r")  # "r" means read mode
  content = file.read()
  print(content)
  file.close()  # Always close the file

Mini summary: open() lets you read data from a file.


Lesson 8: Writing to Files

Definition: Writing to a file means saving data from your program to a file on your computer.

Why it's important: You can save user data, results, or anything else permanently.

Simple explanation: It's like writing in a notebook and saving it for later.

Real-life example: A program saves a user's settings.

School example: A program saves test scores.

Home example: A program saves a shopping list.

Nigerian example: A program saves sales records.

Illustration โ€“ Code:

  # Writing to a file
  file = open("output.txt", "w")  # "w" means write mode
  file.write("Hello, World!\n")
  file.write("This is a new line.\n")
  file.close()  # Always close the file

Mini summary: open() with "w" mode lets you write data to a file.


Lesson 9: Error Handling โ€“ try and except

Definition: Error handling lets you catch errors so your program doesn't crash. You use try and except.

Why it's important: It makes your program more robust and user-friendly.

Simple explanation: It's like wearing a safety net in case you fall.

Real-life example: A program asks for a number. If the user types letters, instead of crashing, it says "Please enter a number."

School example: A program handles invalid test scores.

Home example: A program handles missing files.

Nigerian example: A program handles invalid PIN entries.

Illustration โ€“ Code:

  try:
      number = int(input("Enter a number: "))
      print("You entered:", number)
  except ValueError:
      print("That's not a valid number!")

Mini summary: try/except catches errors and prevents crashes.


Lesson 10: Functions with Parameters

Definition: Parameters are values that you pass into a function so it can work with different data.

Why it's important: Parameters make your functions flexible and reusable.

Simple explanation: It's like a recipe that lets you choose your own ingredients.

Real-life example: A function that greets a person: greet("Ada").

School example: A function that adds two numbers: add(5, 3).

Home example: A function that converts Celsius to Fahrenheit: convert(25).

Nigerian example: A function that converts Naira to Dollars: convert(5000).

Illustration โ€“ Code:

  def greet(name):
      print("Hello, " + name + "!")

  greet("Ada")   # Prints: Hello, Ada!
  greet("Chidi") # Prints: Hello, Chidi!

  def add(a, b):
      print(a + b)

  add(5, 3)  # Prints: 8

Mini summary: Functions with parameters work with different data.


Lesson 11: Functions that Return Values

Definition: A function can return a value back to where it was called. You use the return keyword.

Why it's important: Returning values lets you use the result of a function in other parts of your program.

Simple explanation: It's like asking a friend to do a calculation and then give you the answer.

Real-life example: A function that calculates the area of a rectangle and returns it.

School example: A function that calculates the average of scores.

Home example: A function that converts temperature and returns the result.

Nigerian example: A function that calculates tax and returns the amount.

Illustration โ€“ Code:

  def add(a, b):
      return a + b

  result = add(5, 3)
  print(result)  # Prints: 8

  def square(num):
      return num * num

  print(square(4))  # Prints: 16

Mini summary: Use return to send values back from a function.


Lesson 12: Introduction to Classes and Objects

Definition: A class is like a blueprint for creating objects. An object is an instance of a class. It has attributes (characteristics) and methods (things it can do).

Why it's important: Classes let you model real-world things in code โ€“ like a car, a student, or a bank account.

Simple explanation: A class is like a cookie cutter. An object is the cookie you make with it.

Real-life example: A "Car" class can have attributes like colour and speed, and methods like drive and stop.

School example: A "Student" class can have attributes like name and grade, and methods like study.

Home example: A "Dog" class can have attributes like name and breed, and methods like bark.

Nigerian example: A "MarketVendor" class can have attributes like name and products, and methods like sell.

Illustration โ€“ Code:

  class Student:
      def __init__(self, name, age):
          self.name = name
          self.age = age

      def greet(self):
          print("Hello, my name is " + self.name)

  # Creating an object
  ada = Student("Ada", 10)
  ada.greet()  # Prints: Hello, my name is Ada

  chidi = Student("Chidi", 12)
  chidi.greet()  # Prints: Hello, my name is Chidi

Mini summary: Classes are blueprints for creating objects with attributes and methods.


Lesson 13: More List Methods

Definition: Lists have many built-in methods that let you do things like sort, reverse, add, and remove items.

Why it's important: Methods make working with lists easy and efficient.

Simple explanation: It's like having a Swiss Army knife for lists โ€“ many tools in one.

Real-life example: list.sort() sorts items alphabetically.

School example: list.append() adds a new student to a list.

Home example: list.remove() removes an item from a shopping list.

Nigerian example: list.reverse() reverses the order of items in a list.

Illustration โ€“ Code:

  fruits = ["Banana", "Apple", "Mango", "Orange"]

  # Add an item
  fruits.append("Pineapple")

  # Remove an item
  fruits.remove("Banana")

  # Sort the list
  fruits.sort()

  # Reverse the list
  fruits.reverse()

  # Check the length
  print(len(fruits))

  print(fruits)

Mini summary: Lists have many built-in methods for manipulation.


Lesson 14: Putting It All Together โ€“ A Small Project

Now let's use what we learned to build something useful!

Project: A Simple Contact Manager

We will build a program that lets the user:

  1. Add a new contact (name and phone number).
  2. View all contacts.
  3. Search for a contact by name.
  4. Delete a contact.
  5. Save contacts to a file so they don't disappear when the program closes.

Illustration โ€“ Code:

  # Simple Contact Manager using Dictionaries and Files

  contacts = {}
  filename = "contacts.txt"

  # Load contacts from file
  try:
      file = open(filename, "r")
      for line in file:
          name, number = line.strip().split(",")
          contacts[name] = number
      file.close()
  except:
      print("No saved contacts found.")

  def save_contacts():
      file = open(filename, "w")
      for name, number in contacts.items():
          file.write(name + "," + number + "\n")
      file.close()

  while True:
      print("\n===== CONTACT MANAGER =====")
      print("1. Add Contact")
      print("2. View All Contacts")
      print("3. Search Contact")
      print("4. Delete Contact")
      print("5. Exit")

      choice = input("Choose an option: ")

      if choice == "1":
          name = input("Enter name: ")
          number = input("Enter phone number: ")
          contacts[name] = number
          save_contacts()
          print("Contact added!")

      elif choice == "2":
          if contacts:
              for name, number in contacts.items():
                  print(name + " -> " + number)
          else:
              print("No contacts found.")

      elif choice == "3":
          name = input("Enter name to search: ")
          if name in contacts:
              print(name + " -> " + contacts[name])
          else:
              print("Contact not found.")

      elif choice == "4":
          name = input("Enter name to delete: ")
          if name in contacts:
              del contacts[name]
              save_contacts()
              print("Contact deleted!")
          else:
              print("Contact not found.")

      elif choice == "5":
          print("Goodbye!")
          break

      else:
          print("Invalid choice. Try again.")

Mini summary: Combining all the skills you learned to build a real project.


Lesson 15: Review โ€“ What We Learned in Module Two

In this module, we learned:

  • Dictionaries store key-value pairs.
  • Sets store unique items.
  • How to read from and write to files.
  • How to handle errors with try and except.
  • Functions with parameters and return values.
  • The basics of classes and objects.
  • More list methods.
  • How to build a small project using all these concepts.

You have now built a strong foundation in Python. You are ready for Level 2!


6. Key Vocabulary

  • Dictionary: A collection of key-value pairs.
  • Key: A unique identifier in a dictionary.
  • Value: The data associated with a key.
  • Set: A collection of unique items.
  • File: A place to store data permanently.
  • Read: To get data from a file.
  • Write: To save data to a file.
  • Error Handling: Catching and managing errors.
  • Parameter: A value passed into a function.
  • Return: To send a value back from a function.
  • Class: A blueprint for creating objects.
  • Object: An instance of a class.

7. Important Concepts

  • Dictionaries make data easy to find: Use keys to look up values quickly.
  • Sets remove duplicates: Great for tracking unique items.
  • Files save your data forever: Your program data survives after you close it.
  • Error handling prevents crashes: Always handle possible errors.
  • Functions with parameters are flexible: They can work with different data.
  • Classes model real-world things: They help you organise complex code.

8. Step-by-step Explanations

How to read and write files:

  1. Open the file with open("filename", "r") for reading.
  2. Read the content with .read() or loop through lines.
  3. Close the file with .close().
  4. For writing, use open("filename", "w").
  5. Write content with .write().
  6. Close the file.

9. Real-life Examples

  • A dictionary storing product prices in a store.
  • A set storing unique visitors to a website.
  • A file storing user settings.
  • Error handling in a payment system.
  • A function that calculates discounts.
  • A class representing a bank account.

10. Nigerian Examples

  • A dictionary storing Naira-to-Dollar exchange rates.
  • A set storing the states you have visited in Nigeria.
  • A file storing daily sales records.
  • Error handling when entering a PIN at an ATM.
  • A function that calculates VAT on items.
  • A class representing a market vendor.

11. Fun Examples Children Can Relate To

  • A dictionary of your friends' favourite games.
  • A set of your favourite foods.
  • A file storing your high scores.
  • Error handling in a game when the user enters invalid input.
  • A function that calculates how many days until your birthday.
  • A class representing a video game character.

12. Everyday Examples

  • ๐Ÿ“ฑ A phone book (dictionary).
  • ๐ŸŽต A playlist with unique songs (set).
  • ๐Ÿ“ A to-do list saved to a file.
  • ๐Ÿ” A login system with error handling.
  • ๐Ÿ“Š A function that calculates averages.
  • ๐Ÿ  A class representing a house.

13. Teacher Notes

This module introduces several new concepts. Take it step by step. Use the contact manager project as a capstone. Encourage students to modify and expand the project. Pair programming can be helpful here.


14. Parent Tips

Help your child think of real things that could be modelled as dictionaries, sets, or classes. For example, "What would a dictionary of your family members look like?" or "What are the unique games you own?"


15. Interesting Facts

  • ๐Ÿ“š Dictionaries in Python are very fast โ€“ they can find a value instantly!
  • ๐Ÿ”’ Sets are used in many games to track unique items.
  • ๐Ÿ’พ Files are how programs save your progress in games.
  • ๐Ÿงช Error handling is what keeps websites from crashing.
  • ๐Ÿ—๏ธ Classes are used to build everything from video games to web apps.

16. Did You Know?

  • Python dictionaries are used behind the scenes in many web applications.
  • Sets are used to find common friends on social media.
  • File I/O is how databases work โ€“ they store data permanently.
  • Error handling is a skill that makes you a better programmer.
  • Classes are the foundation of object-oriented programming (OOP).

17. Remember This

  • โœ… Dictionaries = key-value pairs.
  • โœ… Sets = unique items.
  • โœ… Files = permanent storage.
  • โœ… try/except = error handling.
  • โœ… Functions can take parameters and return values.
  • โœ… Classes = blueprints for objects.

18. Common Mistakes

  • โŒ Forgetting quotes around keys in dictionaries.
  • โŒ Trying to access a key that doesn't exist.
  • โŒ Forgetting to close a file.
  • โŒ Not handling errors that might occur.
  • โŒ Forgetting the self parameter in class methods.

19. Best Practices

  • โœ… Use get() to safely access dictionary keys.
  • โœ… Use sets when you need unique items.
  • โœ… Always close files or use with statements.
  • โœ… Always handle potential errors.
  • โœ… Use descriptive names for classes and methods.

20. Illustrations

Dictionary Structure

  +------------------------------------------+
  |  DICTIONARY                               |
  |  +--------------------------------------+ |
  |  |  KEY       |  VALUE                  | |
  |  |------------|-------------------------| |
  |  |  "Ada"     |  "080-1234-5678"       | |
  |  |  "Chidi"   |  "080-8765-4321"       | |
  |  |  "Bola"    |  "080-5555-5555"       | |
  |  +--------------------------------------+ |
  +------------------------------------------+

Comparison Table โ€“ Data Structures

Data StructureWhat It DoesExample
ListOrdered collection of items["Apple", "Banana", "Mango"]
DictionaryKey-value pairs for fast lookups{"Ada": "080-1234", "Chidi": "080-5678"}
SetUnique items, no duplicates{"Mango", "Orange", "Banana"}

Comparison Table โ€“ File Modes

ModeWhat It DoesIf File Doesn't Exist
"r" (read)Reads from a fileError
"w" (write)Writes to a file (overwrites)Creates it
"a" (append)Adds to the end of a fileCreates it

Timeline โ€“ Module Two Learning Path

  +------------------------------------------------------------------+
  |  Lesson 1: Review of Module One                                  |
  |  Lesson 2: What is a Dictionary?                                 |
  |  Lesson 3: Working with Dictionaries                             |
  |  Lesson 4: Looping Through a Dictionary                          |
  |  Lesson 5: What is a Set?                                        |
  |  Lesson 6: Working with Sets                                     |
  |  Lesson 7: Reading from Files                                    |
  |  Lesson 8: Writing to Files                                      |
  |  Lesson 9: Error Handling โ€“ try and except                       |
  |  Lesson 10: Functions with Parameters                            |
  |  Lesson 11: Functions that Return Values                         |
  |  Lesson 12: Introduction to Classes and Objects                  |
  |  Lesson 13: More List Methods                                    |
  |  Lesson 14: Putting It All Together โ€“ A Small Project            |
  |  Lesson 15: Review                                               |
  +------------------------------------------------------------------+

23. End-of-Module Summary

In this module, we have taken a big step forward in our Python journey. We learned about dictionaries โ€“ a powerful way to store key-value pairs. We explored sets โ€“ collections that only keep unique items. We discovered how to read from and write to files, making our programs remember data even after they close. We learned how to handle errors gracefully using try and except. We improved our functions by adding parameters and return values. We also got a taste of object-oriented programming with classes and objects.

We built a contact manager project that used all these new skills together. You now have a solid foundation in Python programming. You can build programs that store and retrieve data, handle errors, and organise code in clear, reusable ways. You are ready for the next level!


24. Frequently Asked Questions

  1. What is a dictionary? A collection of key-value pairs.
  2. What is a set? A collection of unique items.
  3. Why do we need files? To save data permanently.
  4. What does try/except do? It prevents errors from crashing your program.
  5. What are parameters? Values you pass into a function.
  6. What does return do? It sends a value back from a function.
  7. What is a class? A blueprint for creating objects.
  8. What is an object? An instance of a class.
  9. How do I read a file? Use open("file", "r").
  10. How do I write to a file? Use open("file", "w").

25. Review Questions

  1. What is a dictionary?
  2. What is a key in a dictionary?
  3. What is a value in a dictionary?
  4. How do you add an item to a dictionary?
  5. What is a set?
  6. How do you add an item to a set?
  7. How do you read from a file?
  8. How do you write to a file?
  9. What does try/except do?
  10. What is a parameter in a function?
  11. What does return do in a function?
  12. What is a class?
  13. What is an object?
  14. What is the difference between a list and a dictionary?
  15. What is the difference between a list and a set?

26. Fill-in-the-Blank

  1. A _____ stores key-value pairs. (dictionary)
  2. A _____ stores unique items. (set)
  3. To read a file, use the _____ mode. ("r")
  4. To write to a file, use the _____ mode. ("w")
  5. _____ handles errors in Python. (try/except)
  6. A _____ is a value passed into a function. (parameter)
  7. The _____ keyword returns a value from a function. (return)
  8. A _____ is a blueprint for creating objects. (class)
  9. An _____ is an instance of a class. (object)
  10. A _____ is an ordered collection of items. (list)

27. True or False

  1. Dictionaries store key-value pairs. (True)
  2. Sets allow duplicate items. (False)
  3. Files save data permanently. (True)
  4. try/except prevents errors. (True)
  5. Functions can take parameters. (True)
  6. Functions cannot return values. (False)
  7. A class is an object. (False)
  8. A set is an ordered collection. (False)
  9. You must close files after using them. (True)
  10. Dictionaries are used for fast lookups. (True)

28. Multiple Choice Questions

  1. What does a dictionary store?
    A) Key-value pairs B) Only values C) Only keys D) Duplicates Answer: A
  2. What does a set store?
    A) Unique items B) Duplicate items C) Key-value pairs D) Only numbers Answer: A
  3. What mode reads from a file?
    A) "r" B) "w" C) "a" D) "x" Answer: A
  4. What mode writes to a file?
    A) "w" B) "r" C) "a" D) "x" Answer: A
  5. What does try/except do?
    A) Handles errors B) Writes to files C) Reads from files D) Loops code Answer: A
  6. What is a parameter?
    A) A value passed to a function B) A type of loop C) A data structure D) An error Answer: A
  7. What does return do?
    A) Sends a value back B) Prints a value C) Loops code D) Creates a variable Answer: A
  8. What is a class?
    A) A blueprint for objects B) A collection of items C) A type of loop D) A file Answer: A
  9. What is an object?
    A) An instance of a class B) A key-value pair C) A file D) A loop Answer: A
  10. Which is a dictionary?
    A) {"name": "Ada"} B) ["Ada", "Chidi"] C) {"Ada", "Chidi"} D) "Ada" Answer: A
  11. Which is a set?
    A) {"Ada", "Chidi"} B) {"name": "Ada"} C) ["Ada", "Chidi"] D) "Ada" Answer: A
  12. Why do we close files?
    A) To save memory and prevent errors B) To make them faster C) To delete them D) To read them Answer: A
  13. What is a Nigerian example of a dictionary?
    A) A price list with items and prices B) A list of names C) A set of cities D) A file Answer: A
  14. What is a Nigerian example of a set?
    A) All the states you've visited B) A list of cities C) A dictionary of prices D) A file Answer: A
  15. Is Python free?
    A) Yes B) No Answer: A

29. Matching Exercises

TermDefinition
DictionaryA) Unique items
SetB) Key-value pairs
FileC) Handles errors
try/exceptD) Sends a value back
returnE) Permanent storage

Answers: Dictionary-B, Set-A, File-E, try/except-C, return-D


30. Short Answer Questions

  1. What is a dictionary?
  2. What is the difference between a list and a dictionary?
  3. What is a set?
  4. How do you read from a file?
  5. How do you write to a file?
  6. What does try/except do?
  7. What is a class?

31. Scenario-based Exercises

Scenario 1: You want to store the names and ages of your family members in a program.

Task: Should you use a list, dictionary, or set? Why?

Answer: A dictionary, because you want to look up a person's age by their name.

Scenario 2: You want to keep track of all the unique books you have read.

Task: Should you use a list, dictionary, or set? Why?

Answer: A set, because you only want to track unique titles (no duplicates).


32. Group Activity

In groups of three, build an enhanced version of the Contact Manager. Add a feature to save the contacts to a file and load them automatically when the program starts. Add a feature to update an existing contact. Share your work with the class.


33. Individual Activity

Write a program that uses a dictionary to store students' names and their scores in a subject. Then, write a function that calculates and returns the average score.


34. Classroom Discussion Questions

  • When would you use a dictionary instead of a list?
  • When would you use a set instead of a list?
  • Why is it important to save data to files?
  • How can error handling make your program better?
  • What real-world things could you model with classes?

35. Mini Project

Build a simple "Student Grade Manager" program. It should:

  1. Use a dictionary to store student names and grades.
  2. Allow the user to add, view, and delete students.
  3. Save the data to a file so it doesn't disappear.
  4. Load the data when the program starts.
  5. Calculate and display the average grade.

36. Practical Assignment

Write a program that reads a list of numbers from a file, finds the sum, average, and maximum number, and writes the results to another file.


37. Challenge Exercise

Enhance the Contact Manager project to allow editing of contacts. Also, add a feature to search for a contact by phone number (not just by name).


38. Quiz Answers

Fill-in-the-blank: 1. dictionary, 2. set, 3. "r", 4. "w", 5. try/except, 6. parameter, 7. return, 8. class, 9. object, 10. list

True/False: 1T, 2F, 3T, 4T, 5T, 6F, 7F, 8F, 9T, 10T

Multiple Choice: 1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A, 10A, 11A, 12A, 13A, 14A, 15A

Matching: Dictionary-B, Set-A, File-E, try/except-C, return-D


39. Key Takeaways

  • ๐Ÿ”น Dictionaries store key-value pairs for fast lookups.
  • ๐Ÿ”น Sets store unique items and remove duplicates.
  • ๐Ÿ”น Files save your data permanently.
  • ๐Ÿ”น try/except handles errors gracefully.
  • ๐Ÿ”น Functions with parameters and return values are flexible.
  • ๐Ÿ”น Classes and objects model real-world things.
  • ๐Ÿ”น List methods make working with lists easier.
  • ๐Ÿ”น You can build real projects with these skills.

40. Preparation for the Next Module

In Level 2, you will build on everything you have learned. You will explore more advanced concepts like:

  • More advanced object-oriented programming.
  • Working with external libraries.
  • Building graphical user interfaces (GUIs).
  • Introduction to web development with Python.
  • Working with APIs to get data from the internet.
  • Building larger, more complex projects.

Keep coding, keep exploring, and remember: every expert was once a beginner!


๐ŸŽ‰ Congratulations! You have completed Module Two: Diving Deeper into Python ๐ŸŽ‰

You are now ready for Level 2 โ€“ Advanced Python!

4

Module Three

Module 3 ยท Python Programming Level 1

๐Ÿ Module Three: Building Cool Projects โ€“ Strings, Tuples, and More!

1. Module Title

Module Three: Building Cool Projects โ€“ Strings, Tuples, and More!


2. Module Introduction

Welcome back, young coder! You have made incredible progress. In Module One, you learned the basics โ€“ variables, data types, input, if/else, loops, lists, and functions. In Module Two, you explored dictionaries, sets, file handling, error handling, functions with return values, and even classes!

Now, in Module Three, we will learn some new, powerful concepts that will make your code even better. We will explore strings in more detail โ€“ they are not just text, they have many cool methods! We will learn about tuples โ€“ a special kind of list that cannot be changed. We will discover how to pack and unpack values. We will build a real game โ€“ a "Millionaire Quiz Game" โ€“ using everything we have learned. We will also learn some advanced function tricks like default arguments and keyword arguments.

This module is all about taking your skills to the next level and building something fun. Let's get started!


3. Learning Objectives

After completing this module, you will be able to:

  • Use string methods to manipulate text (lower, upper, split, join, etc.).
  • Understand and use tuples โ€“ immutable lists.
  • Pack and unpack values in Python.
  • Use default arguments in functions.
  • Use keyword arguments in functions.
  • Build a complete "Millionaire Quiz Game" project.
  • Combine all your Python skills in a real-world project.
  • Write clean, well-documented code.

4. Warm-up Story

Chidi's Millionaire Dream

Chidi loved watching the TV show "Who Wants to Be a Millionaire?" He always dreamed of being a contestant. He said to his friend Ada, "I wish I could practice with questions before the show!" Ada said, "Chidi, you know Python! You can build your own quiz game!"

Chidi was excited. He decided to build a "Millionaire Quiz Game" using Python. He created a list of questions and answers. He used strings to format the questions nicely. He used loops to go through all the questions. He used if/else to check if the answers were correct. He even used a dictionary to keep track of scores. When he finished, he had a fully working game. He invited his friends to play, and they all had fun. Chidi realised that with Python, he could build anything he imagined!


5. Main Lessons

Lesson 1: Review of Modules One and Two

Before we start new things, let's quickly review what we learned in the first two modules.

From Module One:

  • Variables store data.
  • Data types: integers, floats, strings.
  • input() gets user input.
  • if/elif/else for decisions.
  • while and for loops.
  • Lists store many items.
  • Functions with def.
  • Comments with #.

From Module Two:

  • Dictionaries store key-value pairs.
  • Sets store unique items.
  • Reading and writing files.
  • Error handling with try/except.
  • Functions with parameters and return values.
  • Classes and objects.
  • List methods like append(), sort(), reverse().

You have a strong foundation. Now, let's add some more tools to your toolbox!


Lesson 2: String Methods โ€“ Making Text Smarter

Definition: Strings are pieces of text. Python has many built-in methods (tools) that let you change and work with strings.

Why it's important: You will often need to clean, format, or change text in your programs.

Simple explanation: It's like having a set of tools to fix, clean, and change words.

Real-life example: Changing all letters to uppercase for a consistent look.

School example: Removing extra spaces from a student's name.

Home example: Checking if a password is strong.

Nigerian example: Formatting a phone number to a standard format.

Illustration โ€“ Code:

  # String methods
  text = "   Hello, World!   "

  # Remove extra spaces from the ends
  print(text.strip())  # "Hello, World!"

  # Convert to uppercase
  print(text.upper())  # "   HELLO, WORLD!   "

  # Convert to lowercase
  print(text.lower())  # "   hello, world!   "

  # Split into a list of words
  words = text.split()  # ["Hello,", "World!"]

  # Check if it starts with something
  print(text.startswith(" Hello"))  # True

  # Check if it ends with something
  print(text.endswith("!"))  # True

  # Find a word
  print(text.find("World"))  # Finds the position

  # Replace text
  print(text.replace("World", "Python"))  # "   Hello, Python!   "

Mini summary: String methods let you manipulate and work with text easily.


Lesson 3: More String Methods โ€“ Formatting and Joining

Definition: We can format strings using format() or f-strings. We can also join strings together from a list.

Why it's important: Formatting helps you create nice-looking output. Joining helps you combine many pieces of text.

Simple explanation: It's like putting puzzle pieces together to make a complete picture.

Real-life example: Creating a sentence from a list of words.

School example: Printing a report card with formatted grades.

Home example: Creating a shopping list with prices.

Nigerian example: Formatting currency values with the Naira symbol.

Illustration โ€“ Code:

  # Using f-strings (preferred in modern Python)
  name = "Ada"
  age = 10
  print(f"Hello, {name}! You are {age} years old.")

  # Using format() method
  print("Hello, {}! You are {} years old.".format(name, age))

  # Joining a list of strings
  words = ["Python", "is", "awesome"]
  sentence = " ".join(words)
  print(sentence)  # "Python is awesome"

  # Splitting a string into a list
  text = "apple,banana,mango"
  fruits = text.split(",")
  print(fruits)  # ["apple", "banana", "mango"]

Mini summary: format() and f-strings format text; join() combines strings.


Lesson 4: What is a Tuple?

Definition: A tuple is like a list, but it cannot be changed (it is immutable). You create a tuple using parentheses ().

Why it's important: Tuples are used for data that should not change โ€“ like days of the week, coordinates, or settings.

Simple explanation: A tuple is like a list that you write in pen โ€“ you can't erase or change it.

Real-life example: The days of the week: ("Monday", "Tuesday", "Wednesday").

School example: The subjects in a school timetable.

Home example: The names of your family members.

Nigerian example: The names of the states in the South-East.

Illustration โ€“ Code:

  # Creating a tuple
  days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

  # Accessing items
  print(days[0])  # "Monday"

  # Looping through a tuple
  for day in days:
      print(day)

  # Trying to change a tuple will cause an error
  # days[0] = "Sunday"  # Error! Tuples cannot be changed

Mini summary: Tuples are like lists, but they cannot be changed after creation.


Lesson 5: Packing and Unpacking

Definition: Packing is putting multiple values into a tuple. Unpacking is taking those values out and assigning them to variables.

Why it's important: Packing and unpacking make it easy to work with multiple values at once.

Simple explanation: It's like packing a suitcase (packing) and then unpacking it when you arrive (unpacking).

Real-life example: Returning multiple values from a function.

School example: Getting a student's name, age, and grade in one go.

Home example: Getting the temperature, humidity, and wind speed from a weather sensor.

Nigerian example: Getting the name, price, and quantity of a product from a database.

Illustration โ€“ Code:

  # Packing values into a tuple
  student = ("Ada", 10, "A")

  # Unpacking values into variables
  name, age, grade = student
  print(name)   # "Ada"
  print(age)    # 10
  print(grade)  # "A"

  # Returning multiple values from a function
  def get_student():
      return "Chidi", 12, "B"

  name2, age2, grade2 = get_student()
  print(name2, age2, grade2)  # "Chidi 12 B"

  # Swapping values using tuple unpacking
  a = 5
  b = 10
  a, b = b, a
  print(a, b)  # 10 5

Mini summary: Packing groups values; unpacking separates them into variables.


Lesson 6: Default Arguments in Functions

Definition: Default arguments let you set a default value for a parameter. If the caller doesn't provide a value, the default is used.

Why it's important: Default arguments make your functions more flexible and easier to use.

Simple explanation: It's like having a backup plan โ€“ if the user doesn't choose, you decide for them.

Real-life example: A function that greets a person. If no name is given, it says "Hello, Guest!".

School example: A function that calculates grades. If no pass mark is given, it uses 50 as default.

Home example: A function that calculates a discount. If no discount is given, it uses 10% as default.

Nigerian example: A function that calculates tax. If no tax rate is given, it uses 7.5% as default.

Illustration โ€“ Code:

  # A function with a default argument
  def greet(name="Guest"):
      print("Hello, " + name + "!")

  greet()          # Prints: Hello, Guest!
  greet("Ada")     # Prints: Hello, Ada!

  # Another example
  def calculate_discount(price, discount=10):
      return price - (price * discount / 100)

  print(calculate_discount(100))     # Uses 10% discount -> 90
  print(calculate_discount(100, 20)) # Uses 20% discount -> 80

Mini summary: Default arguments give a fallback value if the user doesn't provide one.


Lesson 7: Keyword Arguments in Functions

Definition: Keyword arguments let you pass arguments to a function by name, not just by position. This makes your code clearer.

Why it's important: It makes function calls easier to read and understand.

Simple explanation: It's like saying "Put the sugar in the bowl" โ€“ you name what you are doing.

Real-life example: order(food="Pizza", quantity=2).

School example: grade(student="Ada", score=90).

Home example: set_alarm(time="7:00", days="Monday").

Nigerian example: buy_item(name="Rice", quantity=5, price=1000).

Illustration โ€“ Code:

  # A function with multiple parameters
  def student_info(name, age, grade):
      print(f"Name: {name}, Age: {age}, Grade: {grade}")

  # Positional arguments (order matters)
  student_info("Ada", 10, "A")

  # Keyword arguments (order doesn't matter)
  student_info(grade="B", name="Chidi", age=12)

  # Mixing positional and keyword (positional first)
  student_info("Bola", age=11, grade="C")

  # Default arguments with keyword arguments
  def greet(name="Guest", greeting="Hello"):
      print(greeting + ", " + name + "!")

  greet()                          # Hello, Guest!
  greet(name="Ada")                # Hello, Ada!
  greet(greeting="Hi", name="Chidi") # Hi, Chidi!

Mini summary: Keyword arguments let you pass values by name for clarity.


Lesson 8: The Power of len() and range()

Definition: len() returns the length (number of items) of a collection. range() generates a sequence of numbers.

Why it's important: They are used in loops and to check sizes of data structures.

Simple explanation: len() counts how many, range() gives you numbers to count with.

Real-life example: Checking the length of a password.

School example: Looping through a list of student names.

Home example: Creating a range of numbers for a timer.

Nigerian example: Counting the number of items in a shopping list.

Illustration โ€“ Code:

  # len() โ€“ get the length
  fruits = ["Mango", "Orange", "Banana"]
  print(len(fruits))  # 3

  text = "Hello, World!"
  print(len(text))    # 13

  # range() โ€“ generate numbers
  for i in range(5):
      print(i)  # Prints 0, 1, 2, 3, 4

  # range(start, stop, step)
  for i in range(1, 10, 2):
      print(i)  # Prints 1, 3, 5, 7, 9

  # Using len() and range() together
  for i in range(len(fruits)):
      print(fruits[i])

Mini summary: len() counts items; range() generates number sequences.


Lesson 9: List Comprehensions โ€“ A Shorter Way to Build Lists

Definition: List comprehensions are a shorter way to create lists. They combine a loop and a condition in one line.

Why it's important: They make your code shorter and easier to read.

Simple explanation: It's like writing a loop and an if statement all in one line.

Real-life example: Creating a list of doubled numbers.

School example: Creating a list of even numbers from 1 to 20.

Home example: Creating a list of words that start with "a".

Nigerian example: Creating a list of prices above a certain amount.

Illustration โ€“ Code:

  # Traditional way
  squares = []
  for i in range(1, 6):
      squares.append(i * i)
  print(squares)  # [1, 4, 9, 16, 25]

  # List comprehension โ€“ shorter!
  squares2 = [i * i for i in range(1, 6)]
  print(squares2)  # [1, 4, 9, 16, 25]

  # With a condition
  evens = [i for i in range(1, 11) if i % 2 == 0]
  print(evens)  # [2, 4, 6, 8, 10]

  # Using with strings
  fruits = ["Mango", "Orange", "Banana"]
  upper_fruits = [fruit.upper() for fruit in fruits]
  print(upper_fruits)  # ["MANGO", "ORANGE", "BANANA"]

Mini summary: List comprehensions are a shorter way to create lists from loops.


Lesson 10: Building the Millionaire Quiz Game โ€“ Planning

Now we will build our capstone project โ€“ a "Millionaire Quiz Game". Let's plan it first.

What the game will do:

  1. Show the user questions one by one.
  2. Each question has 4 answer choices (A, B, C, D).
  3. The user selects an answer.
  4. The game checks if the answer is correct.
  5. If correct, the user earns points.
  6. If wrong, the game ends or shows the correct answer.
  7. The game displays the final score at the end.

What we need:

  • Questions and answers stored in a data structure (list of tuples).
  • A loop to go through all questions.
  • User input to get the answer.
  • Conditional statements to check answers.
  • A score counter.
  • String formatting to display questions and options nicely.

Lesson 11: Building the Millionaire Quiz Game โ€“ Step 1: Data

We will store our questions in a list of tuples. Each tuple will have: (question, option_a, option_b, option_c, option_d, correct_answer).

Illustration โ€“ Code:

  # List of questions
  questions = [
      ("What is the capital of Nigeria?", "Lagos", "Abuja", "Kano", "Ibadan", "B"),
      ("Who is the president of Nigeria?", "Buhari", "Tinubu", "Jonathan", "Obasanjo", "B"),
      ("What is 5 + 3?", "6", "7", "8", "9", "C"),
      ("Which is the largest country in Africa?", "Nigeria", "South Africa", "Algeria", "DR Congo", "C"),
      ("What is the currency of Nigeria?", "Naira", "Cedis", "Rand", "Shilling", "A")
  ]

Mini summary: Store questions in a list of tuples for easy access.


Lesson 12: Building the Millionaire Quiz Game โ€“ Step 2: Display and Check

We will write a function to display a question and its options, get user input, and check if it's correct.

Illustration โ€“ Code:

  def ask_question(question_tuple):
      # Unpack the tuple
      question, a, b, c, d, correct = question_tuple

      # Display the question and options
      print("\n" + question)
      print("A. " + a)
      print("B. " + b)
      print("C. " + c)
      print("D. " + d)

      # Get user's answer
      answer = input("Your answer (A/B/C/D): ").upper()

      # Check if correct
      if answer == correct:
          print("โœ… Correct!")
          return True
      else:
          print("โŒ Wrong! The correct answer was " + correct + ".")
          return False

Mini summary: Display the question, get input, and check the answer.


Lesson 13: Building the Millionaire Quiz Game โ€“ Step 3: The Main Game Loop

Now we put everything together with a main game loop.

Illustration โ€“ Code:

  def play_game():
      score = 0
      total = len(questions)

      print("=" * 40)
      print("๐ŸŽ‰ WELCOME TO THE MILLIONAIRE QUIZ GAME! ๐ŸŽ‰")
      print("=" * 40)

      for index, q in enumerate(questions):
          print(f"\n๐Ÿ“Œ Question {index + 1} of {total}")
          if ask_question(q):
              score += 1

      # Display final score
      print("\n" + "=" * 40)
      print(f"๐Ÿ† GAME OVER! You scored {score} out of {total}.")
      if score == total:
          print("๐ŸŽ‰ PERFECT SCORE! You are a genius! ๐ŸŽ‰")
      elif score >= total * 0.7:
          print("๐ŸŒŸ Great job! You are a quiz master!")
      elif score >= total * 0.4:
          print("๐Ÿ‘ Not bad! Keep learning!")
      else:
          print("๐Ÿ“š Keep studying! You'll do better next time!")
      print("=" * 40)

  # Run the game
  play_game()

Mini summary: The main loop runs all questions and displays the final score.


Lesson 14: Enhancing the Quiz Game โ€“ Adding Difficulty Levels

We can add difficulty levels to our game. Easy questions, medium questions, and hard questions.

Illustration โ€“ Code:

  # Questions with difficulty
  easy_questions = [
      ("What is the capital of Nigeria?", "Lagos", "Abuja", "Kano", "Ibadan", "B"),
      ("What is 5 + 3?", "6", "7", "8", "9", "C")
  ]

  medium_questions = [
      ("Which year did Nigeria gain independence?", "1950", "1960", "1970", "1980", "B"),
      ("Who is the current president of Nigeria?", "Buhari", "Tinubu", "Jonathan", "Obasanjo", "B")
  ]

  hard_questions = [
      ("What is the largest state in Nigeria by area?", "Lagos", "Borno", "Niger", "Bauchi", "C"),
      ("Which river is the longest in Nigeria?", "Niger", "Benue", "Cross", "Ogun", "A")
  ]

  def play_with_difficulty():
      difficulty = input("Choose difficulty (easy/medium/hard): ").lower()
      if difficulty == "easy":
          questions = easy_questions
      elif difficulty == "medium":
          questions = medium_questions
      elif difficulty == "hard":
          questions = hard_questions
      else:
          print("Invalid choice. Playing easy mode.")
          questions = easy_questions

      # Play the game with the chosen questions...

Mini summary: Add difficulty levels to make the game more interesting.


Lesson 15: Review โ€“ What We Learned in Module Three

In this module, we learned:

  • String methods โ€“ how to manipulate text.
  • Tuples โ€“ immutable lists.
  • Packing and unpacking values.
  • Default arguments and keyword arguments in functions.
  • The power of len() and range().
  • List comprehensions โ€“ a shorter way to build lists.
  • How to build a complete "Millionaire Quiz Game" project.
  • How to add difficulty levels to a game.

You now have the skills to build real projects with Python!


6. Key Vocabulary

  • String Method: A function that works on strings (like upper(), lower()).
  • Tuple: An immutable list (cannot be changed).
  • Packing: Putting multiple values into a tuple.
  • Unpacking: Taking values out of a tuple.
  • Default Argument: A parameter with a default value.
  • Keyword Argument: Passing arguments by name.
  • List Comprehension: A shorter way to create lists.
  • Immutable: Cannot be changed.

7. Important Concepts

  • String methods make text processing easy: You can clean, format, and change text.
  • Tuples protect data: Use them when you don't want data to change.
  • Packing and unpacking are powerful: They make it easy to work with multiple values.
  • Default and keyword arguments make functions flexible: They are easier to use.
  • List comprehensions are concise: They make your code shorter.
  • Building projects is the best way to learn: Apply everything you know.

8. Step-by-step Explanations

How to build a quiz game:

  1. Plan your questions and store them in a data structure.
  2. Write a function to display a question and get the answer.
  3. Write the main game loop that goes through all questions.
  4. Keep track of the score.
  5. Display the final score and a message.
  6. Enhance with difficulty levels, timers, or other features.

9. Real-life Examples

  • A quiz app on a phone.
  • A game show like "Who Wants to Be a Millionaire?"
  • A school test with multiple-choice questions.
  • An online survey with questions.
  • A trivia night at a bar or restaurant.

10. Nigerian Examples

  • A quiz game about Nigerian history and culture.
  • A trivia app for Nigerian students.
  • A game about Nigerian states and capitals.
  • A quiz about Nigerian celebrities.
  • A learning app for Nigerian children.

11. Fun Examples Children Can Relate To

  • A quiz about favourite cartoons.
  • A game about animals and their sounds.
  • A trivia game about video games.
  • A quiz about popular movies.
  • A game about school subjects.

12. Everyday Examples

  • ๐Ÿ“ฑ A mobile quiz app.
  • ๐ŸŽฎ A game show on TV.
  • ๐Ÿ“ A school test.
  • ๐Ÿ“Š A survey with multiple-choice questions.
  • ๐ŸŽฏ A trivia night with friends.

13. Teacher Notes

This module is project-focused. Let students work on the quiz game step by step. Encourage them to add their own features โ€“ more questions, difficulty levels, timers, or graphics. Pair programming works well here.


14. Parent Tips

Play the quiz game with your child! Let them quiz you on the questions they created. Encourage them to add more questions from subjects they enjoy. Celebrate their achievement in building a complete game!


15. Interesting Facts

  • ๐ŸŽฎ The first video game was created in 1958!
  • ๐Ÿ“Š "Who Wants to Be a Millionaire?" first aired in 1999.
  • ๐Ÿง  The average human can remember about 7 things at once.
  • ๐Ÿ’ป Python was named after Monty Python, not the snake.
  • ๐Ÿ† Some people have won real million-dollar prizes on quiz shows!

16. Did You Know?

  • You can build a quiz game with just a few lines of Python!
  • Many online learning platforms use quiz games to teach.
  • Quiz games are a great way to study for tests.
  • You can add a timer to make the game more exciting.
  • You can store questions in a file to make the game longer.

17. Remember This

  • โœ… Strings have many useful methods.
  • โœ… Tuples cannot be changed.
  • โœ… Packing and unpacking are powerful.
  • โœ… Default and keyword arguments make functions flexible.
  • โœ… List comprehensions make code shorter.
  • โœ… Building projects is the best way to learn.

18. Common Mistakes

  • โŒ Trying to change a tuple โ€“ remember, tuples are immutable!
  • โŒ Forgetting to convert user input to the correct format.
  • โŒ Not handling when the user enters an invalid choice.
  • โŒ Forgetting to check the length of strings before accessing characters.
  • โŒ Using a list comprehension that is too complex to read.

19. Best Practices

  • โœ… Use tuples for data that shouldn't change.
  • โœ… Use string methods to clean and format text.
  • โœ… Use default and keyword arguments for clarity.
  • โœ… Use list comprehensions for simple transformations.
  • โœ… Always test your code with different inputs.

20. Illustrations

Quiz Game Flowchart

  +-------------+     +-------------+     +-------------+     +-------------+
  |  START      | --> |  SHOW       | --> |  GET        | --> |  CHECK      |
  |  GAME       |     |  QUESTION   |     |  USER       |     |  ANSWER     |
  +-------------+     +-------------+     |  INPUT      |     +-------------+
                                  |       +-------------+           |
                                  |                            +-------------+
                                  |                            |  CORRECT?   |
                                  |                            +-------------+
                                  |                            |       |
                                  |                            V       V
                                  |                      +-------------+   +-------------+
                                  |                      |  SCORE++    |   |  SHOW       |
                                  |                      +-------------+   |  CORRECT    |
                                  |                                       |  ANSWER     |
                                  V                                       +-------------+
                          +-------------+                                       |
                          |  MORE       | <------------------------------------+
                          |  QUESTIONS? |
                          +-------------+
                                | Yes
                                V
                          +-------------+
                          |  FINAL      |
                          |  SCORE      |
                          +-------------+
                                V
                          +-------------+
                          |  END GAME   |
                          +-------------+

Comparison Table โ€“ Data Structures

Data StructureOrderedMutableAllows DuplicatesExample
ListYesYesYes[1, 2, 3, 3]
TupleYesNoYes(1, 2, 3, 3)
SetNoYesNo{1, 2, 3}
DictionaryYes (Python 3.7+)YesKeys: No, Values: Yes{"a": 1, "b": 2}

Comparison Table โ€“ String Methods

MethodWhat It DoesExample
upper()Converts to uppercase"hello".upper() โ†’ "HELLO"
lower()Converts to lowercase"HELLO".lower() โ†’ "hello"
strip()Removes spaces from ends" hi ".strip() โ†’ "hi"
split()Splits into a list"a,b,c".split(",") โ†’ ["a","b","c"]
join()Joins a list into a string",".join(["a","b"]) โ†’ "a,b"
replace()Replaces text"hi".replace("i","o") โ†’ "ho"

Timeline โ€“ Module Three Learning Path

  +------------------------------------------------------------------+
  |  Lesson 1: Review of Modules One and Two                         |
  |  Lesson 2: String Methods โ€“ Making Text Smarter                  |
  |  Lesson 3: More String Methods โ€“ Formatting and Joining          |
  |  Lesson 4: What is a Tuple?                                      |
  |  Lesson 5: Packing and Unpacking                                 |
  |  Lesson 6: Default Arguments in Functions                        |
  |  Lesson 7: Keyword Arguments in Functions                        |
  |  Lesson 8: The Power of len() and range()                        |
  |  Lesson 9: List Comprehensions โ€“ A Shorter Way to Build Lists    |
  |  Lesson 10: Building the Millionaire Quiz Game โ€“ Planning        |
  |  Lesson 11: Building the Millionaire Quiz Game โ€“ Step 1: Data   |
  |  Lesson 12: Building the Millionaire Quiz Game โ€“ Step 2: Display |
  |  Lesson 13: Building the Millionaire Quiz Game โ€“ Step 3: Main   |
  |  Lesson 14: Enhancing the Quiz Game โ€“ Adding Difficulty Levels   |
  |  Lesson 15: Review                                               |
  +------------------------------------------------------------------+

23. End-of-Module Summary

In this module, we have taken our Python skills to a new level. We learned powerful string methods that let us manipulate text easily. We discovered tuples โ€“ immutable lists that protect our data from being changed. We mastered packing and unpacking, which makes working with multiple values a breeze. We learned about default and keyword arguments, which make our functions more flexible and our code clearer.

We explored len() and range(), two essential tools for loops. We learned about list comprehensions โ€“ a shorter, more elegant way to build lists. Most importantly, we built a complete "Millionaire Quiz Game" project that used everything we learned. We even added difficulty levels to make it more interesting.

You now have the confidence and skills to build real projects with Python. You can create games, apps, and tools that solve problems and entertain people. The journey continues โ€“ keep coding, keep exploring, and keep having fun!


24. Frequently Asked Questions

  1. What are string methods? Functions that work on strings, like upper() and lower().
  2. What is a tuple? A list that cannot be changed.
  3. What is packing and unpacking? Packing groups values; unpacking separates them.
  4. What is a default argument? A parameter with a default value if not provided.
  5. What is a keyword argument? Passing arguments by name.
  6. What does len() do? Returns the length of a collection.
  7. What does range() do? Generates a sequence of numbers.
  8. What is a list comprehension? A shorter way to create lists.
  9. What is the best way to learn Python? Build projects!
  10. Can I make games with Python? Yes! You just built a quiz game.

25. Review Questions

  1. What does upper() do?
  2. What does split() do?
  3. What is the difference between a list and a tuple?
  4. What is unpacking?
  5. What is a default argument?
  6. What is a keyword argument?
  7. What does len() return?
  8. What does range(5) generate?
  9. What is a list comprehension?
  10. How do you store questions in a quiz game?
  11. How do you check if an answer is correct?
  12. How do you keep score in a quiz game?
  13. How do you add difficulty levels?
  14. What is the benefit of using tuples?
  15. What is the benefit of using list comprehensions?

26. Fill-in-the-Blank

  1. _____ converts a string to uppercase. (upper())
  2. _____ splits a string into a list. (split())
  3. A _____ is an immutable list. (tuple)
  4. _____ takes values out of a tuple. (Unpacking)
  5. A _____ argument has a default value. (default)
  6. _____ returns the length of a collection. (len())
  7. _____ generates a sequence of numbers. (range())
  8. A _____ is a shorter way to create lists. (list comprehension)
  9. In a quiz game, you store questions in a _____ or list. (tuple)
  10. You use _____ to check if an answer is correct. (if/else)

27. True or False

  1. Tuples can be changed. (False)
  2. Lists can be changed. (True)
  3. upper() converts a string to lowercase. (False)
  4. split() splits a string into a list. (True)
  5. Unpacking takes values out of a tuple. (True)
  6. Default arguments cannot be used in functions. (False)
  7. len() returns the length of a string. (True)
  8. range(5) generates numbers from 1 to 5. (False โ€“ it generates 0 to 4)
  9. List comprehensions make code longer. (False)
  10. You can build games with Python. (True)

28. Multiple Choice Questions

  1. What does upper() do?
    A) Converts to uppercase B) Converts to lowercase C) Removes spaces D) Splits the string Answer: A
  2. What is a tuple?
    A) A mutable list B) An immutable list C) A dictionary D) A set Answer: B
  3. What is unpacking?
    A) Putting values into a tuple B) Taking values out of a tuple C) Creating a list D) Deleting a tuple Answer: B
  4. What is a default argument?
    A) A parameter with a default value B) A required parameter C) A keyword argument D) A return value Answer: A
  5. What does len() do?
    A) Returns the length B) Returns the sum C) Returns the average D) Returns the maximum Answer: A
  6. What does range(5) generate?
    A) 0, 1, 2, 3, 4 B) 1, 2, 3, 4, 5 C) 0, 1, 2, 3 D) 1, 2, 3, 4 Answer: A
  7. What is a list comprehension?
    A) A shorter way to create lists B) A type of loop C) A type of function D) A type of tuple Answer: A
  8. How do you check if an answer is correct?
    A) Using if/else B) Using for loop C) Using while loop D) Using try/except Answer: A
  9. What is a keyword argument?
    A) Passing arguments by name B) Passing arguments by position C) A default argument D) A return value Answer: A
  10. Which data structure is immutable?
    A) Tuple B) List C) Dictionary D) Set Answer: A
  11. Which method joins a list into a string?
    A) join() B) split() C) upper() D) strip() Answer: A
  12. Which method removes spaces from ends?
    A) strip() B) split() C) upper() D) lower() Answer: A
  13. What is a Nigerian example of a quiz game?
    A) A game about Nigerian states B) A game about US states C) A game about European countries D) A game about animals Answer: A
  14. Can you build games with Python?
    A) Yes B) No Answer: A
  15. Is Python free?
    A) Yes B) No Answer: A

29. Matching Exercises

TermDefinition
upper()A) Splits into a list
split()B) Converts to uppercase
TupleC) Immutable list
len()D) Returns length
range()E) Generates numbers

Answers: upper()-B, split()-A, Tuple-C, len()-D, range()-E


30. Short Answer Questions

  1. What is a tuple?
  2. What is the difference between split() and join()?
  3. What is unpacking?
  4. What is a default argument?
  5. What does range() do?
  6. What is a list comprehension?
  7. How do you build a quiz game?

31. Scenario-based Exercises

Scenario 1: You want to create a quiz about Nigerian states and their capitals.

Task: Write the code to store 3 questions and display them.

Answer:

  questions = [
      ("What is the capital of Lagos?", "Ikeja", "Lagos", "Abuja", "Ibadan", "A"),
      ("What is the capital of Oyo?", "Ibadan", "Oyo", "Abuja", "Lagos", "A"),
      ("What is the capital of Kano?", "Kano", "Abuja", "Ibadan", "Lagos", "A")
  ]

  for q in questions:
      print(q[0])
      print("A. " + q[1])
      print("B. " + q[2])
      print("C. " + q[3])
      print("D. " + q[4])
      answer = input("Your answer: ").upper()
      if answer == q[5]:
          print("Correct!")
      else:
          print("Wrong! Correct answer is " + q[5])

32. Group Activity

In groups of three, build an enhanced version of the Millionaire Quiz Game. Add a timer, lifelines (like 50/50), and a leaderboard. Each person takes a different part of the project.


33. Individual Activity

Write a quiz game on a topic you are passionate about โ€“ sports, music, movies, or anything else. Include at least 10 questions and a scoring system.


34. Classroom Discussion Questions

  • What was the most fun part of building the quiz game?
  • What would you add to make the game better?
  • How can you store questions in a file?
  • How can you add a timer to the game?
  • What other games can you build with Python?

35. Mini Project

Build a "Millionaire Quiz Game" with the following features:

  1. At least 10 questions.
  2. Options A, B, C, D.
  3. Score tracking.
  4. Final score display with a message.
  5. Difficulty levels (easy, medium, hard).

36. Practical Assignment

Write a complete quiz game about Nigerian culture. Include:

  1. Questions about Nigerian history, food, states, and languages.
  2. At least 15 questions.
  3. Score tracking.
  4. Feedback for correct and incorrect answers.
  5. Ability to play again.

37. Challenge Exercise

Enhance the quiz game with a timer โ€“ each question must be answered in 10 seconds. If the time runs out, the question is marked wrong. Use the time module to implement this.


38. Quiz Answers

Fill-in-the-blank: 1. upper(), 2. split(), 3. tuple, 4. Unpacking, 5. default, 6. len(), 7. range(), 8. list comprehension, 9. tuple, 10. if/else

True/False: 1F, 2T, 3F, 4T, 5T, 6F, 7T, 8F, 9F, 10T

Multiple Choice: 1A, 2B, 3B, 4A, 5A, 6A, 7A, 8A, 9A, 10A, 11A, 12A, 13A, 14A, 15A

Matching: upper()-B, split()-A, Tuple-C, len()-D, range()-E


39. Key Takeaways

  • ๐Ÿ”น String methods like upper(), lower(), split(), join() are powerful tools.
  • ๐Ÿ”น Tuples are immutable lists โ€“ they cannot be changed.
  • ๐Ÿ”น Packing and unpacking make working with multiple values easy.
  • ๐Ÿ”น Default and keyword arguments make functions flexible and clear.
  • ๐Ÿ”น len() and range() are essential for loops.
  • ๐Ÿ”น List comprehensions make code shorter and cleaner.
  • ๐Ÿ”น Building projects like a quiz game is the best way to learn.
  • ๐Ÿ”น You can build amazing things with Python!

40. Preparation for the Next Module

Congratulations! You have completed Level 1 of Python Programming. You have learned all the fundamentals โ€“ from variables to functions, from lists to dictionaries, from files to classes, and from strings to building games!

In Level 2, you will take your skills even further. You will learn:

  • How to work with external libraries.
  • How to build graphical user interfaces (GUIs).
  • How to work with APIs to get data from the internet.
  • How to build web applications with Python.
  • How to use Python for data science.
  • How to build even more advanced games.

You have built a strong foundation. The world of Python is vast and exciting. Keep coding, keep exploring, and never stop learning!


๐ŸŽ‰ Congratulations! You have completed Level 1 of Python Programming! ๐ŸŽ‰

You are now ready for Level 2 โ€“ Advanced Python!

5

Practice Lab

Practice Lab ยท Python Level 1

๐Ÿ Practice Lab: Python Programming Level 1

1. Lab Title

Practice Lab: Python Programming Level 1 โ€“ Hands-On Exercises


2. Lab Introduction

Welcome, young coder! You have completed all the lessons in Level 1 of Python Programming. Now it's time to practice what you have learned. This lab is full of hands-on exercises that will help you become a better programmer. Each exercise is designed to test a specific skill you learned in the course.

Don't worry if you make mistakes โ€“ that's how we learn! Try each exercise on your own first. If you get stuck, look back at your notes or ask for help. The goal is to practice, not to be perfect. Let's get coding!


3. Learning Objectives

After completing this lab, you will be able to:

  • Write Python programs from scratch using all the concepts you learned.
  • Use variables, data types, and input/output correctly.
  • Write conditional statements (if/elif/else) to make decisions.
  • Use loops (while and for) to repeat tasks.
  • Work with lists, tuples, dictionaries, and sets.
  • Write functions with parameters and return values.
  • Read from and write to files.
  • Handle errors using try/except.
  • Build small projects using all these skills.

4. Warm-up Story

Chidi's Coding Practice

Chidi had learned so much about Python. He could write variables, loops, functions, and even build a quiz game. But his teacher said, "Chidi, the best way to get better at coding is to practice every day. Just like playing football or learning an instrument โ€“ practice makes perfect!"

Chidi decided to practice coding every day. He started with simple exercises โ€“ printing messages, calculating numbers, and asking for user input. Then he moved to harder exercises โ€“ writing functions, working with lists, and building small programs. Each day, he got a little better. Soon, he could solve problems that were difficult before.

Now, it's your turn to practice! This lab has many exercises to help you become a confident Python programmer.


5. Lab Exercises

Exercise 1: Hello, World! (Print Statements)

Task: Write a Python program that prints the following messages:

  1. "Hello, World!"
  2. "Welcome to Python Programming!"
  3. "I am learning to code!"

Expected Output:

Hello, World!
Welcome to Python Programming!
I am learning to code!

Hint: Use the print() function.


Exercise 2: Variables and Data Types

Task: Create a program that does the following:

  1. Create a variable called name and store your name.
  2. Create a variable called age and store your age.
  3. Create a variable called height and store your height in meters (e.g., 1.55).
  4. Create a variable called is_student and store True.
  5. Print all the variables.

Example Output:

Name: Ada
Age: 10
Height: 1.55
Is student: True

Hint: Use print("Name:", name) or f-strings.


Exercise 3: User Input

Task: Write a program that does the following:

  1. Ask the user for their name.
  2. Ask the user for their favourite food.
  3. Print a message like "Hello [name]! [food] sounds delicious!"

Example Interaction:

What is your name? Ada
What is your favourite food? Jollof Rice
Hello Ada! Jollof Rice sounds delicious!

Hint: Use input() to get user input and print() to display the result.


Exercise 4: Conditional Statements (if/else)

Task: Write a program that asks the user for their age. If the age is 18 or above, print "You are an adult." Otherwise, print "You are a child."

Example Interaction 1:

How old are you? 20
You are an adult.

Example Interaction 2:

How old are you? 10
You are a child.

Hint: Use int() to convert user input to an integer.


Exercise 5: More Conditional Statements (elif)

Task: Write a program that asks the user for a number and does the following:

  1. If the number is positive, print "Positive".
  2. If the number is negative, print "Negative".
  3. If the number is zero, print "Zero".

Example Interactions:

Enter a number: 5
Positive

Enter a number: -3
Negative

Enter a number: 0
Zero

Hint: Use if, elif, and else.


Exercise 6: While Loop

Task: Write a program that uses a while loop to print numbers from 1 to 10.

Expected Output:

1
2
3
4
5
6
7
8
9
10

Hint: Start a counter at 1 and increment it until it reaches 10.


Exercise 7: For Loop

Task: Write a program that uses a for loop to print the numbers 1 to 10.

Expected Output:

1
2
3
4
5
6
7
8
9
10

Hint: Use range(1, 11).


Exercise 8: Lists

Task: Write a program that does the following:

  1. Create a list of 5 favourite fruits.
  2. Print the first fruit.
  3. Print the last fruit.
  4. Add a new fruit to the list.
  5. Remove the second fruit.
  6. Print the final list.

Example Output:

First fruit: Mango
Last fruit: Orange
Final list: ['Mango', 'Banana', 'Orange', 'Pineapple']

Hint: Use list methods like append(), remove(), and indexing.


Exercise 9: Looping Through a List

Task: Write a program that loops through a list of numbers and prints each number multiplied by 2.

Example Input:

numbers = [1, 2, 3, 4, 5]

Expected Output:

2
4
6
8
10

Hint: Use a for loop to go through the list.


Exercise 10: Dictionaries

Task: Write a program that does the following:

  1. Create a dictionary that stores the names and ages of 3 people.
  2. Print the age of one person.
  3. Add a new person.
  4. Change the age of an existing person.
  5. Print the final dictionary.

Example Output:

Ada's age: 10
Final dictionary: {'Ada': 10, 'Chidi': 12, 'Bola': 11, 'Tunde': 9}

Hint: Use curly braces {} to create a dictionary.


Exercise 11: Functions

Task: Write a function called greet that takes a name as a parameter and prints "Hello, [name]!". Then call the function with three different names.

Expected Output:

Hello, Ada!
Hello, Chidi!
Hello, Bola!

Hint: Use def greet(name):.


Exercise 12: Functions with Return Values

Task: Write a function called add that takes two numbers as parameters and returns their sum. Then call the function with different numbers and print the results.

Example Output:

5 + 3 = 8
10 + 20 = 30
7 + 2 = 9

Hint: Use return to send the value back.


Exercise 13: File Writing

Task: Write a program that does the following:

  1. Ask the user for their name.
  2. Ask the user for their age.
  3. Write this information to a file called "user_info.txt".

Hint: Use open("user_info.txt", "w") and write().


Exercise 14: File Reading

Task: Write a program that reads and prints the contents of a file called "user_info.txt". If the file doesn't exist, handle the error with try/except.

Hint: Use open("user_info.txt", "r") and read(). Use try/except to handle the error.


Exercise 15: Error Handling

Task: Write a program that asks the user for a number. If the user enters something that is not a number, print "That is not a valid number!" and ask again.

Hint: Use a while loop and try/except.


Exercise 16: Tuples

Task: Create a tuple with 5 of your favourite things (movies, foods, games, etc.). Print the tuple. Then, try to change an item (it should cause an error).

Hint: Use parentheses () for tuples.


Exercise 17: Packing and Unpacking

Task: Create a tuple with three values (name, age, city). Unpack the tuple into three variables and print them.

Example Output:

Name: Ada
Age: 10
City: Lagos

Hint: Use name, age, city = my_tuple.


Exercise 18: Sets

Task: Create a set of 5 favourite colours. Add a new colour. Try to add a duplicate โ€“ notice it doesn't change. Print the set.

Hint: Use curly braces {} for sets.


Exercise 19: List Comprehensions

Task: Use a list comprehension to create a list of squares of numbers from 1 to 10.

Expected Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Hint: Use [i * i for i in range(1, 11)].


Exercise 20: Mini Project โ€“ Simple Calculator

Task: Build a simple calculator program that:

  1. Asks the user for two numbers.
  2. Asks the user for an operation (+, -, *, /).
  3. Performs the calculation and prints the result.
  4. Handles errors if the user enters invalid input.

Example Interaction:

Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): +
10 + 5 = 15

Hint: Use functions, if/elif/else, and try/except.


6. Key Vocabulary

  • Variable: A container for storing data.
  • Data Type: The kind of data (integer, string, float, boolean).
  • Input: Data given to a program by the user.
  • Output: Data displayed by a program.
  • Conditional: A statement that makes a decision (if/else).
  • Loop: Code that repeats (while, for).
  • List: A collection of items (mutable).
  • Tuple: A collection of items (immutable).
  • Dictionary: Key-value pairs.
  • Set: A collection of unique items.
  • Function: A reusable block of code.
  • File: A place to store data permanently.
  • Error Handling: Catching and managing errors.

7. Important Concepts

  • Practice makes perfect: The more you code, the better you become.
  • Read the error messages: They tell you what is wrong.
  • Break problems into small steps: Don't try to solve everything at once.
  • Use comments: They help you understand your code.
  • Test your code often: Run it after each change.

8. Step-by-step Explanations

How to complete a lab exercise:

  1. Read the exercise carefully.
  2. Understand what the program should do.
  3. Write the code step by step.
  4. Run the program and test it.
  5. If there is an error, read the error message and fix it.
  6. When it works, move to the next exercise.

9. Real-life Examples

  • A calculator app on a phone.
  • A contact list in a phone book.
  • A shopping list for groceries.
  • A grade calculator for school.
  • A game on a computer.

10. Nigerian Examples

  • A program that converts Naira to Dollars.
  • A program that lists Nigerian states.
  • A program that calculates market prices.
  • A program that helps with school grades.
  • A program that stores contact information.

11. Fun Examples Children Can Relate To

  • A program that tells a joke.
  • A program that counts down to a birthday.
  • A program that stores favourite games.
  • A program that asks for a favourite cartoon.
  • A program that makes a simple game.

12. Everyday Examples

  • ๐Ÿ“ฑ A calculator.
  • ๐Ÿ“ A to-do list.
  • ๐Ÿ“… A birthday reminder.
  • ๐Ÿ›’ A shopping list.
  • ๐Ÿ“Š A grade calculator.

13. Teacher Notes

This lab is designed to be self-paced. Students can work at their own speed. Encourage them to help each other. Circulate and provide guidance. Celebrate their achievements, no matter how small. Remind them that making mistakes is part of learning.


14. Parent Tips

Help your child set up their coding environment. Sit with them as they work on the exercises. Ask questions like "What do you think this code does?" and "What happens if you change this value?" Celebrate their progress and encourage them to keep going.


15. Interesting Facts

  • ๐Ÿ’ป The first computer programmer was a woman named Ada Lovelace.
  • ๐Ÿ Python was named after Monty Python, not the snake.
  • ๐Ÿ“Š Python is used by Google, NASA, and Instagram.
  • ๐ŸŒ Python is one of the most popular programming languages in the world.
  • ๐ŸŽฎ You can build games with Python!

16. Did You Know?

  • Python is used in artificial intelligence and machine learning.
  • Many Nigerian developers use Python to build apps.
  • Python is free and open source.
  • You can use Python to build websites.
  • Python is a great first language to learn.

17. Remember This

  • โœ… Practice every day.
  • โœ… Read error messages โ€“ they help you.
  • โœ… Break problems into small steps.
  • โœ… Test your code often.
  • โœ… Help others โ€“ it helps you too!

18. Common Mistakes

  • โŒ Forgetting colons : after if, else, while, for, def.
  • โŒ Forgetting to indent code.
  • โŒ Using = instead of == for comparison.
  • โŒ Not converting input to the right data type.
  • โŒ Forgetting to close parentheses or quotes.

19. Best Practices

  • โœ… Use meaningful variable names.
  • โœ… Add comments to explain your code.
  • โœ… Use consistent indentation.
  • โœ… Test your code frequently.
  • โœ… Start small and add features gradually.

20. Illustrations

Lab Exercise Flowchart

  +-------------+     +-------------+     +-------------+     +-------------+
  |  READ       | --> |  UNDERSTAND | --> |  WRITE      | --> |  TEST       |
  |  EXERCISE   |     |  THE TASK   |     |  THE CODE   |     |  THE CODE   |
  +-------------+     +-------------+     +-------------+     +-------------+
       |                                                           |
       |                                                           V
       |                                                  +-------------+
       +--------------------------------------------------|  DEBUG      |
                                                          |  IF NEEDED  |
                                                          +-------------+
                                                               |
                                                               V
                                                          +-------------+
                                                          |  MOVE TO    |
                                                          |  NEXT       |
                                                          |  EXERCISE   |
                                                          +-------------+

Comparison Table โ€“ Data Structures

Data StructureMutableOrderedDuplicatesExample
ListYesYesYes[1, 2, 3]
TupleNoYesYes(1, 2, 3)
DictionaryYesYes (3.7+)Keys: No, Values: Yes{"a": 1, "b": 2}
SetYesNoNo{1, 2, 3}

23. End-of-Lab Summary

Great job completing this practice lab! You have written many programs using all the skills you learned in Level 1. You used variables, data types, input/output, conditional statements, loops, lists, dictionaries, functions, files, error handling, tuples, sets, and list comprehensions.

Remember, becoming a great programmer takes time and practice. Keep coding every day, even if it's just for 15 minutes. Try building your own projects โ€“ a game, a calculator, or a personal diary. The more you code, the better you will become. You are on the right path!


24. Frequently Asked Questions

  1. What should I do if I get stuck? Read the error message, look at your code, and try to find the mistake. You can also ask a teacher or friend for help.
  2. How many exercises should I do in one day? As many as you can. Quality is more important than quantity. Take your time to understand each exercise.
  3. Can I use the internet to help? Yes! Looking up solutions and examples is a great way to learn. Just make sure you understand the code you use.
  4. What if my code doesn't work? That's normal! Debugging is part of programming. Try to find the error, fix it, and try again.
  5. What is the most important thing to remember? Practice, practice, practice! The more you code, the better you become.
  6. Can I share my code with others? Yes! Sharing code and helping others is a great way to learn.
  7. What if I can't finish all exercises? That's okay. Do what you can and come back to the rest later.
  8. Can I use these exercises for my portfolio? Yes! These exercises show your skills and progress.
  9. What should I learn next? After Level 1, you can move to Level 2 or start building your own projects.
  10. Is Python a good language to learn? Yes! Python is one of the most popular and beginner-friendly programming languages.

25. Review Questions

  1. How do you print a message in Python?
  2. How do you get user input?
  3. What is the difference between = and ==?
  4. What does if/else do?
  5. How do you write a while loop?
  6. How do you write a for loop?
  7. What is a list?
  8. How do you add an item to a list?
  9. What is a dictionary?
  10. How do you define a function?
  11. What does return do?
  12. How do you read from a file?
  13. How do you write to a file?
  14. What is a tuple?
  15. What is a set?

26. Fill-in-the-Blank

  1. _____ prints a message to the screen. (print)
  2. _____ gets user input. (input)
  3. _____ makes decisions in a program. (if)
  4. A _____ loop repeats code as long as a condition is true. (while)
  5. A _____ loop repeats code a set number of times. (for)
  6. A _____ is a collection of items (mutable). (list)
  7. A _____ is a collection of key-value pairs. (dictionary)
  8. A _____ is a reusable block of code. (function)
  9. _____ returns a value from a function. (return)
  10. A _____ is a collection of unique items. (set)

27. True or False

  1. print("Hello") prints Hello. (True)
  2. input() gets user input. (True)
  3. = is used for comparison. (False โ€“ it's used for assignment)
  4. == is used for comparison. (True)
  5. A while loop runs a set number of times. (False โ€“ it runs while a condition is true)
  6. A for loop runs a set number of times. (True)
  7. Lists are immutable. (False โ€“ they are mutable)
  8. Tuples are immutable. (True)
  9. Dictionaries store key-value pairs. (True)
  10. Sets allow duplicate items. (False โ€“ they only store unique items)

28. Multiple Choice Questions

  1. How do you print "Hello" in Python?
    A) echo("Hello") B) print("Hello") C) printf("Hello") D) output("Hello") Answer: B
  2. How do you get user input?
    A) input() B) get() C) read() D) scan() Answer: A
  3. What does if do?
    A) Makes a decision B) Repeats code C) Stores data D) Prints data Answer: A
  4. What is a variable?
    A) A container for data B) A loop C) A function D) A file Answer: A
  5. What is a list?
    A) A collection of items B) A key-value pair C) A loop D) A function Answer: A
  6. What is a dictionary?
    A) Key-value pairs B) A collection of items C) A loop D) A function Answer: A
  7. How do you define a function?
    A) def function_name(): B) function function_name(): C) fun function_name(): D) define function_name(): Answer: A
  8. What does return do?
    A) Sends a value back B) Prints a value C) Loops code D) Creates a variable Answer: A
  9. What is a tuple?
    A) An immutable list B) A mutable list C) A dictionary D) A set Answer: A
  10. What is a set?
    A) A collection of unique items B) A collection of duplicates C) A key-value pair D) A loop Answer: A
  11. Which data structure is immutable?
    A) Tuple B) List C) Dictionary D) Set Answer: A
  12. Which data structure stores unique items?
    A) Set B) List C) Tuple D) Dictionary Answer: A
  13. Which data structure stores key-value pairs?
    A) Dictionary B) List C) Tuple D) Set Answer: A
  14. Can Python be used to build games?
    A) Yes B) No Answer: A
  15. Is Python free?
    A) Yes B) No Answer: A

29. Matching Exercises

TermDefinition
print()A) Gets user input
input()B) Displays output
ifC) Repeats code
whileD) Makes a decision
forE) Repeats a set number of times

Answers: print()-B, input()-A, if-D, while-C, for-E


30. Short Answer Questions

  1. How do you print a message in Python?
  2. How do you get user input?
  3. What is the difference between a list and a tuple?
  4. What is a dictionary?
  5. What is a set?
  6. How do you define a function?
  7. What does return do?

31. Scenario-based Exercises

Scenario 1: You want to store the names of 5 of your friends in a list. Then, you want to print each name one by one.

Task: Write the code to do this.

Answer:

  friends = ["Ada", "Chidi", "Bola", "Tunde", "Kemi"]
  for friend in friends:
      print(friend)

Scenario 2: You want to create a program that asks the user for their age and tells them if they are a child (under 18) or an adult (18 and above).

Task: Write the code to do this.

Answer:

  age = int(input("How old are you? "))
  if age >= 18:
      print("You are an adult.")
  else:
      print("You are a child.")

32. Group Activity

In groups of three, work together to complete all the lab exercises. Each person can take turns being the "driver" (writing code) and the "navigator" (reading and suggesting ideas). Help each other debug and learn.


33. Individual Activity

Choose 3 exercises from this lab that you found most challenging. Redo them from scratch without looking at your previous answers. This will help you understand the concepts better.


34. Classroom Discussion Questions

  • Which exercise was the most challenging? Why?
  • What is one new thing you learned while doing this lab?
  • Which concept do you still find confusing?
  • How can you use Python in your daily life?
  • What project would you like to build next?

35. Mini Project

Build a program that acts as a Personal Diary. The program should:

  1. Ask the user for today's date.
  2. Ask the user to write a diary entry.
  3. Save the entry to a file.
  4. Give the user the option to view all past entries.
  5. Handle errors (e.g., missing file, invalid input).

36. Practical Assignment

Complete all 20 exercises in this lab. For each exercise, write the code, test it, and save it in a file named lab_exercise_X.py (where X is the exercise number). Submit all files to your teacher.


37. Challenge Exercise

Build a program that allows the user to create a To-Do List. The program should:

  1. Allow the user to add tasks.
  2. Allow the user to view all tasks.
  3. Allow the user to mark a task as complete.
  4. Allow the user to delete a task.
  5. Save the tasks to a file.
  6. Load tasks from the file when the program starts.

38. Quiz Answers

Fill-in-the-blank: 1. print, 2. input, 3. if, 4. while, 5. for, 6. list, 7. dictionary, 8. function, 9. return, 10. set

True/False: 1T, 2T, 3F, 4T, 5F, 6T, 7F, 8T, 9T, 10F

Multiple Choice: 1B, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A, 10A, 11A, 12A, 13A, 14A, 15A

Matching: print()-B, input()-A, if-D, while-C, for-E


39. Key Takeaways

  • ๐Ÿ”น Practice is the key to becoming a great programmer.
  • ๐Ÿ”น Read error messages โ€“ they tell you what is wrong.
  • ๐Ÿ”น Break problems into small, manageable steps.
  • ๐Ÿ”น Test your code often to catch errors early.
  • ๐Ÿ”น Help others โ€“ it helps you learn too!
  • ๐Ÿ”น Have fun and enjoy the process of learning.

40. Preparation for the Next Module

Congratulations on completing the practice lab! You have now practiced all the skills from Level 1. You are ready to move on to Level 2 โ€“ Advanced Python Concepts.

In Level 2, you will learn:

  • More advanced functions (lambda, higher-order).
  • Working with modules and libraries.
  • Building graphical user interfaces (GUIs).
  • Web development with Python.
  • Working with data (CSV, JSON).
  • Building larger, more complex projects.

Keep coding, keep exploring, and never stop learning. You have built a strong foundation โ€“ now go and build amazing things!


๐ŸŽ‰ Congratulations! You have completed the Python Programming Level 1 Practice Lab! ๐ŸŽ‰

You are now ready for Level 2 โ€“ Advanced Python Concepts!

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, pass the exam, and unlock Practice Tools plus a verified certificate with your name on it โ€” โ‚ฆ4,000/month.

๐ŸŽ“ Sign Up & Unlock for โ‚ฆ4,000/month
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - try them free for 7 days, no card required.
โ†’