Fundamentals of Python Programming โ Level 1: Your First Steps into Coding
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!
After completing this course, you will be able to:
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
In this course, we learned:
You are now ready to start your coding journey!
How to write a simple program:
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.
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!
+-------------+ +-------------+ +-------------+ +-------------+ | GO TO | --> | DOWNLOAD | --> | RUN | --> | TEST WITH | | PYTHON.ORG | | INSTALLER | | INSTALLER | | "python --version" | +-------------+ +-------------+ +-------------+ +-------------+
| Data Type | What It Is | Example |
|---|---|---|
| Integer | Whole number | 10, 25, 100 |
| String | Text | "Hello", "Ada" |
| Float | Decimal number | 3.14, 2.5 |
| Boolean | True/False | True, False |
| List | Collection of items | [1, 2, 3] |
| Loop Type | When to Use | Example |
|---|---|---|
| while | When you don't know how many times | `while count < 5:` |
| for | When you know how many times | `for i in range(5):` |
| Statement | When it Runs | Example |
|---|---|---|
| if | When condition is true | `if age >= 18:` |
| else | When condition is false | `else:` |
| elif | When first condition is false and another is true | `elif age >= 13:` |
+------------------------------------------------------------------+ | 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 | +------------------------------------------------------------------+
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!
| Term | Definition |
|---|---|
| Python | A) Stores multiple items |
| Variable | B) Reusable block of code |
| List | C) Programming language |
| Function | D) Container for data |
| Comment | E) Note in the code |
Answers: Python-C, Variable-D, List-A, Function-B, Comment-E
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.")
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.
Write a program that asks the user for a number and prints the multiplication table for that number (from 1 to 10).
Build a simple "Quiz Game" program. The program should:
Write a program that acts as a simple calculator. It should:
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.
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
In Level 2, we will build on what you have learned. You will explore more advanced topics like:
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!
Module One: Welcome to Python Programming โ Your First Steps into Coding
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!
After completing this module, you will be able to:
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
In this module, we learned:
input().if/else) to make decisions.while and for) to repeat code.You are now ready to continue your Python journey!
How to write and run a Python program:
.py extension (e.g., hello.py).python filename.py and press Enter.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.
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!
input() gets user input.if/else makes decisions.: after if, else, while, and for.= for comparison instead of ==.age, name).+-------------+ +-------------+ +-------------+ +-------------+ | GO TO | --> | DOWNLOAD | --> | RUN | --> | TEST WITH | | PYTHON.ORG | | INSTALLER | | INSTALLER | | "python --version" | +-------------+ +-------------+ +-------------+ +-------------+
| Data Type | What It Is | Example |
|---|---|---|
| Integer | Whole number | 10, 25, 100 |
| Float | Decimal number | 3.14, 2.5, 0.99 |
| String | Text | "Hello", "Ada", "Lagos" |
| Boolean | True/False | True, False |
| List | Collection of items | [1, 2, 3] |
| Loop Type | When to Use | Example |
|---|---|---|
| while | When you don't know how many times | while count < 5: |
| for | When you know how many times | for i in range(5): |
| Statement | When it Runs | Example |
|---|---|---|
| if | When condition is true | if age >= 18: |
| else | When condition is false | else: |
| elif | When first condition is false and another is true | elif age >= 13: |
+------------------------------------------------------------------+ | 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 | +------------------------------------------------------------------+
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.
if/else do?_____ gets user input. (input())_____ makes decisions. (if)input() asks the user for information. (True)if makes decisions. (True)input() do?if do?| Term | Definition |
|---|---|
| Python | A) Stores multiple items |
| Variable | B) Reusable block of code |
| List | C) Programming language |
| Function | D) Container for data |
| Comment | E) Note in the code |
Answers: Python-C, Variable-D, List-A, Function-B, Comment-E
if/else do?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.")
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.
Write a program that asks the user for a number and prints the multiplication table for that number (from 1 to 10).
Build a simple "Quiz Game" program. The program should:
Write a program that acts as a simple calculator. It should:
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.
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
if/else statements make decisions.while and for) repeat code.In Module Two, we will build on what you have learned. You will explore more advanced topics like:
try/except.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!
Module Two: Diving Deeper into Python โ Dictionaries, Files, and More!
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!
After completing this module, you will be able to:
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.
Before we start new things, let's quickly review what we learned in Module One.
We learned:
input() to get user input.if/else to make decisions.while and for loops to repeat code.def.#.You have a strong foundation. Now, let's build on it!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
In this module, we learned:
You have now built a strong foundation in Python. You are ready for Level 2!
How to read and write files:
open("filename", "r") for reading..read() or loop through lines..close().open("filename", "w")..write().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.
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?"
self parameter in class methods.get() to safely access dictionary keys.with statements.+------------------------------------------+ | DICTIONARY | | +--------------------------------------+ | | | KEY | VALUE | | | |------------|-------------------------| | | | "Ada" | "080-1234-5678" | | | | "Chidi" | "080-8765-4321" | | | | "Bola" | "080-5555-5555" | | | +--------------------------------------+ | +------------------------------------------+
| Data Structure | What It Does | Example |
|---|---|---|
| List | Ordered collection of items | ["Apple", "Banana", "Mango"] |
| Dictionary | Key-value pairs for fast lookups | {"Ada": "080-1234", "Chidi": "080-5678"} |
| Set | Unique items, no duplicates | {"Mango", "Orange", "Banana"} |
| Mode | What It Does | If File Doesn't Exist |
|---|---|---|
| "r" (read) | Reads from a file | Error |
| "w" (write) | Writes to a file (overwrites) | Creates it |
| "a" (append) | Adds to the end of a file | Creates it |
+------------------------------------------------------------------+ | 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 | +------------------------------------------------------------------+
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!
| Term | Definition |
|---|---|
| Dictionary | A) Unique items |
| Set | B) Key-value pairs |
| File | C) Handles errors |
| try/except | D) Sends a value back |
| return | E) Permanent storage |
Answers: Dictionary-B, Set-A, File-E, try/except-C, return-D
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).
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.
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.
Build a simple "Student Grade Manager" program. It should:
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.
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).
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
In Level 2, you will build on everything you have learned. You will explore more advanced concepts like:
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!
Module Three: Building Cool Projects โ Strings, Tuples, and More!
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!
After completing this module, you will be able to:
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!
Before we start new things, let's quickly review what we learned in the first two modules.
From Module One:
input() gets user input.if/elif/else for decisions.while and for loops.def.#.From Module Two:
try/except.append(), sort(), reverse().You have a strong foundation. Now, let's add some more tools to your toolbox!
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.
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.
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.
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.
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.
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.
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.
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.
Now we will build our capstone project โ a "Millionaire Quiz Game". Let's plan it first.
What the game will do:
What we need:
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.
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.
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.
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.
In this module, we learned:
len() and range().You now have the skills to build real projects with Python!
upper(), lower()).How to build a quiz game:
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.
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!
+-------------+ +-------------+ +-------------+ +-------------+
| 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 |
+-------------+
| Data Structure | Ordered | Mutable | Allows Duplicates | Example |
|---|---|---|---|---|
| List | Yes | Yes | Yes | [1, 2, 3, 3] |
| Tuple | Yes | No | Yes | (1, 2, 3, 3) |
| Set | No | Yes | No | {1, 2, 3} |
| Dictionary | Yes (Python 3.7+) | Yes | Keys: No, Values: Yes | {"a": 1, "b": 2} |
| Method | What It Does | Example |
|---|---|---|
| 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" |
+------------------------------------------------------------------+ | 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 | +------------------------------------------------------------------+
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!
upper() and lower().len() do? Returns the length of a collection.range() do? Generates a sequence of numbers.upper() do?split() do?len() return?range(5) generate?_____ converts a string to uppercase. (upper())_____ splits a string into a list. (split())_____ generates a sequence of numbers. (range())upper() converts a string to lowercase. (False)split() splits a string into a list. (True)len() returns the length of a string. (True)range(5) generates numbers from 1 to 5. (False โ it generates 0 to 4)upper() do?len() do?range(5) generate?if/else B) Using for loop C) Using while loop D) Using try/except Answer: Ajoin() B) split() C) upper() D) strip() Answer: Astrip() B) split() C) upper() D) lower() Answer: A| Term | Definition |
|---|---|
| upper() | A) Splits into a list |
| split() | B) Converts to uppercase |
| Tuple | C) Immutable list |
| len() | D) Returns length |
| range() | E) Generates numbers |
Answers: upper()-B, split()-A, Tuple-C, len()-D, range()-E
split() and join()?range() do?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])
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.
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.
Build a "Millionaire Quiz Game" with the following features:
Write a complete quiz game about Nigerian culture. Include:
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.
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
upper(), lower(), split(), join() are powerful tools.len() and range() are essential for loops.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:
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!
Practice Lab: Python Programming Level 1 โ Hands-On Exercises
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!
After completing this lab, you will be able to:
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.
Task: Write a Python program that prints the following messages:
Expected Output:
Hello, World! Welcome to Python Programming! I am learning to code!
Hint: Use the print() function.
Task: Create a program that does the following:
name and store your name.age and store your age.height and store your height in meters (e.g., 1.55).is_student and store True.Example Output:
Name: Ada Age: 10 Height: 1.55 Is student: True
Hint: Use print("Name:", name) or f-strings.
Task: Write a program that does the following:
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.
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.
Task: Write a program that asks the user for a number and does the following:
Example Interactions:
Enter a number: 5 Positive Enter a number: -3 Negative Enter a number: 0 Zero
Hint: Use if, elif, and else.
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.
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).
Task: Write a program that does the following:
Example Output:
First fruit: Mango Last fruit: Orange Final list: ['Mango', 'Banana', 'Orange', 'Pineapple']
Hint: Use list methods like append(), remove(), and indexing.
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.
Task: Write a program that does the following:
Example Output:
Ada's age: 10
Final dictionary: {'Ada': 10, 'Chidi': 12, 'Bola': 11, 'Tunde': 9}
Hint: Use curly braces {} to create a dictionary.
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):.
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.
Task: Write a program that does the following:
Hint: Use open("user_info.txt", "w") and write().
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.
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.
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.
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.
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.
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)].
Task: Build a simple calculator program that:
Example Interaction:
Enter first number: 10 Enter second number: 5 Enter operation (+, -, *, /): + 10 + 5 = 15
Hint: Use functions, if/elif/else, and try/except.
How to complete a lab exercise:
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.
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.
: after if, else, while, for, def.= instead of == for comparison.
+-------------+ +-------------+ +-------------+ +-------------+
| READ | --> | UNDERSTAND | --> | WRITE | --> | TEST |
| EXERCISE | | THE TASK | | THE CODE | | THE CODE |
+-------------+ +-------------+ +-------------+ +-------------+
| |
| V
| +-------------+
+--------------------------------------------------| DEBUG |
| IF NEEDED |
+-------------+
|
V
+-------------+
| MOVE TO |
| NEXT |
| EXERCISE |
+-------------+
| Data Structure | Mutable | Ordered | Duplicates | Example |
|---|---|---|---|---|
| List | Yes | Yes | Yes | [1, 2, 3] |
| Tuple | No | Yes | Yes | (1, 2, 3) |
| Dictionary | Yes | Yes (3.7+) | Keys: No, Values: Yes | {"a": 1, "b": 2} |
| Set | Yes | No | No | {1, 2, 3} |
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!
= and ==?if/else do?return do?_____ prints a message to the screen. (print)_____ gets user input. (input)_____ makes decisions in a program. (if)print("Hello") prints Hello. (True)input() gets user input. (True)= is used for comparison. (False โ it's used for assignment)== is used for comparison. (True)echo("Hello") B) print("Hello") C) printf("Hello") D) output("Hello") Answer: Binput() B) get() C) read() D) scan() Answer: Aif do?def function_name(): B) function function_name(): C) fun function_name(): D) define function_name(): Answer: Areturn do?| Term | Definition |
|---|---|
| print() | A) Gets user input |
| input() | B) Displays output |
| if | C) Repeats code |
| while | D) Makes a decision |
| for | E) Repeats a set number of times |
Answers: print()-B, input()-A, if-D, while-C, for-E
return do?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.")
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.
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.
Build a program that acts as a Personal Diary. The program should:
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.
Build a program that allows the user to create a To-Do List. The program should:
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
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:
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!