Course Introduction
Welcome to the Fundamentals of Coding course! This course is designed for absolute beginners â including curious 10âyearâolds who want to learn how to talk to computers. Coding is like learning a new language, but instead of talking to people, you talk to machines. You give them instructions, and they follow them to do amazing things â from making games to building websites to controlling robots. This course will take you from zero to hero in coding. You will learn the basic building blocks that all programs use, and by the end, you will be able to write your own simple programs. No prior experience is needed â just curiosity and a willingness to learn. Let's start our coding adventure!
This outline gives you a complete roadmap for learning coding. Each module builds on the previous one, so it's best to go in order. You can use this outline to:
Each module includes learning objectives, key concepts, and a suggested time allocation. This course is designed to be flexible â you can learn at your own pace.
This course has 10 modules that will take you from absolute beginner to a confident coder. Each module contains several lessons with handsâon exercises.
Time: 1 week (2â3 hours)
Outcome: Understand what coding is and write your first program.
Time: 1 week (2â3 hours)
Outcome: Learn to think like a programmer and design algorithms.
Time: 1.5 weeks (3â4 hours)
Outcome: Store and manipulate data using variables and data types.
Time: 1 week (2â3 hours)
Outcome: Perform calculations and make comparisons using operators.
Time: 1.5 weeks (3â4 hours)
Outcome: Write programs that make decisions using conditionals.
Time: 1.5 weeks (3â4 hours)
Outcome: Write programs that repeat actions using loops.
Time: 1.5 weeks (3â4 hours)
Outcome: Organise and manipulate data using lists, tuples, and dictionaries.
Time: 1.5 weeks (3â4 hours)
Outcome: Write reusable code using functions and modules.
Time: 1 week (2â3 hours)
Outcome: Debug programs and solve coding problems confidently.
Time: 2 weeks (4â6 hours)
Outcome: Build a complete program from scratch and showcase your skills.
| Module | Topic | Suggested Time |
|---|---|---|
| 1 | What is Coding? | 1 week |
| 2 | Thinking Like a Programmer | 1 week |
| 3 | Variables and Data Types | 1.5 weeks |
| 4 | Operators and Expressions | 1 week |
| 5 | Control Flow â Making Decisions | 1.5 weeks |
| 6 | Loops â Repeating Actions | 1.5 weeks |
| 7 | Lists and Data Structures | 1.5 weeks |
| 8 | Functions â Reusing Code | 1.5 weeks |
| 9 | Debugging and ProblemâSolving | 1 week |
| 10 | Final Project | 2 weeks |
Upon completion of this course, you will have built several projects and demonstrated your understanding of core coding concepts. You can receive a certificate of completion if you:
Once you have mastered the fundamentals, you can move on to advanced topics:
The Fundamentals of Coding course is your first step into the world of programming. You will learn how to think like a programmer, write code, solve problems, and build real projects. By the end, you will have a strong foundation that will allow you to learn any programming language or go deeper into any area of technology. Coding is a superpower â it lets you create, automate, and bring your ideas to life. This course gives you that superpower. Ready to begin? Let's code!
You have seen the complete roadmap. Now it's time to begin the journey. Open Module 1: What is Coding? and take your first step into the world of programming. Remember, every expert was once a beginner. You've got this!
Module Introduction
Welcome to the wonderful world of coding! Have you ever wondered how video games work, how websites are made, or how your favourite apps know what to do when you tap a button? The answer is coding! Coding is how we give instructions to computers. It is like learning a new language â but instead of talking to people, you talk to machines. In this module, we will learn what coding is, why it is important, and how to write our very first simple programs. No prior experience is needed â just bring your curiosity and imagination. Let's begin our coding adventure!
Emeka is 10 years old. He loves playing video games. One day, he asked his older sister, âHow does the game know what to do when I press a button?â His sister smiled and said, âIt's because of coding! Every time you press a button, the game follows instructions that someone wrote in a special language.â Emeka was curious. His sister opened her laptop and showed him a simple program. She wrote: âprint('Hello, Emeka!')â and clicked ârun.â The computer showed âHello, Emeka!â on the screen. Emeka was amazed! He tried changing it to his friend's name, and it worked. He realized that coding is like giving a computer a recipe â you tell it what to do, and it follows your instructions exactly. From that day, Emeka wanted to learn everything about coding. And now, you can too!
Definition: Coding is the process of giving instructions to a computer to make it do something. It is like writing a recipe that the computer follows step by step.
Why it's important: Coding is how we create all the digital things we love â games, apps, websites, and even robots!
Simple explanation: Think of coding like giving a robot a list of chores. You tell it âvacuum the floor,â then âclean the windows,â and the robot does exactly what you say.
Realâlife example: A traffic light works because of code â it says âturn red, wait 5 seconds, turn green, wait 5 seconds, repeat.â
School example: Your teacher uses a program to show videos on the screen. That program is written in code.
Home example: Your microwave uses code to cook food for the right amount of time.
Nigerian example: The ATM machine at the bank uses code to ask for your PIN and give you cash.
+------------------------------------------+ | What is Coding? | |------------------------------------------+ | Coding is telling a computer what to do. | | It is like writing a recipe. | | | | Recipe for a cake: | | 1. Mix flour and sugar. | | 2. Add eggs. | | 3. Bake for 30 minutes. | | | | Code for a game: | | 1. If button pressed, jump. | | 2. If jump, add points. | | 3. If points = 10, you win! | +------------------------------------------+
Mini summary: Coding is giving a computer a list of instructions to follow. It is how we make digital things work.
Definition: Coding is important because it powers almost everything that uses electricity â from phones to cars to hospitals.
Why it's important: Without coding, we wouldn't have the internet, social media, video games, or even selfâdriving cars.
Simple explanation: Coding is like the "magic" that makes technology work. It is everywhere!
Realâlife example: Your phone's calculator app is a program written in code.
School example: The system your school uses to take attendance is built with code.
Home example: The smart TV remote uses code to change channels.
Nigerian example: The traffic control system in Lagos uses code to manage traffic lights.
+------------------------------------------+ | Why is Coding Important? | |------------------------------------------+ | Coding is everywhere! | | - Phones | | - Computers | | - Games | | - Cars | | - Hospitals | | - Schools | | - Banks | | | | Without coding, the world would be | | very different! | +------------------------------------------+
Mini summary: Coding is important because it makes our modern world work. It is used in almost every device we use.
Definition: Coding is the act of writing instructions. Programming is a bigger process that includes planning, designing, testing, and coding. Often, people use the words interchangeably.
Why it's important: Understanding the difference helps you know what you are learning. Coding is part of programming.
Simple explanation: Think of coding like writing a single sentence, and programming like writing a whole book. Coding is one part of programming.
Realâlife example: A chef follows a recipe (coding), but creating a new recipe from scratch is like programming.
School example: Writing one line of code is coding. Writing a whole game is programming.
Home example: Setting the timer on your microwave is like coding. Designing a whole smart kitchen is like programming.
Nigerian example: Writing code for a mobile app is coding. Designing the entire app â including the user interface and testing â is programming.
+------------------------------------------+ | Coding vs Programming | |------------------------------------------+ | Coding = Writing instructions | | Programming = Coding + Planning + Testing| | | | Coding is a part of programming. | | Programming is the whole process. | +------------------------------------------+
Mini summary: Coding is writing instructions. Programming is the whole process that includes coding, planning, and testing.
Definition: A programming language is a special language that humans use to give instructions to a computer. It has its own rules and words.
Why it's important: Without a programming language, we couldn't tell computers what to do. It is like the "dialect" that computers understand.
Simple explanation: Just like you speak English or Yoruba to talk to people, programmers speak "Python" or "Scratch" to talk to computers.
Realâlife example: Python, JavaScript, and Scratch are all programming languages.
School example: If your school teaches coding, you might learn Scratch or Python.
Home example: Your smart speaker understands a programming language.
Nigerian example: Nigerian developers use languages like Python, Java, and C++ to build software.
+------------------------------------------+ | Programming Languages | |------------------------------------------+ | +---------+ +---------+ +-------+ | | | Scratch | | Python | | C++ | | | | Visual | | Text | | Text | | | | (blocks)| | (words) | | (words)| | | +---------+ +---------+ +-------+ | | | | Different languages for different | | tasks. | +------------------------------------------+
Mini summary: A programming language is how we talk to computers. There are many languages, each with its own rules.
Definition: Scratch is a visual programming language where you drag and snap blocks together to create programs. It is perfect for beginners.
Why it's important: Scratch is fun and easy. It teaches you the basics of coding without the need to type anything.
Simple explanation: Scratch is like digital LEGO. You snap blocks together to build a program.
Realâlife example: Many schools use Scratch to teach coding to kids.
School example: In class, you might use Scratch to make a cat dance.
Home example: You can use Scratch at home to make your own games.
Nigerian example: Some Nigerian coding clubs use Scratch to introduce children to programming.
+------------------------------------------+ | Scratch Example | |------------------------------------------+ | [when green flag clicked] | | â | | [move 10 steps] | | â | | [turn right 15 degrees] | | â | | [if touching edge? then] | | â | | [bounce] | | | | Blocks snap together like puzzle pieces!| +------------------------------------------+
Mini summary: Scratch is a visual language that uses blocks. It is a great way to start coding.
Definition: "Hello, World!" is the traditional first program that everyone writes when learning a new language. It simply prints "Hello, World!" on the screen.
Why it's important: It is a simple way to make sure everything is set up correctly. It also gives you the joy of seeing your first program run.
Simple explanation: You tell the computer to say "Hello, World!" and it does! It's like magic.
Realâlife example: Every programmer remembers their first "Hello, World!".
School example: You might write "Hello, World!" in your first coding class.
Home example: You can ask a smart speaker to say "Hello" â it's a similar idea.
Nigerian example: In Nigerian coding camps, students start with "Hello, World!" in Python.
+------------------------------------------+
| Hello, World! in Python |
|------------------------------------------+
| print("Hello, World!") |
| |
| Output: |
| Hello, World! |
| |
| That's it! You've written your first |
| program! |
+------------------------------------------+
Mini summary: "Hello, World!" is the classic first program. It prints that message on the screen.
Definition: Computers don't understand code directly. They understand only machine language (binary â 0s and 1s). Code is translated into machine language by a special program called an interpreter or compiler.
Why it's important: Understanding this helps you know why code needs to be written in a specific way.
Simple explanation: It's like having a translator. You speak English, the translator converts it to Yoruba so the listener can understand.
Realâlife example: When you use Google Translate, it translates English to French. A compiler translates code to machine language.
School example: In class, you write code, and the computer translates it to run.
Home example: A smart speaker translates your voice command into actions.
Nigerian example: Nigerian programmers write code in Python, and the computer translates it to machine language.
+------------------------------------------+ | How Code is Translated | |------------------------------------------+ | Code (English) | | | | | v | | Interpreter/Compiler (Translator) | | | | | v | | Machine Language (0s and 1s) | | | | | v | | Computer executes instructions | +------------------------------------------+
Mini summary: Computers only understand 0s and 1s. Compilers and interpreters translate code into machine language so the computer can run it.
Definition: A coding environment is where you write and run your code. It includes a text editor (where you type code) and a way to run the code.
Why it's important: You need a place to write and test your code. A good environment makes coding easier.
Simple explanation: It's like having a desk with a notebook and pen. You need a place to work.
Realâlife example: For Python, you can use IDLE (included with Python) or an online editor like Replit.
School example: Schools often use online editors like Trinket or Code.org.
Home example: You can install Python on your home computer and use a text editor like VS Code.
Nigerian example: Nigerian students often use online platforms like Replit or Glitch to code.
+------------------------------------------+ | Setting Up Your Environment | |------------------------------------------+ | 1. Choose a language (like Python). | | 2. Install it on your computer. | | 3. Use a text editor (like VS Code). | | 4. Or use an online editor (like Replit).| | 5. Write your code and run it! | +------------------------------------------+
Mini summary: A coding environment is where you write and run your code. You can use an online editor or install software on your computer.
Definition: Comments are notes in the code that the computer ignores. They are for humans to read and understand what the code does.
Why it's important: Comments make your code easier to understand for you and others. They are like sticky notes.
Simple explanation: A comment is like writing a note to remind yourself why you wrote something.
Realâlife example: A programmer writes comments to remember what a piece of code does.
School example: Teachers encourage students to add comments to their code.
Home example: You add comments to a recipe to remember where you left off.
Nigerian example: Nigerian developers use comments to explain their code to team members.
+------------------------------------------+
| Comments in Python |
|------------------------------------------+
| # This is a singleâline comment |
| print("Hello") # This is an inline comment|
| |
| """ |
| This is a multiâline comment. |
| It can span several lines. |
| """ |
| |
| Comments are ignored by the computer! |
+------------------------------------------+
Mini summary: Comments are notes in the code that help humans understand it. The computer ignores them.
Definition: Debugging is the process of finding and fixing errors (called "bugs") in your code. It is a normal and important part of coding.
Why it's important: All programmers make mistakes. Debugging is how you learn and improve.
Simple explanation: Debugging is like being a detective. You look for clues to find what's wrong.
Realâlife example: A programmer runs their code, sees an error, and fixes it.
School example: A student's code doesn't work, and they look for the mistake.
Home example: When a recipe doesn't work, you check what you did wrong and fix it.
Nigerian example: Nigerian developers spend time debugging their applications.
+------------------------------------------+ | Debugging Steps | |------------------------------------------| | 1. Read the error message. | | 2. Look at the line where the error is. | | 3. Think about what might be wrong. | | 4. Make a change. | | 5. Run the code again. | | 6. Repeat until it works! | +------------------------------------------+
Mini summary: Debugging is finding and fixing errors in your code. It is a normal part of coding.
Definition: Coding is used to create almost everything digital â websites, apps, games, robots, and more.
Why it's important: Knowing how coding is used helps you see the impact of what you are learning.
Simple explanation: Coding is behind every app on your phone, every website you visit, and every game you play.
Realâlife example: WhatsApp is a messaging app built with code.
School example: Your school's website is built with code.
Home example: A smart TV uses code to stream shows.
Nigerian example: Nigerian businesses use code to build websites and apps to serve customers.
+------------------------------------------+ | RealâWorld Applications | |------------------------------------------+ | - Websites (Google, YouTube) | | - Apps (WhatsApp, Instagram) | | - Games (Minecraft, Fortnite) | | - Robots (industrial, personal) | | - Cars (autonomous driving) | | - Hospitals (medical systems) | | - Schools (learning platforms) | +------------------------------------------+
Mini summary: Coding is used to build websites, apps, games, robots, and many other things we use every day.
Definition: Coding gives you the power to create things with technology. It is like having a superpower!
Why it's important: When you code, you are not just using technology â you are creating it.
Simple explanation: Coding lets you turn your ideas into reality. If you can imagine it, you can code it.
Realâlife example: A girl created an app to help kids learn. She used code to bring her idea to life.
School example: Students create games to share with their classmates.
Home example: You can code a simple game for your family to play.
Nigerian example: A Nigerian teenager built a website to share information about science.
+------------------------------------------+ | Coding is a Superpower! | |------------------------------------------+ | +-------+ | | | Idea | â Code it! | | +-------+ | | | | | v | | +-------+ | | | Build | â Create something new! | | +-------+ | | | | | v | | +-------+ | | | Share | â Help others with your | | +-------+ creation! | | | | You have the power to create! | +------------------------------------------+
Mini summary: Coding is a superpower that lets you create and share amazing things with technology.
In this module, we explored what coding is and why it is important. We learned that coding is giving instructions to a computer. We discovered the difference between coding and programming. We explored programming languages, especially Scratch, and wrote our first "Hello, World!" program. We learned how computers understand code, how to set up a coding environment, and the importance of comments and debugging. We also saw realâworld examples of coding and learned that coding is a superpower. You are now ready to continue your coding adventure!
Concept 1: Coding is giving instructions. It is like writing a recipe for a computer.
Concept 2: Computers need translation. Code is translated into machine language.
Concept 3: There are many languages. Different languages are suited for different tasks.
Concept 4: Mistakes are normal. Debugging is a key part of coding.
How to write your first "Hello, World!" program in Python:
We've seen many realâlife examples in the lessons, such as traffic lights, ATMs, WhatsApp, and smart TVs. These show how coding powers everyday technology.
In Nigeria, coding is used in many ways. ATMs use code to dispense cash. Traffic management systems in Lagos are powered by code. Nigerian developers build websites, apps, and software for businesses and government. Coding camps are growing across the country.
Imagine you are making a sandwich. The instructions for making a sandwich are like code. You say: "Take two slices of bread, put butter on one side, put cheese on top, close the sandwich." That's an algorithm! Coding is the same â giving stepâbyâstep instructions.
Another fun example: A robot chef follows your code to make a sandwich. If you forget a step, the robot might make a mess â that's a bug!
Key points: Emphasize that coding is about giving clear, stepâbyâstep instructions. Use analogies like recipes and directions. Make it fun with Scratch. Encourage students to experiment and make mistakes â that's how they learn.
Activity idea: Have students write a "recipe" for making a peanut butter sandwich â use it to demonstrate the importance of clear instructions!
Parents can help children learn coding by exploring Scratch together. Ask questions like "What do you think this block does?" Encourage them to try new things. Celebrate their successes and help them debug errors. Show them how coding is used in your daily life.
Did you know that coding is used in fashion design, movie animation, and even farming?
Did you know that Nigeria has a growing community of young coders and many coding competitions?
+------------------------------------------+ | Coding Journey | |------------------------------------------+ | Start | | | | | v | | Learn Basics | | | | | v | | Write First Program | | | | | v | | Make Mistakes (Debug) | | | | | v | | Build Projects | | | | | v | | Keep Learning | | | | | v | | Become a Coder! đ | +------------------------------------------+ +------------------------------------------+ | Scratch Blocks Example | |------------------------------------------+ | [when green flag clicked] | | â | | [move 10 steps] | | â | | [turn right 15 degrees] | | â | | [if touching edge? then] | | â | | [bounce] | +------------------------------------------+
| Coding | Programming |
|---|---|
| Writing instructions | Whole process: planning, coding, testing |
| Part of programming | Includes coding and more |
| Like writing a sentence | Like writing a whole book |
| Language | Type | Best For |
|---|---|---|
| Scratch | Visual (blocks) | Beginners |
| Python | Text (words) | General coding, data, AI |
| JavaScript | Text (words) | Websites |
In this module, we explored the exciting world of coding. We learned that coding is giving instructions to a computer. We saw why coding is important and how it powers our modern world. We discovered the difference between coding and programming. We met Scratch and wrote our first "Hello, World!" program. We learned how computers understand code through translation, how to set up a coding environment, and how comments help us. We explored debugging and realâworld applications. Finally, we learned that coding is a superpower that lets us create and share amazing things. You have taken your first step into the world of coding. Keep going â the next module will be even more exciting!
Match the term with its definition.
| Term | Definition |
|---|---|
| Coding | a) A visual programming language |
| Programming | b) Notes that the computer ignores |
| Scratch | c) Giving instructions to a computer |
| Comments | d) Finding and fixing errors |
| Debugging | e) The whole process of creating software |
Answers: Coding â c, Programming â e, Scratch â a, Comments â b, Debugging â d
Scenario 1: You want to make a sandwich. Write a stepâbyâstep algorithm (like a recipe) for making a peanut butter and jelly sandwich. Then imagine you are a robot â what if you forgot a step?
Scenario 2: You are trying to run your first program and you see an error message. What steps would you take to fix it?
"Design a Superhero Code" â In groups of 4, invent a superhero whose superpower is coding. What can they do? How do they use coding to help people? Create a poster and present it to the class.
Write a simple "Hello, World!" program in a language of your choice (Scratch or Python). Add a comment explaining what the code does. Take a screenshot and share it with the class.
"Coding in My World" â Create a poster or a short presentation showing all the places coding is used in your daily life. Include at least 5 examples (e.g., phone, games, traffic lights). Present it to the class.
Install or set up a coding environment (like Replit or Scratch) on your computer or use an online editor. Write and run the "Hello, World!" program. Take a screenshot and submit it.
"Code Detective" â Write a simple program that says "Hello" to three different people by name. For example, if the user types "Chidi", it says "Hello, Chidi!". (Hint: use input if you know it â otherwise, just write three separate print statements).
In Module 2, we will dive into Thinking Like a Programmer. You will learn how to break down big problems into small, manageable steps. We'll explore algorithms, flowcharts, and how to design solutions before writing code. Get ready to think like a coding master!
Module Introduction
Welcome back, coders! In Module 1, we learned what coding is and why it is important. Now we are going to learn how to think like a programmer. Programming is not just about typing code â it is about solving problems. Programmers break big problems into small pieces, look for patterns, and create stepâbyâstep plans. In this module, we will learn the special way of thinking that programmers use every day. We will explore algorithms, flowcharts, and how to plan before you code. By the end, you will be able to look at any problem and know how to start building a solution. Let's train our brains to think like programmers!
Tunde is 11 years old. He wants to build a robot that can clean his room. But where does he start? The room is messy, and it feels like a huge problem. Tunde remembers what his coding teacher said: "Break it down!" He thinks: "Cleaning the room is one big task. But I can break it into small parts: pick up toys, put books on the shelf, sweep the floor." He also notices a pattern â every time he cleans, he goes from top to bottom. He ignores details like the colour of the toys â that's not important. He creates a stepâbyâstep plan: Step 1, Step 2, Step 3. Tunde realises that the same way of thinking can be used for coding problems. He becomes a problemâsolving master! Now, you can learn Tunde's secret â thinking like a programmer.
Definition: Computational thinking is the way that programmers solve problems. It is a way of breaking down big problems into small pieces and solving them step by step.
Why it's important: It helps you solve problems not just in coding, but in everyday life too!
Simple explanation: Computational thinking is like using your brain like a computer. You break things down, look for patterns, and make plans.
Realâlife example: Planning a birthday party â you break it into invitations, food, games, and cake.
School example: Writing an essay â you plan the introduction, body, and conclusion.
Home example: Organising your room â sorting toys, clothes, and books.
Nigerian example: Planning a market trip â you decide what to buy, in what order, and how much money to take.
+------------------------------------------+ | What is Computational Thinking? | |------------------------------------------+ | It is a way to solve problems like | | a computer does. | | | | 1. Break it down (Decomposition) | | 2. Find patterns (Pattern Recognition) | | 3. Focus on what matters (Abstraction) | | 4. Make a plan (Algorithm) | +------------------------------------------+
Mini summary: Computational thinking is how programmers solve problems â by breaking them down, finding patterns, simplifying, and planning.
Definition: Decomposition is the process of breaking a big problem into smaller, more manageable parts.
Why it's important: A big problem can feel overwhelming. When you break it down, it becomes easy to solve.
Simple explanation: If you have to eat a whole pizza, you don't eat it all at once â you cut it into slices and eat one piece at a time.
Realâlife example: Building a house â you don't build it all at once. You lay the foundation, then walls, then roof.
School example: A science project â you break it into research, experiment, writing, and presentation.
Home example: Cleaning your room â you pick up toys, then clothes, then books.
Nigerian example: Preparing a meal â you chop vegetables, cook the stew, boil rice.
+------------------------------------------+ | Decomposition Example | |------------------------------------------+ | Big Problem: Build a Robot | | | | | v | | +-------+ | | | Design| | | +-------+ | | | | | v | | +-------+ | | | Gather| | | | Parts | | | +-------+ | | | | | v | | +-------+ | | | Assem-| | | | ble | | | +-------+ | | | | | v | | +-------+ | | | Program| | | +-------+ | | | | | v | | +-------+ | | | Test | | | +-------+ | | | | Big problem â small pieces! | +------------------------------------------+
Mini summary: Decomposition is breaking a big problem into small, manageable steps.
Definition: Pattern recognition is finding similarities or common elements in different problems.
Why it's important: When you see a pattern, you can use the same solution in different situations.
Simple explanation: If you know how to tie your shoe laces once, you can tie them every time â it's the same pattern.
Realâlife example: In a recipe, you add salt to many dishes â that's a pattern.
School example: Solving maths problems â the same formula can be used for similar problems.
Home example: Cleaning â you always sweep before mopping.
Nigerian example: Greeting elders â the pattern is the same across many communities.
+------------------------------------------+ | Pattern Recognition Example | |------------------------------------------+ | Problem 1: Brush teeth | | Problem 2: Wash hands | | Problem 3: Clean dishes | | | | Pattern: All involve cleaning with | | water and soap. | | | | When you know one, you can guess | | how to do the others! | +------------------------------------------+
Mini summary: Pattern recognition is noticing similarities between problems. It helps you reuse solutions.
Definition: Abstraction is ignoring unnecessary details and focusing only on the important parts.
Why it's important: It makes problems simpler and easier to solve.
Simple explanation: When you look at a map, you see roads and cities â not every single tree. That's abstraction.
Realâlife example: When you buy a phone, you focus on its features, not on how every single transistor works.
School example: In a story, you focus on the main character, not every background detail.
Home example: When planning a trip, you focus on the destination and route, not on every small detail along the way.
Nigerian example: When making jollof rice, you focus on the main ingredients, not every single spice detail.
+------------------------------------------+ | Abstraction Example | |------------------------------------------+ | Building a car: | | Important: wheels, engine, steering | | Not important: colour of the seats, | | the brand of the radio | | | | Focus on what matters most! | +------------------------------------------+
Mini summary: Abstraction is ignoring unnecessary details and focusing on the essential parts.
Definition: An algorithm is a stepâbyâstep set of instructions to solve a problem or complete a task.
Why it's important: Algorithms are the foundation of coding. Every program is an algorithm.
Simple explanation: An algorithm is like a recipe. It tells you what to do first, second, and third.
Realâlife example: A recipe for making pancakes is an algorithm.
School example: The instructions for a science experiment are an algorithm.
Home example: The steps to get ready for school â wake up, brush teeth, eat breakfast, etc.
Nigerian example: The steps to make a Nigerian dish are an algorithm.
+------------------------------------------+ | Algorithm Example | |------------------------------------------| | How to make a cup of tea: | | 1. Boil water. | | 2. Put tea bag in a cup. | | 3. Pour water into the cup. | | 4. Add sugar and stir. | | 5. Add milk and stir. | | 6. Enjoy! | | | | Each step is clear and in order. | +------------------------------------------+
Mini summary: An algorithm is a clear, stepâbyâstep set of instructions to solve a problem.
Definition: Pseudocode is a way to write algorithms using everyday language, not a programming language. It looks like code but is easy to read.
Why it's important: Pseudocode helps you plan your program before you write actual code. It is a bridge between your idea and the real code.
Simple explanation: Pseudocode is like writing a draft of your code in simple English. It helps you think clearly.
Realâlife example: Before a chef cooks, they plan the recipe in their mind â that's like pseudocode.
School example: Before writing an essay, you write an outline â that's like pseudocode.
Home example: Before fixing a bike, you plan the steps â that's like pseudocode.
Nigerian example: Before a tailor sews a dress, they plan the measurements and cuts â that's like pseudocode.
+------------------------------------------+ | Pseudocode Example | |------------------------------------------+ | START | | Ask the user for their name | | Store the name in a variable | | Say "Hello, " + name | | END | | | | This is not real code â it's a plan! | +------------------------------------------+
Mini summary: Pseudocode is a plainâEnglish plan for your program. It helps you organise your ideas before coding.
Definition: A flowchart is a diagram that shows the steps of an algorithm using different shapes and arrows.
Why it's important: Flowcharts help you see the flow of your program visually. They make it easy to spot errors.
Simple explanation: A flowchart is like a map for your algorithm. It shows where you start, where you go next, and where you end.
Realâlife example: The instructions for assembling furniture often include a flowchart.
School example: Teachers use flowcharts to explain how to solve maths problems.
Home example: You can draw a flowchart for your morning routine.
Nigerian example: A flowchart can show the steps to register for a national ID.
+------------------------------------------+ | Flowchart Shapes | |------------------------------------------+ | +----------+ | | | Start/End| â Oval | | +----------+ | | +----------+ | | | Process | â Rectangle (action) | | +----------+ | | +----------+ | | | Decision | â Diamond (yes/no) | | +----------+ | | +----------+ | | | Input/ | â Parallelogram | | | Output | | | +----------+ | +------------------------------------------+
Mini summary: A flowchart is a visual diagram of your algorithm. It uses shapes and arrows to show the sequence.
Definition: Let's create a simple algorithm for making a sandwich. This will help us practice computational thinking.
Why it's important: Practicing with everyday tasks helps you understand how to build algorithms for code.
Simple explanation: We will write stepâbyâstep instructions for making a sandwich, just like we would write a program.
Realâlife example: Making a sandwich for lunch.
School example: Following a recipe in a home economics class.
Home example: Making a snack for yourself.
Nigerian example: Making a Nigerian snack â like puff puff.
+------------------------------------------+ | Sandwich Algorithm | |------------------------------------------+ | 1. Get two slices of bread. | | 2. Open the jar of butter. | | 3. Take a knife. | | 4. Spread butter on one side of each | | bread slice. | | 5. Put a slice of cheese on one bread. | | 6. Put another slice of cheese on top. | | 7. Place the other bread on top, butter | | side down. | | 8. Cut the sandwich in half. | | 9. Eat and enjoy! | +------------------------------------------+
Mini summary: Algorithms are used in everyday tasks. Making a sandwich is a great example of an algorithm.
Definition: We will write pseudocode for a program that asks for your name and greets you.
Why it's important: This shows how you can take an idea and turn it into a plan before coding.
Simple explanation: We write the steps in plain English so we know exactly what the program will do.
Realâlife example: A website that says "Welcome, [name]" uses a similar idea.
School example: A program that asks a user's name and greets them.
Home example: A voice assistant that says "Hello" when you call its name.
Nigerian example: A banking app that greets you by name when you log in.
+------------------------------------------+ | Pseudocode for Greeting Program | |------------------------------------------+ | START | | ASK "What is your name?" | | STORE answer in variable called name | | PRINT "Hello, " + name + "!" | | END | | | | This is the plan for a real program! | +------------------------------------------+
Mini summary: Pseudocode is a great way to plan out what your program will do before writing actual code.
Definition: Let's draw a flowchart for the greeting program we planned in pseudocode.
Why it's important: Visualising the plan helps you understand the flow of the program.
Simple explanation: We use shapes and arrows to show what happens first, next, and last.
Realâlife example: A user registration form follows a similar flow.
School example: A program that collects student information follows this flow.
Home example: A form that asks for your name and email.
Nigerian example: A government portal that asks for your details.
+------------------------------------------+ | Greeting Program Flowchart | |------------------------------------------+ | +----------+ | | | START | | | +----+-----+ | | | | | v | | +----+-----+ | | | Ask for | | | | name | | | +----+-----+ | | | | | v | | +----+-----+ | | | Store | | | | name | | | +----+-----+ | | | | | v | | +----+-----+ | | | Print | | | | "Hello" | | | | + name | | | +----+-----+ | | | | | v | | +----------+ | | | END | | | +----------+ | +------------------------------------------+
Mini summary: A flowchart is a visual representation of your algorithm. It makes the plan easy to see and follow.
Definition: We can use computational thinking for any problem â not just coding. It helps us be better problemâsolvers.
Why it's important: It trains your brain to be logical and clear.
Simple explanation: Whether you are planning a party or building a robot, you can use decomposition, pattern recognition, abstraction, and algorithms.
Realâlife example: Planning a road trip â break it into steps (decomposition), find the best route (pattern), focus on the destination (abstraction), and make a plan (algorithm).
School example: Doing a group project â divide tasks (decomposition), use similar approaches (pattern), focus on the goal (abstraction), and make a timeline (algorithm).
Home example: Organising a birthday party â plan games, food, and decorations (decomposition), reuse ideas from previous parties (pattern), focus on the theme (abstraction), and make a schedule (algorithm).
Nigerian example: Planning a wedding â many tasks (decomposition), similar to other weddings (pattern), focus on the budget (abstraction), and make a list (algorithm).
+------------------------------------------+ | Computational Thinking in Life | |------------------------------------------+ | Problem: Plan a birthday party | | | | 1. Decomposition: guests, food, games, | | cake, invitations | | 2. Pattern Recognition: use ideas from | | other parties | | 3. Abstraction: focus on the theme | | (e.g., superhero) | | 4. Algorithm: Step 1, Step 2, Step 3 | +------------------------------------------+
Mini summary: Computational thinking is not just for coding â it is a life skill for solving all kinds of problems.
Definition: Even programmers can make mistakes in how they think about problems. Let's learn common mistakes and how to avoid them.
Why it's important: Knowing mistakes helps you become a better problemâsolver.
Simple explanation: Sometimes we try to solve everything at once (forgetting decomposition), or we focus on the wrong details (forgetting abstraction).
Realâlife example: Trying to clean a whole house at once â you get overwhelmed. Better to do one room at a time.
School example: Trying to write an essay without an outline â you may get lost. Better to plan first.
Home example: Trying to cook without a recipe â you may forget an ingredient. Better to make a plan.
Nigerian example: Trying to organise a large event without a checklist â things get missed. Better to break it down.
+------------------------------------------+ | Common Mistakes | |------------------------------------------+ | - Solving everything at once | | (forget decomposition) | | - Focusing on tiny details | | (forget abstraction) | | - Not looking for patterns | | - Trying to code before planning | | | | Always plan first! | +------------------------------------------+
Mini summary: Common mistakes include trying to do everything at once, not focusing on what matters, and coding without a plan.
In this module, we learned about computational thinking â the way programmers solve problems. We explored the four pillars: decomposition (breaking problems down), pattern recognition (finding similarities), abstraction (focusing on what matters), and algorithms (stepâbyâstep plans). We learned to write pseudocode and draw flowcharts. We practiced by planning a greeting program and a sandwich algorithm. We also saw how computational thinking applies to everyday life. You are now ready to think like a programmer!
Concept 1: Computational thinking has four parts. Decomposition, pattern recognition, abstraction, and algorithms.
Concept 2: Always plan before you code. Use pseudocode and flowcharts to plan.
Concept 3: Algorithms are everywhere. They are not just in computers â they are in daily tasks.
Concept 4: Computational thinking is a life skill. It helps you solve all kinds of problems.
How to solve a problem using computational thinking:
We've seen many realâlife examples in the lessons, such as planning a birthday party, making a sandwich, and writing an essay. These show how computational thinking is used every day.
In Nigeria, computational thinking is used in many areas â from planning weddings and events to organising markets and businesses. Nigerian developers use it to build websites, apps, and software. Understanding this way of thinking helps solve local challenges.
Imagine you are building a LEGO castle. You don't build it all at once â you break it down into sections (decomposition), use similar techniques for the towers (pattern recognition), focus on the main structure (abstraction), and follow the instructions (algorithm).
Another fun example: You are planning a scavenger hunt. You break it into clues, find patterns in the hiding spots, focus on the main route, and create a stepâbyâstep list of clues.
Key points: Emphasize that computational thinking is not just for coding â it is a way of life. Use engaging examples that kids can relate to. Encourage them to break down problems from their daily lives. Make the learning interactive with group activities.
Activity idea: Have students write an algorithm for something they do every day (like brushing teeth) and draw a flowchart for it.
Parents can help children practice computational thinking by asking them to plan activities (like a party or a trip). Encourage them to break down problems and look for patterns. Ask questions like "How would you break this down?" and "What's your first step?" Help them see the logic in everyday tasks.
Did you know that ancient Egyptians used algorithms to build the pyramids? They followed stepâbyâstep plans!
Did you know that NASA uses computational thinking to plan space missions?
+------------------------------------------+ | Computational Thinking Cycle | |------------------------------------------+ | +-------+ | | |Problem| | | +---+---+ | | | | | v | | +-------+ | | |Decom- | â Break it down | | |posit- | | | |ion | | | +---+---+ | | | | | v | | +-------+ | | |Pattern| â Find similarities | | |Recog- | | | |nition | | | +---+---+ | | | | | v | | +-------+ | | |Abstrac| â Focus on important parts | | |tion | | | +---+---+ | | | | | v | | +-------+ | | |Algo- | â Stepâbyâstep plan | | |rithm | | | +---+---+ | | | | | v | | +-------+ | | |Solution| | | +-------+ | +------------------------------------------+ +------------------------------------------+ | Flowchart Symbols | |------------------------------------------+ | +----------+ +----------+ +---------+ | | | START | | PROCESS | | DECISION| | | | /END | | (Box) | | (Diamond)| | | | (Oval) | +----------+ +----+----+ | | +----------+ | | | | | | +----------+ +----------+ +---------+| | | INPUT | | OUTPUT | | ARROW || | | /OUTPUT | | (Box) | | (â) || | | (Paralle-| +----------+ +---------+| | | logram) | | | +----------+ | +------------------------------------------+
| Concept | Definition | Example |
|---|---|---|
| Decomposition | Breaking down a big problem | Cleaning a room â toys, books, clothes |
| Pattern recognition | Finding similarities | Same cleaning steps for different rooms |
| Abstraction | Focusing on important details | Ignoring toy colours, focusing on picking them up |
| Algorithm | Stepâbyâstep plan | 1. Pick up toys, 2. Put books on shelf, 3. Sweep |
| Tool | What it is | Purpose |
|---|---|---|
| Pseudocode | PlainâEnglish plan | Plan before coding |
| Flowchart | Visual diagram | See the flow of the algorithm |
In this module, we learned how to think like a programmer. We explored computational thinking â a powerful way to solve problems by breaking them down, finding patterns, focusing on what matters, and creating stepâbyâstep plans. We learned to use pseudocode and flowcharts to plan our programs before writing any code. We practiced with everyday tasks and saw how computational thinking applies to life. Now you have the mindset of a programmer â you can solve any problem by thinking clearly and logically. You are ready to move on to the next module and start writing real code!
Match the term with its definition.
| Term | Definition |
|---|---|
| Decomposition | a) A visual diagram |
| Pattern recognition | b) A stepâbyâstep plan |
| Abstraction | c) Breaking a problem down |
| Algorithm | d) Finding similarities |
| Flowchart | e) Focusing on important details |
Answers: Decomposition â c, Pattern recognition â d, Abstraction â e, Algorithm â b, Flowchart â a
Scenario 1: You need to pack your school bag for the week. Use decomposition to break this task into smaller parts. What are the steps?
Scenario 2: You are planning a surprise birthday party for your friend. Use the four parts of computational thinking to plan it. Write out your plan using pseudocode (plain English).
"Algorithm Challenge" â In groups of 4, choose an everyday task (e.g., making a sandwich, brushing teeth, getting ready for school). Write an algorithm for it (stepâbyâstep). Then draw a flowchart for the same task. Present to the class.
Write pseudocode for a simple program that asks the user for their favourite colour and prints "I like [colour] too!" Then draw a flowchart for the same program.
"My Morning Routine Flowchart" â Create a flowchart that shows your morning routine (waking up, brushing teeth, eating breakfast, etc.). Use the correct flowchart shapes and arrows. Present it to the class.
Choose a simple problem (like making a sandwich or planning a trip). Write pseudocode for the solution. Then create a flowchart for the same solution. Submit both.
"CrossâRoads Algorithm" â Design an algorithm that helps a pedestrian cross a busy road safely. Include decision points (e.g., look left, look right, is it clear?). Write pseudocode and draw a flowchart.
In Module 3, we will dive into Variables and Data Types. You will learn how to store and manage information in your programs â like numbers, text, and true/false values. You will write your first real programs that use variables. Get ready to store data and make your programs come alive!
Module Introduction
Welcome back, coders! In Module 2, we learned how to think like a programmer â we broke down problems, found patterns, and made plans. Now it's time to start writing real code! In this module, we will learn about variables and data types. Variables are like boxes where we store information. Data types tell us what kind of information is in the box â numbers, words, or true/false values. Think of variables like a school locker. You can put a book, a lunchbox, or a jacket in it â but you need to know what you put there so you can use it later. By the end of this module, you will be able to store and use information in your programs. Let's start storing data!
Ngozi is 11 years old. She goes to school and has a locker. In her locker, she keeps her books, lunch, and art supplies. She labels the shelf: "books", "lunch", "art". Every day, she puts things in and takes things out. One day, she decided to put a new notebook in the "books" shelf. She opened it, placed the notebook, and closed it. Later, she opened it again and took out the notebook to use. Ngozi's locker is like a variable â it stores things and she can change what's inside. In coding, variables are just like lockers â they store information that we can use and change. Ngozi learns that variables make coding easy because she can keep track of information.
Definition: A variable is a named box that stores information in a computer's memory. You can put data in it, change it, and use it later.
Why it's important: Variables let programs remember things. Without variables, every program would be a oneâtime thing with no memory.
Simple explanation: A variable is like a labelled box. You put something in it, and you can take it out whenever you need it.
Realâlife example: A shopping list â you write "bread" on it, and later you remember to buy bread.
School example: Your name tag â it stores your name so people know who you are.
Home example: A jar for saving money â you put money in and take it out.
Nigerian example: A "thrift" savings box â you put money in it and it remembers how much you have saved.
+------------------------------------------+ | What is a Variable? | |------------------------------------------+ | +-------------------+ | | | Variable Box | | | | Name: age | | | | Value: 10 | | | +-------------------+ | | | | A variable stores a value. | | You can change the value anytime. | +------------------------------------------+
Mini summary: A variable is a named box that stores information. It helps programs remember things.
Definition: Variables are used to store data that our program needs to remember â like a score in a game, a user's name, or the result of a calculation.
Why it's important: Without variables, programs couldn't keep track of anything. They would be like a person with no memory.
Simple explanation: Variables help us write flexible programs. Instead of writing "Hello, Chidi!" we can use a variable name and say "Hello, [name]" â it works for anyone!
Realâlife example: A bank account â it stores how much money you have. You can deposit and withdraw.
School example: A grade book â it stores each student's grades.
Home example: A calendar â it stores your appointments.
Nigerian example: A phone contact list â it stores names and phone numbers.
+------------------------------------------+
| Why Use Variables? |
|------------------------------------------+
| Without variables: |
| print("Hello, Chidi!") |
| Only works for Chidi. |
| |
| With variables: |
| name = "Chidi" |
| print("Hello, " + name) |
| Works for ANY name! |
| |
| Variables make programs flexible! |
+------------------------------------------+
Mini summary: Variables make programs flexible and able to remember information.
Definition: A variable name is how we refer to the variable in our code. It must follow certain rules and it's good to use meaningful names.
Why it's important: Good names make your code easy to read and understand. Bad names make it confusing.
Simple explanation: Imagine naming your locker "box1" vs "books". Which one is easier to remember?
Realâlife example: In school, you label your folders "Math", "Science", "English" â not "Folder 1".
School example: Naming variables like "score" or "player_name" is clear.
Home example: Labelling your food containers "rice" and "beans" instead of "container1".
Nigerian example: Naming variables like "customer_name" and "balance" in a banking app.
+------------------------------------------+ | Naming Rules and Practices | |------------------------------------------+ | Rules: | | - Must start with a letter or _ | | - Can contain letters, numbers, and _ | | - No spaces or special characters | | - Caseâsensitive (age and AGE are diff) | | | | Good names: age, student_name, score | | Bad names: a, x, myvar123 | | | | Use names that make sense! | +------------------------------------------+
Mini summary: Use clear, meaningful names for your variables. Follow the rules of naming.
Definition: A data type tells us what kind of value a variable can hold â like numbers, text, or true/false.
Why it's important: Different types of data are used differently. You can do maths with numbers, but not with text.
Simple explanation: Data types are like different containers. You put liquids in a bottle, solids in a box. You wouldn't put water in a cardboard box!
Realâlife example: A phone number is text, a price is a number.
School example: Your age is a number, your name is text.
Home example: The number of eggs in the fridge is an integer, the brand is a string.
Nigerian example: In a market, the price is a number, the item name is a string, and "in stock" is a boolean.
+------------------------------------------+ | Data Types Overview | |------------------------------------------+ | +--------------+------------------------+ | | | Integer | Whole numbers (e.g., 5) | | | +--------------+------------------------+ | | | Float | Decimal numbers (3.14) | | | +--------------+------------------------+ | | | String | Text (e.g., "Hello") | | | +--------------+------------------------+ | | | Boolean | True or False | | | +--------------+------------------------+ | | | | Each type is used for different things. | +------------------------------------------+
Mini summary: Data types tell us what kind of value a variable holds â numbers, text, or true/false.
Definition: An integer is a whole number â it has no decimal point. Examples: 5, 10, -3, 0.
Why it's important: Integers are used for counting, scores, ages, and anything that needs a whole number.
Simple explanation: Integers are numbers like 1, 2, 3 â without any "point something".
Realâlife example: The number of students in a class is an integer.
School example: Your score on a test is an integer.
Home example: The number of eggs in the carton is an integer.
Nigerian example: The number of people in a queue at the bank is an integer.
+------------------------------------------+ | Integer Examples | |------------------------------------------+ | age = 10 | | score = 85 | | number_of_students = 30 | | temperature = -5 | | | | Integers are whole numbers. | | They can be positive or negative. | +------------------------------------------+
Mini summary: Integers are whole numbers like 10, 85, or -5. They are used for counting.
Definition: A float (floating point number) is a number with a decimal point. Examples: 3.14, 2.5, 0.99, -1.5.
Why it's important: Floats are used for measurements, prices, and anything that needs more precision.
Simple explanation: Floats are numbers like 2.5 â they have a point and digits after.
Realâlife example: The price of an item â 5.99 Naira.
School example: Your average grade â 86.5.
Home example: The temperature â 28.5 degrees.
Nigerian example: The exchange rate â 1500.50 Naira to a dollar.
+------------------------------------------+ | Float Examples | |------------------------------------------+ | price = 5.99 | | temperature = 28.5 | | pi = 3.14159 | | height = 1.75 | | | | Floats are numbers with decimals. | +------------------------------------------+
Mini summary: Floats are numbers with a decimal point, like 3.14 or 5.99.
Definition: A string is a sequence of characters â words, letters, numbers, or symbols â enclosed in quotes. Examples: "Hello", "Chidi", "123".
Why it's important: Strings are used for all text data â names, messages, addresses, and more.
Simple explanation: A string is any text that you put inside quotation marks. It can be letters, numbers, or symbols.
Realâlife example: Your name â "Chidi".
School example: The title of a book â "The Cat in the Hat".
Home example: Your address â "12, Unity Street".
Nigerian example: The name of a bank â "Access Bank".
+------------------------------------------+ | String Examples | |------------------------------------------+ | name = "Chidi" | | greeting = "Hello, World!" | | school = "God's Grace Academy" | | phone = "08012345678" | | | | Strings are text. They must be inside | | quotes. | +------------------------------------------+
Mini summary: Strings are text data â like names, messages, and addresses â written inside quotes.
Definition: A boolean is a data type that can only be True or False. It is used for conditions and decisions.
Why it's important: Booleans are used to check conditions â like "Is the user logged in?" or "Is the score greater than 10?"
Simple explanation: A boolean is like a yes/no question. It only has two answers: yes (True) or no (False).
Realâlife example: "Is it raining outside?" â True or False.
School example: "Is the homework done?" â True or False.
Home example: "Is the door locked?" â True or False.
Nigerian example: "Is the market open today?" â True or False.
+------------------------------------------+ | Boolean Examples | |------------------------------------------+ | is_raining = True | | is_homework_done = False | | is_logged_in = True | | is_adult = False | | | | Booleans are either True or False. | | They help programs make decisions. | +------------------------------------------+
Mini summary: Booleans are True or False. They are used for decisions and conditions.
Definition: To store data, you put a value into a variable (like age = 10). To retrieve it, you just use the variable name (like print(age)).
Why it's important: Storing and retrieving data is what makes programs useful. You put information in, and you take it out when you need it.
Simple explanation: It's like putting your books in a locker and later taking them out to study.
Realâlife example: A shopkeeper stores prices in a book and looks them up when a customer asks.
School example: You store your homework in a folder and retrieve it when the teacher asks for it.
Home example: You store your toys in a box and take them out to play.
Nigerian example: A market woman stores her sales in a notebook and checks the total at the end of the day.
+------------------------------------------+ | Storing and Retrieving | |------------------------------------------+ | # Storing data: | | name = "Chidi" | | age = 10 | | | | # Retrieving data: | | print(name) # Output: Chidi | | print(age) # Output: 10 | | | | You store data in variables, and you | | retrieve it by using the variable name. | +------------------------------------------+
Mini summary: You store data in variables using '=', and retrieve it by using the variable name.
Definition: Input is how we get data from the person using the program. The program asks a question, and the user types the answer.
Why it's important: Input makes programs interactive. They can respond differently depending on what the user says.
Simple explanation: It's like a teacher asking a student, "What is your name?" and the student answers.
Realâlife example: A website asks for your username and password.
School example: A quiz program asks you a question and you type your answer.
Home example: A voice assistant asks, "What can I help you with?"
Nigerian example: An ATM asks for your PIN and you type it in.
+------------------------------------------+
| Input in Python |
|------------------------------------------+
| name = input("What is your name? ") |
| print("Hello, " + name + "!") |
| |
| If user types "Chidi", output is: |
| Hello, Chidi! |
| |
| Input makes programs interactive! |
+------------------------------------------+
Mini summary: Input is how we get information from the user. It makes programs interactive.
Definition: Output is how we display information to the user â on the screen, on paper, or through sound.
Why it's important: Output is how the program communicates back to the user. Without output, a program would be silent.
Simple explanation: It's like when you answer a question in class â that's your output.
Realâlife example: A calculator shows the result on the screen.
School example: A program prints "You scored 85%" on the screen.
Home example: A microwave beeps when the food is ready â that's output.
Nigerian example: A POS machine prints a receipt â that's output.
+------------------------------------------+
| Output in Python |
|------------------------------------------+
| print("Hello, World!") |
| print("Your score is:", score) |
| |
| print() sends text to the screen. |
| You can combine text and variables. |
+------------------------------------------+
Mini summary: Output is how a program shows information to the user. print() is the most common output.
Definition: Type conversion is changing a value from one data type to another â like converting a string "10" to an integer 10.
Why it's important: Sometimes you need to change data types to do certain operations. For example, you can't do maths with text.
Simple explanation: It's like when you convert a recipe from cups to grams â you change the form of the same thing.
Realâlife example: Converting a temperature from Celsius to Fahrenheit.
School example: Converting a score from a fraction to a percentage.
Home example: Converting money from Naira to Dollars.
Nigerian example: Converting the exchange rate from Naira to other currencies.
+------------------------------------------+ | Type Conversion | |------------------------------------------+ | # String to integer: | | age_str = "10" | | age_int = int(age_str) | | | | # Integer to string: | | score = 85 | | score_str = str(score) | | | | # String to float: | | price_str = "5.99" | | price_float = float(price_str) | | | | Convert data types when needed! | +------------------------------------------+
Mini summary: Type conversion is changing one data type to another. Use int(), str(), and float().
Definition: Let's write a simple program that uses variables, input, and output.
Why it's important: This shows how everything we've learned works together.
Simple explanation: We will ask the user for their name and age, then print a greeting.
Realâlife example: A form that asks for your details and confirms them.
School example: A registration program that records student details.
Home example: A program that asks for your preferences.
Nigerian example: A simple banking app that asks for your name and balance.
+------------------------------------------+
| Simple Program Example |
|------------------------------------------+
| # Ask for user's name |
| name = input("Enter your name: ") |
| |
| # Ask for user's age |
| age_str = input("Enter your age: ") |
| age = int(age_str) |
| |
| # Display a greeting |
| print("Hello, " + name + "!") |
| print("You are " + str(age) + " years old.")|
| |
| This combines input, variables, and |
| output! |
+------------------------------------------+
Mini summary: A simple program combines input, variables, type conversion, and output to interact with the user.
In this module, we learned about variables and data types. We discovered that variables are named boxes that store information. We learned about the four main data types: integers (whole numbers), floats (decimal numbers), strings (text), and booleans (True/False). We practiced storing and retrieving data, and we used input and output to interact with users. We also learned how to convert data types when needed. Now you can write programs that remember and use information â you are on your way to becoming a real programmer!
Concept 1: Variables store data. They are essential for any program.
Concept 2: Different data types store different kinds of data. Use the right type for the right job.
Concept 3: Input and output make programs interactive. Programs can talk to users.
Concept 4: Type conversion helps when mixing different types. Always convert when needed.
How to create and use a variable:
How to get user input:
We've seen many realâlife examples in the lessons, such as shopping lists, bank accounts, recipes, and forms. These show how variables and data types are used in everyday life.
In Nigeria, variables are used in banking apps (account balance), market systems (prices and quantities), and government databases (names and IDs). Understanding variables helps you build realâworld applications.
Imagine a game where you collect coins. Your "score" variable stores how many coins you have. Every time you get a coin, you add 1 to score. That's a variable in action!
Another fun example: A robot that asks your name and says "Hello, [your name]!" â that uses a variable to store your name.
Key points: Emphasize the analogy of lockers and boxes. Use interactive activities with input and output. Practice naming variables with descriptive names. Show how type conversion is essential.
Activity idea: Have students write a program that asks for their name, age, and favourite colour, then prints a greeting.
Parents can help children understand variables by pointing out examples in daily life â like labels on boxes, money in a bank account, or names in a phone. Encourage them to think about "data types" â is it a number, text, or true/false?
Did you know that a string is called a "string" because it's a string (sequence) of characters?
Did you know that booleans are named after George Boole, a mathematician who invented Boolean logic?
+------------------------------------------+ | Data Types Summary | |------------------------------------------+ | Type | Example | What it is | |----------+-----------+-------------------| | Integer | 10 | Whole number | | Float | 3.14 | Decimal number | | String | "Hello" | Text | | Boolean | True | True or False | +------------------------------------------+ +------------------------------------------+ | Variable in Memory | |------------------------------------------+ | +-------------------+ | | | Variable Name | | | | age | | | +-------------------+ | | | Value | | | | 10 | | | +-------------------+ | | | | The computer stores the name and | | the value in memory. | +------------------------------------------+
| Data Type | Example | Use |
|---|---|---|
| Integer | 5, -3, 100 | Counting, scores |
| Float | 3.14, 2.5 | Measurements, prices |
| String | "Hello", "Chidi" | Names, messages |
| Boolean | True, False | Conditions, yes/no |
| Operation | Integer | Float | String |
|---|---|---|---|
| Addition | 5 + 3 = 8 | 5.0 + 3.0 = 8.0 | "Hello" + "World" = "HelloWorld" |
| Multiplication | 5 * 3 = 15 | 5.0 * 3.0 = 15.0 | "Hi" * 3 = "HiHiHi" |
In this module, we learned the building blocks of programming â variables and data types. We discovered that variables are like labelled boxes that store information. We explored the four main data types: integers (whole numbers), floats (decimal numbers), strings (text), and booleans (true/false). We learned how to store and retrieve data, and how to get input from users and show output. We also learned how to convert data types when needed. You are now able to write programs that remember information and interact with users. This is a huge step in your coding journey!
Match the term with its definition.
| Term | Definition |
|---|---|
| Integer | a) Text data |
| Float | b) Whole number |
| String | c) True or False |
| Boolean | d) Decimal number |
| Variable | e) A named box storing data |
Answers: Integer â b, Float â d, String â a, Boolean â c, Variable â e
Scenario 1: You are building a program that calculates the total price of items in a shop. The price of an item is 5.99 Naira, and the quantity is 3. What data types would you use for price and quantity? How would you calculate the total?
Scenario 2: A program asks the user for their favourite colour and prints "Your favourite colour is [colour]". Write the code using variables, input, and output.
"Data Type Detective" â In groups of 4, write a program that asks the user for their name, age, height (in meters), and whether they like coding (yes/no). Use the correct data types for each. Print a summary of the user's information.
Write a program that asks the user for two numbers, converts them to integers, adds them, and prints the result.
"Personal Profile Program" â Write a program that asks the user for their name, age, favourite subject, and whether they have a pet. Store each answer in a variable with the correct data type. Print a summary of the user's profile.
Write a program that converts Celsius to Fahrenheit. The formula is: F = (C Ă 9/5) + 32. Ask the user for the temperature in Celsius (as a float), convert it, and print the result.
"Simple Calculator" â Write a program that asks the user for two numbers and an operation (addition, subtraction, multiplication, or division). Use input, variables, and type conversion to perform the operation and print the result.
In Module 4, we will explore Operators and Expressions. You will learn how to perform calculations, compare values, and combine different operations. You will be able to make your programs do maths and make decisions. Get ready to crunch numbers and build powerful expressions!
Module Introduction
Welcome back, coders! In Module 3, we learned about variables and data types â how to store information. Now it's time to learn how to work with that information. We use operators and expressions to perform actions on data. Operators are like tools in a toolbox â they let you add, subtract, compare, and combine values. An expression is a combination of values and operators that produces a result. Think of it like a maths problem: 5 + 3 is an expression, and the result is 8. In this module, we will learn about arithmetic operators (for maths), comparison operators (for comparing), logical operators (for decisions), and assignment operators (for storing values). By the end, you will be able to write programs that do real calculations and make smart decisions. Let's crunch some numbers!
Ada is 11 years old. She helps her mother at the market. She needs to calculate the total cost of items for a customer. The customer buys 3 oranges at 50 Naira each and 2 breads at 200 Naira each. Ada thinks: "3 Ă 50 = 150, 2 Ă 200 = 400, total = 550 Naira." She uses operations like multiplication and addition. Then the customer says, "I have a 20% discount." Ada calculates the discount and says, "You pay 440 Naira." Ada uses operators to do all the maths. After the customer leaves, Ada realizes that coding is just like doing maths â you use operators to calculate and compare. She becomes the fastest calculator in the market!
Definition: An operator is a symbol that performs an action on one or more values. An expression is a combination of values and operators that produces a result.
Why it's important: Without operators, programs couldn't do maths, compare values, or make decisions. They are the action words of coding.
Simple explanation: Operators are like verbs in a sentence â they do something. Expressions are like complete sentences â they have a result.
Realâlife example: In maths, 5 + 3 is an expression. The '+' is an operator.
School example: In a science experiment, you calculate the average â that's using operators.
Home example: When you count money, you are using addition.
Nigerian example: A trader adds up sales at the end of the day â that's using operators.
+------------------------------------------+ | Operators and Expressions | |------------------------------------------+ | Expression: 5 + 3 | | Operators: + (plus) | | Result: 8 | | | | Expression: (10 - 2) * 3 | | Operators: - and * | | Result: 24 | | | | Operators are the tools that make | | calculations and decisions possible. | +------------------------------------------+
Mini summary: Operators perform actions; expressions are combinations of operators and values that produce a result.
Definition: Arithmetic operators are used for mathematical calculations â addition, subtraction, multiplication, division, and modulo (remainder).
Why it's important: They allow programs to do all kinds of maths â from simple counting to complex scientific calculations.
Simple explanation: These are the same maths symbols you use every day â +, -, Ă, á.
Realâlife example: Adding prices, calculating discounts, and splitting bills.
School example: Calculating your average grade.
Home example: Counting how many eggs you need for a recipe.
Nigerian example: Calculating the total cost of items in a market.
+------------------------------------------+ | Arithmetic Operators | |------------------------------------------+ | + (Addition) 5 + 3 = 8 | | - (Subtraction) 10 - 4 = 6 | | * (Multiplication) 3 * 4 = 12 | | / (Division) 15 / 3 = 5.0 | | % (Modulo) 10 % 3 = 1 (remainder)| | | | Modulo gives the remainder after | | division. | +------------------------------------------+
Mini summary: Arithmetic operators are +, -, *, /, and %. They help us do maths in code.
Definition: Addition (+) combines two numbers. Subtraction (-) subtracts one number from another.
Why it's important: These are the most basic and useful operations in any program.
Simple explanation: Addition puts things together; subtraction takes them away.
Realâlife example: Adding items to a cart, subtracting money spent.
School example: Adding scores, subtracting points for mistakes.
Home example: Adding ingredients, subtracting what you used.
Nigerian example: Adding daily sales, subtracting expenses.
+------------------------------------------+ | Addition and Subtraction | |------------------------------------------+ | # Addition | | total = 10 + 5 | | print(total) # Output: 15 | | | | # Subtraction | | result = 20 - 8 | | print(result) # Output: 12 | | | | They work with numbers (integers and | | floats). | +------------------------------------------+
Mini summary: + adds, - subtracts. They are the most common operators.
Definition: Multiplication (*) multiplies numbers. Division (/) divides one number by another.
Why it's important: They are used for scaling, averaging, and many other calculations.
Simple explanation: Multiplication is repeated addition; division is splitting into equal parts.
Realâlife example: Calculating total price (price Ă quantity).
School example: Finding the average score (sum / count).
Home example: Scaling a recipe (multiply ingredients).
Nigerian example: Calculating the total cost of buying 5 oranges at 50 Naira each.
+------------------------------------------+ | Multiplication and Division | |------------------------------------------+ | # Multiplication | | total = 5 * 50 | | print(total) # Output: 250 | | | | # Division | | avg = 100 / 4 | | print(avg) # Output: 25.0 | | | | Division always returns a float (decimal)| | in Python 3. | +------------------------------------------+
Mini summary: * multiplies, / divides. They are essential for many calculations.
Definition: Modulo (%) gives the remainder after division. For example, 10 % 3 = 1 because 3 goes into 10 three times (9) with 1 left over.
Why it's important: Modulo is useful for checking even/odd numbers, cycling through values, and many other tasks.
Simple explanation: After you divide, it tells you what is left over.
Realâlife example: Splitting 10 oranges among 3 people â 3 each, 1 left over.
School example: Checking if a number is even (n % 2 == 0).
Home example: Dividing cookies among friends.
Nigerian example: Sharing money equally and finding the remainder.
+------------------------------------------+
| Modulo Example |
|------------------------------------------+
| # Check if a number is even |
| num = 10 |
| if num % 2 == 0: |
| print("Even") |
| else: |
| print("Odd") |
| |
| # Cycle through values |
| day = 1 |
| day = day % 7 # 1, 2, 3, 4, 5, 6, 0 |
| |
| Modulo is very useful! |
+------------------------------------------+
Mini summary: % gives the remainder after division. It is used for many tasks.
Definition: Assignment operators are used to store values in variables. The most common is '='. There are also compound assignment operators like +=, -=, *=.
Why it's important: They let you update variables easily.
Simple explanation: = puts a value into a variable. += adds to the variable and stores the result.
Realâlife example: Adding money to your savings: savings = savings + 100.
School example: Adding points to your score.
Home example: Counting how many steps you've taken.
Nigerian example: Adding daily earnings to total savings.
+------------------------------------------+ | Assignment Operators | |------------------------------------------+ | # Simple assignment | | score = 0 | | score = 10 # score is now 10 | | | | # Compound assignment | | score = 10 | | score += 5 # score = score + 5 = 15 | | score -= 3 # score = score - 3 = 12 | | score *= 2 # score = score * 2 = 24 | | score /= 4 # score = score / 4 = 6.0 | | | | They make your code shorter and clearer.| +------------------------------------------+
Mini summary: Assignment operators store values. +=, -=, etc., update variables in one step.
Definition: Comparison operators compare two values and return True or False. They are used to make decisions.
Why it's important: Comparisons are the basis of decisions in programs â like checking if a score is high enough.
Simple explanation: These operators ask questions like "Is this equal to that?" or "Is this greater than that?"
Realâlife example: Checking if your age is 18 or older.
School example: Checking if your score is above 50%.
Home example: Checking if you have enough money to buy something.
Nigerian example: Checking if a customer is old enough to vote.
+------------------------------------------+ | Comparison Operators | |------------------------------------------+ | == Equal to 5 == 5 â True | | != Not equal to 5 != 3 â True | | > Greater than 5 > 3 â True | | < Less than 5 < 3 â False | | >= Greater or equal 5 >= 5 â True | | <= Less or equal 5 <= 3 â False | | | | They always return True or False. | +------------------------------------------+
Mini summary: Comparison operators compare values and return True or False. They are used in decisions.
Definition: The equality operator (==) checks if two values are equal. The inequality operator (!=) checks if they are not equal.
Why it's important: They are used to check if a condition is met â like if a user's password is correct.
Simple explanation: == asks "Are these the same?" != asks "Are these different?"
Realâlife example: Checking if the PIN entered is correct.
School example: Checking if the answer is correct.
Home example: Checking if your homework is done.
Nigerian example: Checking if a customer's ID matches the database.
+------------------------------------------+
| Equality Operators |
|------------------------------------------+
| # Check if two values are equal |
| password = "secret" |
| user_input = input("Enter password: ") |
| if user_input == password: |
| print("Access granted!") |
| else: |
| print("Access denied!") |
| |
| # Check if not equal |
| if score != 0: |
| print("You have points!") |
+------------------------------------------+
Mini summary: == checks equality, != checks inequality. They are used for conditions.
Definition: > (greater than), < (less than), >= (greater or equal), and <= (less or equal) compare the magnitude of values.
Why it's important: They are used to check ranges â like if a score is above a passing mark.
Simple explanation: They ask "Is this bigger than that?" or "Is this smaller?"
Realâlife example: Checking if you have enough money (price <= money).
School example: Checking if your grade is above 70.
Home example: Checking if the temperature is below 0.
Nigerian example: Checking if a farmer has enough crops (quantity >= 100).
+------------------------------------------+
| Greater and Less Than |
|------------------------------------------+
| # Check if score is passing |
| score = 75 |
| if score >= 70: |
| print("Passed!") |
| else: |
| print("Failed!") |
| |
| # Check if temperature is freezing |
| temp = -2 |
| if temp < 0: |
| print("It's freezing!") |
+------------------------------------------+
Mini summary: >, <, >=, <= compare sizes. They are used for range checks.
Definition: Logical operators combine multiple conditions: and, or, not.
Why it's important: They allow you to check complex conditions â like "If the user is logged in AND has permission."
Simple explanation: and means both must be true; or means at least one must be true; not flips true to false.
Realâlife example: "If it's raining AND I have an umbrella, I'll go out."
School example: "If the answer is correct AND I have time, I'll check again."
Home example: "If it's cold AND I have a jacket, I'll go outside."
Nigerian example: "If the customer has an ID AND has money, I can serve them."
+------------------------------------------+
| Logical Operators |
|------------------------------------------+
| and: True if both are True |
| or: True if at least one is True |
| not: Flips True to False and vice versa |
| |
| # Example |
| is_raining = True |
| has_umbrella = True |
| if is_raining and has_umbrella: |
| print("I'll go out.") |
| else: |
| print("I'll stay in.") |
| |
| # not example |
| is_logged_in = False |
| if not is_logged_in: |
| print("Please log in.") |
+------------------------------------------+
Mini summary: and, or, not combine conditions. They make complex decisions possible.
Definition: Operator precedence determines the order in which operations are performed in an expression, just like in maths (BODMAS).
Why it's important: Knowing precedence helps you write correct expressions without mistakes.
Simple explanation: Just like in maths, multiplication comes before addition. Brackets override everything.
Realâlife example: In maths, 2 + 3 Ă 4 = 14 (not 20).
School example: In a formula, you need to know which operation to do first.
Home example: Calculating total with discounts â you multiply first.
Nigerian example: Calculating profit â you subtract costs after multiplying quantities.
+------------------------------------------+ | Operator Precedence | |------------------------------------------+ | Highest to lowest: | | 1. Brackets ( ) | | 2. Multiplication (*) and Division (/) | | 3. Addition (+) and Subtraction (-) | | 4. Comparison operators | | 5. Logical operators (not, and, or) | | | | # Examples | | result = 2 + 3 * 4 # 14 (not 20) | | result = (2 + 3) * 4 # 20 | +------------------------------------------+
Mini summary: Operator precedence is the order of operations. Use brackets to make it clear.
Definition: You can combine multiple operators to build complex expressions that do several things at once.
Why it's important: Complex expressions make programs efficient and powerful.
Simple explanation: You can mix arithmetic, comparison, and logical operators in one line.
Realâlife example: Calculating total price with tax and discount.
School example: Calculating final grade from assignments, exams, and bonuses.
Home example: Figuring out the cost of a shopping trip with discounts.
Nigerian example: Calculating the final price of goods after VAT.
+------------------------------------------+
| Complex Expression Example |
|------------------------------------------+
| # Calculate final price |
| price = 1000 |
| discount = 0.1 # 10% |
| tax = 0.05 # 5% |
| final = price * (1 - discount) * (1 + tax) |
| print(final) # 945.0 |
| |
| # Check if a number is between 10 and 20|
| num = 15 |
| if num >= 10 and num <= 20: |
| print("In range") |
+------------------------------------------+
Mini summary: Complex expressions combine multiple operators for powerful results.
Definition: Let's build a simple calculator program that uses arithmetic operators.
Why it's important: This shows how operators are used in a real program.
Simple explanation: We will ask for two numbers and an operation, then compute the result.
Realâlife example: A calculator app on your phone.
School example: A program that solves maths problems.
Home example: A tool to help with shopping calculations.
Nigerian example: A program for market traders to calculate totals.
+------------------------------------------+
| Simple Calculator Program |
|------------------------------------------+
| # Ask for two numbers |
| num1 = float(input("Enter first number: ")) |
| num2 = float(input("Enter second number: ")) |
| op = input("Enter operation (+, -, *, /): ") |
| |
| if op == "+": |
| result = num1 + num2 |
| elif op == "-": |
| result = num1 - num2 |
| elif op == "*": |
| result = num1 * num2 |
| elif op == "/": |
| result = num1 / num2 |
| else: |
| result = "Invalid operation" |
| |
| print("Result:", result) |
+------------------------------------------+
Mini summary: A calculator program uses arithmetic operators to perform calculations based on user input.
In this module, we learned about operators and expressions. We discovered arithmetic operators (+, -, *, /, %) for maths. We learned assignment operators (=, +=, etc.) to store values. We explored comparison operators (==, !=, >, <, >=, <=) to compare values. We learned logical operators (and, or, not) to combine conditions. We also learned about operator precedence and built complex expressions. Finally, we built a simple calculator. You now have the tools to do calculations and make decisions in your programs!
Concept 1: Operators perform actions. They are the verbs of programming.
Concept 2: Expressions produce values. They are the sentences.
Concept 3: Precedence matters. Know the order of operations.
Concept 4: Comparisons return True or False. They are used for decisions.
How to evaluate an expression:
How to use a compound assignment:
We've seen many realâlife examples in the lessons, such as market calculations, discounts, temperature checks, and calculators. These show how operators are used in daily life.
In Nigeria, operators are used in market calculations, banking apps, and business applications. Traders add totals, calculate discounts, and compare prices. Understanding operators helps you build practical applications.
Imagine a game where you collect coins. Your score increases by 10 each time you collect a coin: score += 10. That's an operator!
Another fun example: A program that tells you if you can go outside. It checks: if it's sunny AND you have your shoes on, then you can go out.
Key points: Emphasize the difference between '=' (assignment) and '==' (equality). Use realâlife maths examples. Practice with different operator combinations. Show how precedence affects results.
Activity idea: Have students calculate the total cost of a shopping list using operators.
Parents can help children understand operators by involving them in realâlife calculations â like shopping, budgeting, or cooking. Ask them to calculate totals and discounts. Show them that coding operators are the same as maths operators.
Did you know that you can chain comparisons in Python? For example: 5 < x < 10 means x is between 5 and 10.
Did you know that the order of operations in programming is the same as in maths (BODMAS)?
+------------------------------------------+ | Operator Precedence Pyramid | |------------------------------------------+ | ( ) Highest | | * / | | + - | | == != > < >= <= | | not | | and | | or Lowest | | | | Use brackets to be safe! | +------------------------------------------+ +------------------------------------------+ | Expression Tree Example | |------------------------------------------+ | Expression: (3 + 4) * (10 - 5) | | | | Step 1: 3 + 4 = 7 | | Step 2: 10 - 5 = 5 | | Step 3: 7 * 5 = 35 | | | | Result: 35 | +------------------------------------------+
| Operator Type | Operators | Purpose |
|---|---|---|
| Arithmetic | +, -, *, /, % | Maths calculations |
| Assignment | =, +=, -=, *=, /= | Store and update values |
| Comparison | ==, !=, >, <, >=, <= | Compare values |
| Logical | and, or, not | Combine conditions |
| Expression | Result | Explanation |
|---|---|---|
| 5 + 3 * 2 | 11 | 3*2=6, 5+6=11 |
| (5 + 3) * 2 | 16 | 5+3=8, 8*2=16 |
| 10 / 3 | 3.333... | Division gives a float |
| 10 % 3 | 1 | Remainder |
| 5 > 3 and 4 < 6 | True | Both true |
In this module, we learned the power of operators and expressions. We explored arithmetic operators (+, -, *, /, %) for maths, assignment operators (=, +=, etc.) to store values, comparison operators (==, !=, >, <, >=, <=) to make decisions, and logical operators (and, or, not) to combine conditions. We learned that operator precedence determines the order of operations, and we saw how to build complex expressions. Finally, we built a simple calculator program. You now have the tools to do calculations, compare values, and make decisions in your programs. This is a huge step towards becoming a real programmer!
Match the operator with its description.
| Operator | Description |
|---|---|
| + | a) Remainder after division |
| % | b) Multiplication |
| == | c) Addition |
| * | d) Equality check |
| > | e) Greater than |
Answers: + â c, % â a, == â d, * â b, > â e
Scenario 1: A student wants to calculate their final grade. The final grade is 60% exam, 30% homework, and 10% participation. Write an expression to calculate the final grade given three variables: exam, homework, participation.
Scenario 2: A shopkeeper wants to calculate the total price after a discount. The price is 5000 Naira, and the discount is 15%. Write an expression to calculate the final price.
"Operator Challenge" â In groups of 4, write a program that asks the user for two numbers and an operation. Perform the operation and print the result. Then add error handling for division by zero.
Write a program that asks the user for their age and checks if they are old enough to vote (age >= 18). Print a message telling them if they can vote or not.
"Simple Calculator" â Build a calculator program that can add, subtract, multiply, divide, and also calculate the remainder (modulo). Ask the user for two numbers and an operation. Use ifâelif statements and operators.
Write a program that calculates the area of a rectangle (length Ă width) and the perimeter (2 Ă (length + width)). Ask the user for the length and width, then display both results.
"Temperature Converter" â Write a program that converts temperature from Celsius to Fahrenheit and also from Fahrenheit to Celsius. Ask the user which conversion they want and perform the calculation using operators.
In Module 5, we will explore Control Flow â Making Decisions. You will learn how to use ifâelse statements to make your programs decide what to do based on conditions. You will also learn about loops to repeat actions. Get ready to make your programs smart and responsive!
Module Introduction
Welcome back, coders! In Module 4, we learned about operators and expressions â how to do maths and comparisons. Now it's time to make our programs smart. We want them to make decisions â like "If the user is logged in, show the dashboard; otherwise, show the login screen." This is called control flow. Control flow allows programs to choose different paths based on conditions. Think of it like a road with branches: you can go left or right depending on the traffic light. In this module, we will learn about conditionals (if, elif, else) and how they control the flow of a program. We will also learn about loops (for, while) that let us repeat actions. By the end, your programs will be able to make decisions and repeat tasks automatically. Let's start steering our code!
Chidi is 11 years old. He wants to buy a snack after school. He has 200 Naira. He sees a chocolate for 150 Naira and a biscuit for 100 Naira. He thinks: "IF I have enough money for chocolate, I will buy chocolate. ELSE IF I have enough for biscuit, I will buy biscuit. ELSE I will buy nothing." Chidi makes a decision based on his money. This is exactly what control flow does â it makes decisions based on conditions. Chidi decides to buy chocolate because he has enough. He feels happy. In coding, we use ifâelse statements to make decisions just like Chidi.
Definition: Control flow is the order in which a program executes its instructions. It can be sequential (step by step), conditional (decisions), or repetitive (loops).
Why it's important: Without control flow, programs would just run from top to bottom with no decisions or repeats. Control flow makes programs dynamic and flexible.
Simple explanation: Control flow is like a road map â it tells the program which path to take at each intersection.
Realâlife example: A traffic light controls the flow of cars. If the light is red, stop; if green, go.
School example: A teacher decides: "If the bell rings, go home. Else, stay in class."
Home example: "If it's raining, take an umbrella. Else, don't."
Nigerian example: "If I have enough money, I will take a bus. Else, I will walk."
+------------------------------------------+ | What is Control Flow? | |------------------------------------------+ | +---------+ | | | Start | | | +----+----+ | | | | | v | | +---------+ +---------+ | | | Decision| -> | Action | | | | (if) | | (then) | | | +----+----+ +---------+ | | | | | v | | +---------+ | | | End | | | +---------+ | | | | Control flow decides which path to take.| +------------------------------------------+
Mini summary: Control flow is how a program decides what to do and in what order. It includes decisions and repeats.
Definition: The if statement checks a condition. If the condition is True, it runs the code inside the block. If it's False, it skips it.
Why it's important: if statements are the most basic way to make decisions in code.
Simple explanation: Think of it like: "If it's raining, take an umbrella." The condition is "it's raining." If True, you take the umbrella.
Realâlife example: "If I have enough money, I will buy the toy."
School example: "If I score above 70, I get an A."
Home example: "If I'm hungry, I will eat."
Nigerian example: "If the price is low, I will buy more."
+------------------------------------------+
| if Statement Example |
|------------------------------------------+
| # Python code |
| age = 10 |
| if age >= 18: |
| print("You are an adult.") |
| else: |
| print("You are a child.") |
| |
| # Output: You are a child. |
| |
| The condition age >= 18 is False, so |
| the else block runs. |
+------------------------------------------+
Mini summary: The if statement checks a condition and runs code only if the condition is True.
Definition: Indentation means adding spaces (or tabs) at the beginning of a line. In Python, indentation is used to show which lines of code belong to a block.
Why it's important: Indentation tells the computer where the if statement's code starts and ends.
Simple explanation: Imagine a list: you indent items under a heading. Code works the same â indented lines "belong" to the condition.
Realâlife example: In a bulleted list, items are indented under a main point.
School example: When writing an essay, paragraphs are indented to show a new idea.
Home example: In a recipe, the steps are indented under the ingredient list.
Nigerian example: In a market list, items are grouped under a category.
+------------------------------------------+
| Indentation Example |
|------------------------------------------+
| if age >= 18: |
| print("You are an adult.") â indented 4 spaces |
| print("You can vote.") â indented 4 spaces |
| else: |
| print("You are a child.") â indented 4 spaces |
| |
| The indented lines are part of the if |
| block. In Python, indentation is |
| mandatory! |
+------------------------------------------+
Mini summary: Indentation (spaces at the start of a line) shows which code belongs to a block.
Definition: The else statement runs code when the if condition is False. It provides an alternative path.
Why it's important: else lets you handle both True and False cases.
Simple explanation: "If it's raining, take an umbrella. Else, don't take one."
Realâlife example: "If I have time, I'll read. Else, I'll sleep."
School example: "If I pass, I'm happy. Else, I'm sad."
Home example: "If it's cold, wear a jacket. Else, wear a shirt."
Nigerian example: "If I have money, I'll buy a car. Else, I'll save."
+------------------------------------------+
| else Example |
|------------------------------------------+
| score = 65 |
| if score >= 70: |
| print("Passed!") |
| else: |
| print("Failed!") |
| |
| # Output: Failed! |
| |
| else gives an alternative when the |
| condition is False. |
+------------------------------------------+
Mini summary: else runs code when the if condition is False. It is the alternative path.
Definition: elif (short for "else if") lets you check multiple conditions. If the first if is False, it checks the next condition.
Why it's important: elif allows you to handle many possibilities, not just True or False.
Simple explanation: "If I have 200 Naira, buy chocolate. Else if I have 100 Naira, buy biscuit. Else, buy nothing."
Realâlife example: Grading: A, B, C, D, F.
School example: "If score >= 90, grade A. Else if >= 80, grade B. Else if >= 70, grade C."
Home example: "If it's sunny, go outside. Else if it's cloudy, stay inside. Else, read a book."
Nigerian example: "If price is low, buy. Else if price is medium, wait. Else, don't buy."
+------------------------------------------+
| elif Example |
|------------------------------------------+
| score = 85 |
| if score >= 90: |
| grade = "A" |
| elif score >= 80: |
| grade = "B" |
| elif score >= 70: |
| grade = "C" |
| elif score >= 60: |
| grade = "D" |
| else: |
| grade = "F" |
| print("Grade:", grade) |
| |
| # Output: Grade: B |
| |
| elif checks multiple conditions in order.|
+------------------------------------------+
Mini summary: elif allows you to check multiple conditions in sequence. The first True condition runs.
Definition: A nested conditional is an if statement inside another if statement. It allows for more complex decisionâmaking.
Why it's important: Some decisions depend on other decisions. Nested conditionals handle these situations.
Simple explanation: "If I have money, then if the price is low, I will buy."
Realâlife example: "If I have time, then if I have money, I'll go to the cinema."
School example: "If I pass the exam, then if I get a high score, I'll celebrate."
Home example: "If it's sunny, then if I have sunscreen, I'll go to the beach."
Nigerian example: "If I have enough money, then if the price is fair, I'll buy the goods."
+------------------------------------------+
| Nested Conditionals Example |
|------------------------------------------+
| has_money = True |
| price_low = True |
| if has_money: |
| if price_low: |
| print("I will buy it!") |
| else: |
| print("Too expensive.") |
| else: |
| print("No money.") |
| |
| # Output: I will buy it! |
| |
| The inner if runs only if the outer |
| condition is True. |
+------------------------------------------+
Mini summary: Nested conditionals are if statements inside other if statements. They allow for complex decisions.
Definition: A Boolean expression is an expression that evaluates to either True or False. It uses comparison and logical operators.
Why it's important: Conditions in if statements are Boolean expressions. Understanding them is key to control flow.
Simple explanation: A Boolean expression asks a yes/no question. The answer is either True or False.
Realâlife example: "Is it raining?" â True or False.
School example: "Is the score greater than 70?" â True or False.
Home example: "Is the fridge empty?" â True or False.
Nigerian example: "Is the market open?" â True or False.
+------------------------------------------+ | Boolean Expressions | |------------------------------------------+ | # Examples of Boolean expressions | | 5 > 3 # True | | 10 < 5 # False | | age >= 18 # True or False | | score == 100 # True or False | | has_money and price_low # True or False | | | | They always evaluate to True or False. | +------------------------------------------+
Mini summary: Boolean expressions are conditions that evaluate to True or False. They are used in if statements.
Definition: Let's build a simple number guessing game that uses if, elif, else, and comparison operators.
Why it's important: This shows how control flow can create an interactive program.
Simple explanation: The program picks a secret number. The user guesses. The program gives clues (too high, too low, correct).
Realâlife example: Many games use guessing mechanics.
School example: A teacher's quiz game.
Home example: A family game night.
Nigerian example: A local radio game where listeners guess the answer.
+------------------------------------------+
| Number Guessing Game |
|------------------------------------------+
| secret = 7 |
| guess = int(input("Guess a number (1-10): ")) |
| |
| if guess == secret: |
| print("You got it!") |
| elif guess > secret: |
| print("Too high!") |
| else: |
| print("Too low!") |
| |
| This is a simple interactive game! |
+------------------------------------------+
Mini summary: A number guessing game uses if, elif, else, and comparisons to interact with the user.
In this module, we learned about control flow â the way programs make decisions. We used if to check conditions, else for alternatives, and elif for multiple conditions. We learned about indentation and Boolean expressions. We nested conditionals and built a number guessing game. Now your programs can be smart and interactive!
Concept 1: Decisions are made with if. It's the most basic control flow tool.
Concept 2: Indentation shows which code belongs to the if block. It's mandatory in Python.
Concept 3: elif and else handle alternative paths. Use elif for multiple conditions.
Concept 4: Nested conditionals allow for complex logic. Use them when decisions depend on other decisions.
How to write an if-else statement:
How to write an if-elif-else chain:
We've seen many realâlife examples in the lessons, such as traffic lights, grading systems, shopping decisions, and weather choices. These show how decisions are made in everyday life.
In Nigeria, decisionâmaking is everywhere. A trader decides: "If the price is low, I buy more. Else, I buy less." A parent decides: "If the child passes, I reward them. Else, I encourage them." Control flow in coding mirrors these realâworld decisions.
Imagine a robot that says: "If you smile, I'll give you a chocolate. Else, I'll sing you a song." That's control flow!
Another fun example: A game where you choose a path. If you choose the left path, you find treasure. Else, you find a dragon.
Key points: Emphasise the importance of indentation. Use realâlife decisionâmaking examples. Practice with simple ifâelse, then move to elif and nested. Use the guessing game to make it interactive.
Activity idea: Have students write a program that asks the user's age and tells them if they are a child, teenager, or adult.
Parents can help children understand control flow by discussing decisions in daily life. Ask: "What would you do if...?" This helps them understand conditionals. Encourage them to think about "if" and "else" in real situations.
Did you know that in Python, you can write if statements on one line? Example: if age >= 18: print("Adult")
Did you know that you can have an 'if' statement without an 'else'? It's perfectly fine!
+------------------------------------------+ | Control Flow Diagram | |------------------------------------------+ | +---------+ | | | Start | | | +----+----+ | | | | | v | | +----+----+ | | | if | | | | cond | | | +----+----+ | | | | | +----------+----------+ | | | | | | v v | | +-------+ +-------+ | | | True | | False | | | +---+---+ +---+---+ | | | | | | v v | | +-------+ +-------+ | | | Block | | else | | | | (if) | | block | | | +---+---+ +---+---+ | | | | | | +-------+----------+ | | | | | v | | +-------+ | | | End | | | +-------+ | +------------------------------------------+
| Statement | Use |
|---|---|
| if | Check a condition, run code if True |
| else | Run code if if is False |
| elif | Check another condition if previous was False |
| Condition | True | False |
|---|---|---|
| 5 > 3 | Yes | No |
| 10 < 5 | No | Yes |
| age >= 18 | Depends | Depends |
In this module, we learned about control flow and how to make decisions in code. We used if to check conditions, else for alternatives, and elif for multiple conditions. We discovered the importance of indentation and Boolean expressions. We nested conditionals for complex decisions and built a number guessing game. You can now make your programs interactive and smart. This is a huge step in your coding journey!
Match the term with its description.
| Term | Description |
|---|---|
| if | a) Runs when condition is False |
| else | b) Checks a condition |
| elif | c) Shows block membership |
| Indentation | d) Checks another condition |
| Boolean | e) True or False |
Answers: if â b, else â a, elif â d, Indentation â c, Boolean â e
Scenario 1: A student wants to check if they passed. If the score is 70 or above, they pass. Else, they fail. Write an ifâelse statement to do this.
Scenario 2: A shop gives a discount: if the total is above 5000 Naira, they get 10% off. Else, they get 5% off. Write a program that calculates the final price.
"DecisionâMaking Program" â In groups of 4, write a program that asks the user for their age, gender, and whether they are a student. Then, based on these conditions, tell them the cost of a cinema ticket (e.g., students get a discount).
Write a program that asks for a number and checks if it is even or odd using the modulo operator and an ifâelse statement.
"Number Guessing Game" â Build a number guessing game where the user guesses a secret number between 1 and 10. Give hints: "Too high", "Too low", or "Correct".
Write a program that asks the user for their age and checks if they are eligible for a driver's license (age >= 18). Print a message accordingly.
"Rock, Paper, Scissors" â Write a simple version of rock, paper, scissors. Ask the user for their choice and randomly generate the computer's choice. Use ifâelifâelse to determine the winner.
In Module 6, we will explore Loops â Repeating Actions. You will learn how to make your programs repeat tasks automatically, using for loops and while loops. You will be able to write programs that do repetitive tasks quickly and efficiently. Get ready to automate!
Module Introduction
Welcome back, coders! In Module 5, we learned how to make decisions with ifâelse statements. Now we are going to learn how to make our programs repeat actions automatically. Imagine if you had to say "Hello" 100 times. That would be boring! But with a loop, you can write just a few lines of code and the computer will do it for you. Loops are like a "repeat" button in programming. There are two main types of loops: for loops (repeat a fixed number of times) and while loops (repeat until a condition is met). In this module, we will learn both. We will also learn about infinite loops (and how to avoid them) and nested loops. By the end, you will be able to write programs that can do repetitive tasks quickly and efficiently. Let's start looping!
Chiamaka is 11 years old. Her mother asks her to sweep the veranda. There are 10 steps. She thinks: "I need to sweep each step. I'll do step 1, then step 2, then step 3... up to step 10." She repeats the same action 10 times. This is like a loop â repeating the same action a number of times. One day, her mother says, "Keep sweeping until the veranda is clean." Chiamaka sweeps and checks: "Is it clean? No? Sweep more. Is it clean? No? Sweep more." This is like a while loop â repeat until a condition is met. Chiamaka learns that loops make repetitive tasks easy â just like in coding!
Definition: A loop is a programming construct that repeats a block of code multiple times.
Why it's important: Loops save time and make code shorter. They are used for repetitive tasks.
Simple explanation: A loop is like a "repeat" button. You tell the computer how many times to repeat an action.
Realâlife example: A washing machine spins the drum 20 times â that's a loop.
School example: Repeating multiplication tables â 1Ă1, 1Ă2, 1Ă3, etc.
Home example: Brushing your teeth â you move the brush up and down repeatedly.
Nigerian example: Counting currency notes â you count each note one by one.
+------------------------------------------+
| What is a Loop? |
|------------------------------------------+
| Without loop: |
| print("Hello") |
| print("Hello") |
| print("Hello") |
| print("Hello") |
| print("Hello") |
| |
| With loop: |
| for i in range(5): |
| print("Hello") |
| |
| Loops make code shorter and cleaner! |
+------------------------------------------+
Mini summary: A loop repeats a block of code multiple times. It saves time and effort.
Definition: A for loop repeats a block of code a specific number of times. It is used when you know how many times to repeat.
Why it's important: for loops are the most common way to repeat actions in programming.
Simple explanation: "For each number from 1 to 10, do something."
Realâlife example: Making 10 sandwiches â do the same steps 10 times.
School example: Writing the multiplication table for 5: 5Ă1, 5Ă2, ..., 5Ă10.
Home example: Folding 10 clothes â repeat folding 10 times.
Nigerian example: Counting 100 Naira notes â count from 1 to 100.
+------------------------------------------+
| for Loop Example |
|------------------------------------------+
| # Repeat 5 times |
| for i in range(5): |
| print("Hello") |
| |
| # Output: |
| Hello |
| Hello |
| Hello |
| Hello |
| Hello |
| |
| The loop runs 5 times. |
+------------------------------------------+
Mini summary: A for loop repeats code a fixed number of times. Use range() to specify the count.
Definition: The range() function generates a sequence of numbers. It is often used in for loops to control how many times the loop runs.
Why it's important: range() makes it easy to count from 0 to nâ1, or from start to stop.
Simple explanation: range(5) gives numbers 0, 1, 2, 3, 4.
Realâlife example: Counting 5 people: 1, 2, 3, 4, 5.
School example: Numbering seats in a class.
Home example: Numbering steps in a recipe.
Nigerian example: Numbering items in a market list.
+------------------------------------------+ | range() Examples | |------------------------------------------+ | # range(5) gives 0, 1, 2, 3, 4 | | for i in range(5): | | print(i) | | # Output: 0, 1, 2, 3, 4 | | | | # range(1, 6) gives 1, 2, 3, 4, 5 | | for i in range(1, 6): | | print(i) | | # Output: 1, 2, 3, 4, 5 | | | | # range(2, 10, 2) gives 2, 4, 6, 8 | | for i in range(2, 10, 2): | | print(i) | | # Output: 2, 4, 6, 8 | +------------------------------------------+
Mini summary: range() generates a sequence of numbers. It is commonly used in for loops.
Definition: A while loop repeats a block of code as long as a condition is True. It stops when the condition becomes False.
Why it's important: while loops are used when you don't know how many times to repeat â you repeat until something happens.
Simple explanation: "While the water is not boiling, keep heating."
Realâlife example: Waiting for a bus â while there is no bus, keep waiting.
School example: While a student is answering questions, keep asking.
Home example: While the rice is not cooked, keep boiling.
Nigerian example: While the market is open, keep selling.
+------------------------------------------+
| while Loop Example |
|------------------------------------------+
| count = 1 |
| while count <= 5: |
| print("Hello") |
| count = count + 1 |
| |
| # Output: |
| Hello |
| Hello |
| Hello |
| Hello |
| Hello |
| |
| The loop runs until count is 6. |
+------------------------------------------+
Mini summary: A while loop repeats as long as a condition is True. It stops when the condition is False.
Definition: An infinite loop is a loop that runs forever because the condition never becomes False.
Why it's important: Infinite loops can crash your program or make it unresponsive. You must avoid them.
Simple explanation: It's like a door that keeps swinging without stopping.
Realâlife example: A fan that keeps spinning without a switch to turn it off.
School example: A teacher who keeps asking the same question without moving on.
Home example: A water tap that keeps running.
Nigerian example: A market seller who keeps calling "Buy! Buy!" without stopping.
+------------------------------------------+
| Infinite Loop Example |
|------------------------------------------+
| # This loop will run forever! |
| while True: |
| print("Hello") |
| |
| # To stop it, you need to use break |
| # or change the condition. |
| |
| # Correct way: |
| count = 0 |
| while count < 5: |
| print("Hello") |
| count += 1 |
+------------------------------------------+
Mini summary: Infinite loops run forever. Always ensure your loop condition will become False.
Definition: The break statement is used to exit a loop immediately, even if the condition is still True.
Why it's important: break lets you stop a loop when a specific condition is met, even if the loop would normally continue.
Simple explanation: "Stop this loop now, no matter what."
Realâlife example: A race ends when the first person finishes â break the loop.
School example: A quiz stops when a student gets a perfect score.
Home example: A washing machine stops when the timer reaches 0.
Nigerian example: A seller stops selling when there are no more goods.
+------------------------------------------+
| break Example |
|------------------------------------------+
| count = 1 |
| while True: |
| print("Looping...") |
| if count == 5: |
| break |
| count += 1 |
| print("Loop ended.") |
| |
| # Output: |
| Looping... |
| Looping... |
| Looping... |
| Looping... |
| Looping... |
| Loop ended. |
| |
| break exits the loop immediately. |
+------------------------------------------+
Mini summary: break exits a loop immediately, even if the condition is still True.
Definition: The continue statement skips the rest of the current iteration and moves to the next one.
Why it's important: continue is used to skip over certain cases without exiting the loop.
Simple explanation: "Skip this time and go to the next."
Realâlife example: If a fruit is bad, skip it and check the next one.
School example: In a test, if you don't know a question, skip it and go to the next.
Home example: If an egg is cracked, skip it and use the next one.
Nigerian example: In a market, if an item is not available, skip it and move to the next.
+------------------------------------------+ | continue Example | |------------------------------------------+ | for i in range(5): | | if i == 2: | | continue | | print(i) | | | | # Output: | | 0 | | 1 | | 3 | | 4 | | | | The loop skipped 2 because of continue.| +------------------------------------------+
Mini summary: continue skips the rest of the current iteration and goes to the next.
Definition: A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Why it's important: Nested loops are used for working with multiâdimensional data (like tables, grids, or matrices).
Simple explanation: "For each hour (outer loop), for each minute (inner loop), do something."
Realâlife example: A clock: for each hour (1â12), for each minute (1â60).
School example: A timetable: for each day, for each period.
Home example: For each room, for each shelf.
Nigerian example: For each market day, for each vendor.
+------------------------------------------+
| Nested Loop Example |
|------------------------------------------+
| # Multiplication table (1 to 3) |
| for i in range(1, 4): |
| for j in range(1, 4): |
| print(i, "x", j, "=", i * j) |
| print("---") |
| |
| # Output: |
| 1 x 1 = 1 |
| 1 x 2 = 2 |
| 1 x 3 = 3 |
| --- |
| 2 x 1 = 2 |
| 2 x 2 = 4 |
| 2 x 3 = 6 |
| --- |
| 3 x 1 = 3 |
| 3 x 2 = 6 |
| 3 x 3 = 9 |
| --- |
+------------------------------------------+
Mini summary: Nested loops are loops inside loops. The inner loop runs completely for each outer iteration.
Definition: You can loop through each element in a list using a for loop. This is called iterating.
Why it's important: Loops allow you to process each item in a list easily.
Simple explanation: "For each item in the list, do something."
Realâlife example: Checking each item in a shopping list.
School example: Checking each student's name on the class list.
Home example: Checking each ingredient in a recipe.
Nigerian example: Checking each item in a market inventory.
+------------------------------------------+ | Looping Through a List | |------------------------------------------+ | fruits = ["apple", "banana", "orange"] | | for fruit in fruits: | | print(fruit) | | | | # Output: | | apple | | banana | | orange | | | | The loop runs for each element in the | | list. | +------------------------------------------+
Mini summary: You can loop through lists to access each element one by one.
Definition: Let's build a countdown program using a while loop.
Why it's important: This shows how loops can create interactive and timed experiences.
Simple explanation: The program counts down from 10 to 1 and then says "Blast off!".
Realâlife example: A rocket launch countdown.
School example: A timer for a quiz.
Home example: A countdown timer for cooking.
Nigerian example: A countdown for a special event.
+------------------------------------------+
| Countdown Program |
|------------------------------------------+
| count = 10 |
| while count >= 1: |
| print(count) |
| count -= 1 |
| print("Blast off!") |
| |
| # Output: |
| 10 |
| 9 |
| 8 |
| 7 |
| 6 |
| 5 |
| 4 |
| 3 |
| 2 |
| 1 |
| Blast off! |
+------------------------------------------+
Mini summary: A countdown program uses a while loop to count from 10 to 1 and then print "Blast off!".
In this module, we learned about loops â a powerful way to repeat actions in code. We explored for loops (fixed repetitions) and while loops (repeat until a condition is met). We used range() to generate numbers, and we learned about break and continue to control loop flow. We saw nested loops and how to loop through lists. You can now write programs that automate repetitive tasks â a huge step in your coding journey!
Concept 1: Loops repeat code. They save time and reduce repetition.
Concept 2: for loops are for known repetitions. Use for when you know how many times to repeat.
Concept 3: while loops are for unknown repetitions. Use while when you don't know how many times to repeat.
Concept 4: Avoid infinite loops. Always ensure your condition will become False.
How to use a for loop:
How to use a while loop:
We've seen many realâlife examples in the lessons, such as washing machines, countdowns, and market lists. These show how loops are used in everyday life.
In Nigeria, loops are used in counting money, market inventories, and event countdowns. Understanding loops helps build practical applications for business and life.
Imagine a robot that dances 10 times. You write a loop: "For each dance step, move arms and legs." The robot repeats the dance 10 times!
Another fun example: A game where you collect coins. While the coin is there, collect it â that's a while loop.
Key points: Emphasize the difference between for and while. Use range() to control for loops. Practice with break and continue. Show examples of infinite loops and how to avoid them. Use nested loops for more advanced examples.
Activity idea: Have students write a program that prints a multiplication table using nested loops.
Parents can help children understand loops by pointing out repetitive tasks in daily life â like making multiple sandwiches or folding clothes. Ask: "How many times do you repeat this action?" This helps them relate to loops.
Did you know that you can loop through strings? For example: for letter in "Hello": print(letter) prints each letter.
Did you know that while True is a common way to create an infinite loop that you break out of with break?
+------------------------------------------+ | Loop Flowchart | |------------------------------------------+ | +-------+ | | | Start | | | +---+---+ | | | | | v | | +-------+ | | | Condition? | | | +---+---+ | | | | | | | | v | | | | +-------+ | | | | True | | | | +---+---+ | | | | | | | v | | | +-------+ | | | | Body | | | | +---+---+ | | | | | | | v | | | +-------+ | | | | Update| | | | +---+---+ | | | | | | | +----------+ | | v | | +-------+ | | | End | | | +-------+ | | | | This is the general flow of a loop. | +------------------------------------------+
| Feature | for loop | while loop |
|---|---|---|
| When to use | Known number of repetitions | Unknown number of repetitions |
| Condition | Based on range() or sequence | Boolean condition |
| Risk | Offâbyâone errors | Infinite loops |
| Statement | Effect |
|---|---|
| break | Exits the loop immediately |
| continue | Skips to the next iteration |
In this module, we learned about loops â a powerful tool for repeating actions in code. We explored for loops, which repeat a fixed number of times, and while loops, which repeat until a condition is met. We used range() to control for loops and learned about break and continue to manage loop flow. We also explored nested loops and looping through lists. You now have the ability to automate repetitive tasks, making your programs more efficient and powerful. This is a major step in your coding journey!
Match the term with its description.
| Term | Description |
|---|---|
| for | a) Repeats until a condition is False |
| while | b) Repeats a fixed number of times |
| break | c) Skips an iteration |
| continue | d) Exits a loop immediately |
| range() | e) Generates a sequence of numbers |
Answers: for â b, while â a, break â d, continue â c, range() â e
Scenario 1: You need to print "Hello" 20 times. Which loop would you use? Write the code.
Scenario 2: You want to keep asking a user for a password until they enter the correct one. Which loop would you use? Write the code.
"Loop Challenge" â In groups of 4, write a program that prints a multiplication table (1 to 5) using nested loops. Each group should present their solution.
Write a program that uses a while loop to count down from 10 to 1 and print "Lift off!" after the countdown.
"Multiplication Table Generator" â Write a program that asks the user for a number and prints its multiplication table from 1 to 12 using a for loop.
Write a program that asks the user for a word and prints each letter of the word on a new line using a for loop.
"Number Guessing Game with Loops" â Build a number guessing game where the user has 5 attempts to guess a secret number. Use a for loop to limit the attempts. Give hints ("Too high", "Too low", or "Correct").
In Module 7, we will explore Lists and Data Structures. You will learn how to store collections of data in lists, tuples, and dictionaries. You will be able to manage and organise data efficiently. Get ready to level up your coding skills!
Module Introduction
Welcome back, coders! In Module 6, we learned about loops â how to repeat actions. Now we are going to learn how to organise data. Imagine you have a collection of books. You wouldn't just throw them on the floor â you would put them on a shelf. In coding, we have lists, tuples, and dictionaries â these are like shelves for our data. They help us store, organise, and access information easily. In this module, we will learn how to create and use lists, add and remove items, and access specific elements. We will also learn about tuples (unchangeable lists) and dictionaries (keyâvalue pairs). By the end, you will be able to manage collections of data like a pro. Let's get organised!
Ada is 11 years old. Her mother asks her to go to the market with a list: "Buy rice, beans, tomatoes, onions, and peppers." Ada writes them down on a piece of paper. At the market, she goes to each store and crosses off the items as she buys them. The list helps her remember everything. In coding, a list is exactly like that â a collection of items you can add to, remove from, or change. Ada also has a phonebook where she stores names and phone numbers. Each name has a number â that's like a dictionary in coding. Ada learns that organising data makes life easier, just like in programming!
Definition: A list is a collection of items in a specific order. You can store many values in one variable.
Why it's important: Lists help you group related items together. They make it easy to manage collections of data.
Simple explanation: A list is like a shopping list â a collection of items you need to remember.
Realâlife example: A grocery list: rice, beans, tomatoes.
School example: A list of students in a class.
Home example: A list of chores: sweep, mop, dust.
Nigerian example: A list of items to buy at the market.
+------------------------------------------+ | What is a List? | |------------------------------------------+ | fruits = ["apple", "banana", "orange"] | | | | A list holds multiple items in one | | variable. | +------------------------------------------+
Mini summary: A list is a collection of items stored in a single variable.
Definition: To create a list, you use square brackets [] and separate items with commas.
Why it's important: Creating lists is the first step to working with collections of data.
Simple explanation: You put items inside [ ] with commas between them.
Realâlife example: [1, 2, 3, 4, 5] is a list of numbers.
School example: ["John", "Mary", "Peter"] is a list of names.
Home example: ["bedroom", "kitchen", "living room"] is a list of rooms.
Nigerian example: ["rice", "beans", "garri"] is a list of food items.
+------------------------------------------+ | Creating a List | |------------------------------------------+ | # Empty list | | empty_list = [] | | | | # List of numbers | | numbers = [1, 2, 3, 4, 5] | | | | # List of strings | | names = ["Chidi", "Ngozi", "Ada"] | | | | # List of mixed types | | mixed = ["Hello", 10, 3.14, True] | | | | Lists can store any data type! | +------------------------------------------+
Mini summary: Use [] to create a list. Items are separated by commas.
Definition: Each item in a list has a position called an index. The first item is at index 0, the second at index 1, and so on.
Why it's important: Indexing lets you access any item in the list by its position.
Simple explanation: It's like a shelf with numbered positions. You ask for item #0, #1, etc.
Realâlife example: In a queue, the first person is at position 0.
School example: Seat numbers in a classroom.
Home example: Steps in a staircase: step 0, step 1, etc.
Nigerian example: Counting items in a market â first item, second item.
+------------------------------------------+ | Indexing Example | |------------------------------------------+ | fruits = ["apple", "banana", "orange"] | | print(fruits[0]) # Output: apple | | print(fruits[1]) # Output: banana | | print(fruits[2]) # Output: orange | | | | Index 0 1 2 | | apple banana orange | +------------------------------------------+
Mini summary: Indexing starts at 0. Use list[index] to access an item.
Definition: You can change an item in a list by assigning a new value to a specific index.
Why it's important: Modifying lets you update data in your list.
Simple explanation: If you made a mistake on your shopping list, you can cross it out and write the correct item.
Realâlife example: Changing "beans" to "rice" on a shopping list.
School example: Updating a student's name in the class list.
Home example: Replacing an item on your toâdo list.
Nigerian example: Changing the price of an item in a market list.
+------------------------------------------+ | Modifying a List | |------------------------------------------+ | fruits = ["apple", "banana", "orange"] | | fruits[1] = "grape" | | print(fruits) # Output: ["apple", "grape", "orange"] | | | | The item at index 1 was changed from | | "banana" to "grape". | +------------------------------------------+
Mini summary: You can change an item by assigning a new value to its index.
Definition: The append() method adds a new item to the end of a list.
Why it's important: append lets you grow your list dynamically.
Simple explanation: It's like adding a new item to the bottom of your shopping list.
Realâlife example: Adding a new item to a grocery list.
School example: Adding a new student to the class list.
Home example: Adding a new chore to your list.
Nigerian example: Adding a new item to a market list.
+------------------------------------------+
| append() Example |
|------------------------------------------+
| fruits = ["apple", "banana"] |
| fruits.append("orange") |
| print(fruits) # Output: ["apple", "banana", "orange"] |
| |
| The new item is added to the end. |
+------------------------------------------+
Mini summary: append() adds an item to the end of a list.
Definition: The insert() method adds an item at a specific position. The remove() method deletes the first occurrence of an item. pop() removes an item by index.
Why it's important: These methods give you full control over list contents.
Simple explanation: insert() is like putting an item in the middle of your list. remove() is like crossing it off.
Realâlife example: Inserting a new item between two existing ones.
School example: Inserting a student in a specific seat.
Home example: Removing an item from your toâdo list.
Nigerian example: Inserting a new product in a shop inventory.
+------------------------------------------+
| insert() and remove() Examples |
|------------------------------------------+
| fruits = ["apple", "orange"] |
| fruits.insert(1, "banana") |
| print(fruits) # Output: ["apple", "banana", "orange"] |
| |
| fruits.remove("banana") |
| print(fruits) # Output: ["apple", "orange"] |
| |
| fruits.pop() # Removes the last item |
| print(fruits) # Output: ["apple"] |
+------------------------------------------+
Mini summary: insert() adds at a position, remove() deletes by value, pop() deletes by index.
Definition: The sort() method arranges list items in ascending order (smallest to largest, A to Z).
Why it's important: Sorting helps you organise and find items quickly.
Simple explanation: It's like arranging your books alphabetically.
Realâlife example: Sorting a shopping list alphabetically.
School example: Sorting students' names alphabetically.
Home example: Sorting your movies by title.
Nigerian example: Sorting market items by price.
+------------------------------------------+ | sort() Example | |------------------------------------------+ | numbers = [5, 2, 8, 1, 3] | | numbers.sort() | | print(numbers) # Output: [1, 2, 3, 5, 8] | | | | words = ["banana", "apple", "grape"] | | words.sort() | | print(words) # Output: ["apple", "banana", "grape"] | +------------------------------------------+
Mini summary: sort() arranges list items in order.
Definition: You can use a for loop to go through each item in a list one by one.
Why it's important: Looping is how you process every item in a list.
Simple explanation: "For each item in the list, do something."
Realâlife example: Checking each item on a shopping list.
School example: Calling each student's name from the class list.
Home example: Going through each chore in your list.
Nigerian example: Going through each item in a market inventory.
+------------------------------------------+
| Looping Through a List |
|------------------------------------------+
| fruits = ["apple", "banana", "orange"] |
| for fruit in fruits: |
| print("I like", fruit) |
| |
| # Output: |
| I like apple |
| I like banana |
| I like orange |
+------------------------------------------+
Mini summary: Use a for loop to process each item in a list.
Definition: The len() function returns the number of items in a list.
Why it's important: len() helps you know how many items you have.
Simple explanation: It's like counting how many items are on your shopping list.
Realâlife example: Counting items in a shopping cart.
School example: Counting students in a class.
Home example: Counting how many chores are left.
Nigerian example: Counting items in a market stall.
+------------------------------------------+ | len() Example | |------------------------------------------+ | fruits = ["apple", "banana", "orange"] | | print(len(fruits)) # Output: 3 | | | | len() gives the number of items in the | | list. | +------------------------------------------+
Mini summary: len() returns the number of items in a list.
Definition: A tuple is like a list, but it cannot be changed. It is created with parentheses ( ).
Why it's important: Tuples are used when you want to store data that should not change (like a person's date of birth).
Simple explanation: A tuple is a "fixed" list â you can't add, remove, or change items.
Realâlife example: Your date of birth â it never changes.
School example: Your school ID number â it stays the same.
Home example: Your home address â it doesn't change often.
Nigerian example: Your National ID number â it's permanent.
+------------------------------------------+ | Tuple Example | |------------------------------------------+ | my_tuple = (1, 2, 3) | | print(my_tuple[0]) # Output: 1 | | | | # This will cause an error: | | # my_tuple[0] = 10 | | | | Tuples are unchangeable (immutable). | +------------------------------------------+
Mini summary: A tuple is like a list but cannot be changed after creation.
Definition: A dictionary stores data in keyâvalue pairs. Each key is associated with a value.
Why it's important: Dictionaries are great for mapping data â like names to phone numbers.
Simple explanation: It's like a phonebook: you look up a name (key) and get the number (value).
Realâlife example: A phonebook: "Chidi" â "08012345678".
School example: Student ID â Student Name.
Home example: Room name â Room number.
Nigerian example: Product name â Price.
+------------------------------------------+
| Dictionary Example |
|------------------------------------------+
| # Dictionary creation |
| phonebook = {"Chidi": "08012345678", |
| "Ada": "08098765432"} |
| |
| # Accessing a value |
| print(phonebook["Chidi"]) |
| # Output: 08012345678 |
| |
| # Adding a new keyâvalue pair |
| phonebook["Ngozi"] = "08055556666" |
+------------------------------------------+
Mini summary: A dictionary stores keyâvalue pairs. You access values by their keys.
Definition: You can add new keyâvalue pairs or change existing ones by assigning to a key. You can also use the update() method.
Why it's important: These methods let you modify dictionaries as needed.
Simple explanation: You can add new contacts to your phonebook or update existing numbers.
Realâlife example: Adding a new friend's number to your phonebook.
School example: Adding a new student to the school database.
Home example: Updating the room list.
Nigerian example: Updating the price of an item in a shop.
+------------------------------------------+
| Dictionary Methods |
|------------------------------------------+
| phonebook = {"Chidi": "08012345678"} |
| phonebook["Ada"] = "08098765432" |
| # Adds a new keyâvalue pair |
| |
| # Change a value |
| phonebook["Chidi"] = "08011112222" |
| |
| # Using update() |
| phonebook.update({"Ngozi": "08055556666"}) |
| |
| print(phonebook) |
| # Output: {'Chidi': '08011112222', |
| # 'Ada': '08098765432', |
| # 'Ngozi': '08055556666'} |
+------------------------------------------+
Mini summary: You can add or change keyâvalue pairs by assigning values to keys.
Definition: Let's build a simple phonebook program using a dictionary.
Why it's important: This shows how dictionaries are used in realâlife applications.
Simple explanation: The program stores names and numbers, and lets you look up numbers.
Realâlife example: A contact list on your phone.
School example: A student directory.
Home example: A family contact list.
Nigerian example: A market vendor list.
+------------------------------------------+
| Simple Phonebook Program |
|------------------------------------------+
| phonebook = {} |
| while True: |
| name = input("Enter name (or 'quit'): ") |
| if name == "quit": |
| break |
| number = input("Enter number: ") |
| phonebook[name] = number |
| print("Added!") |
| |
| # Look up a number |
| search = input("Search name: ") |
| if search in phonebook: |
| print(phonebook[search]) |
| else: |
| print("Not found.") |
| |
| This is a simple interactive phonebook!|
+------------------------------------------+
Mini summary: A phonebook program uses a dictionary to store names and numbers.
In this module, we learned about lists, tuples, and dictionaries â the data structures that help us organise information. We created lists and accessed items by index. We modified lists using methods like append, insert, remove, and pop. We sorted lists and looped through them. We learned about tuples (unchangeable lists) and dictionaries (keyâvalue pairs). We built a simple phonebook using a dictionary. Now you can store and organise data like a pro!
Concept 1: Lists store ordered data. You can access, add, remove, and modify items.
Concept 2: Tuples are unchangeable. Use them for fixed data.
Concept 3: Dictionaries store keyâvalue pairs. They are great for mapping data.
Concept 4: Loops are used to process lists. You can iterate through each item.
How to create and use a list:
How to create and use a dictionary:
We've seen many realâlife examples in the lessons, such as shopping lists, phonebooks, student lists, and inventories. These show how data structures are used in everyday life.
In Nigeria, lists are used in market inventories, school registers, and business records. Dictionaries are used in phonebooks, product catalogs, and customer databases. Understanding these structures helps build practical applications.
Imagine a robot that has a list of instructions: "Move forward, turn left, move forward." The robot follows the list step by step.
Another fun example: A game where you collect items. Your inventory is a list of collected items.
Key points: Emphasize the difference between lists, tuples, and dictionaries. Use practical examples like shopping lists and phonebooks. Practice accessing, adding, and removing items. Show how loops are used with lists.
Activity idea: Have students create a list of their favourite foods and a dictionary of their friends' names and phone numbers.
Parents can help children understand data structures by pointing out lists and dictionaries in daily life â like shopping lists, phone contacts, and recipe books. Ask them to think about how data is organised.
Did you know that you can have lists inside lists? These are called nested lists.
Did you know that dictionaries can have any type of value â even lists?
+------------------------------------------+ | List Indexing Diagram | |------------------------------------------+ | +---------+---------+---------+ | | | apple | banana | orange | | | +---------+---------+---------+ | | Index 0 1 2 | | | | fruits[0] â "apple" | | fruits[1] â "banana" | | fruits[2] â "orange" | +------------------------------------------+ +------------------------------------------+ | Dictionary Diagram | |------------------------------------------+ | +-------------+--------------------+ | | | Key | Value | | | +-------------+--------------------+ | | | "Chidi" | "08012345678" | | | +-------------+--------------------+ | | | "Ada" | "08098765432" | | | +-------------+--------------------+ | | | "Ngozi" | "08055556666" | | | +-------------+--------------------+ | | | | phonebook["Chidi"] â "08012345678" | +------------------------------------------+
| Feature | List | Tuple | Dictionary |
|---|---|---|---|
| Syntax | [ ] | ( ) | { } |
| Changeable | Yes | No | Yes |
| Ordered | Yes | Yes | No (Python 3.7+ order preserved) |
| Duplicates | Allowed | Allowed | Keys must be unique |
| Access | By index | By index | By key |
| Method | Purpose |
|---|---|
| append() | Adds item to end |
| insert() | Adds item at position |
| remove() | Deletes item by value |
| pop() | Deletes item by index |
| sort() | Orders list |
In this module, we learned about data structures â ways to organise and store data. We explored lists (ordered, changeable), tuples (ordered, unchangeable), and dictionaries (keyâvalue pairs). We practiced creating, accessing, and modifying lists using methods like append, insert, remove, and pop. We sorted lists and looped through them. We learned how to use dictionaries to map keys to values. You can now store and organise data efficiently, which is a crucial skill for any programmer.
Match the term with its description.
| Term | Description |
|---|---|
| List | a) Keyâvalue pairs |
| Tuple | b) Ordered, changeable |
| Dictionary | c) Ordered, unchangeable |
| append() | d) Adds to the end |
| pop() | e) Removes by index |
Answers: List â b, Tuple â c, Dictionary â a, append() â d, pop() â e
Scenario 1: You are building a contact list for your friends. What data structure would you use and why?
Scenario 2: You need to store the names of students and their grades. What data structure would you use and why?
"Market Inventory" â In groups of 4, create a program that uses a dictionary to store items and their prices. Allow users to add, remove, and view items. Present your program to the class.
Create a list of your top 5 movies. Then write a program that prints each movie on a new line using a loop.
"Simple Phonebook App" â Build a phonebook program that allows users to add, search, and delete contacts. Use a dictionary to store the data.
Write a program that stores the names and scores of 5 students in a dictionary. Print each student's name and score on a new line.
"ToâDo List Manager" â Build a toâdo list program that uses a list to store tasks. Allow users to add, view, and mark tasks as done. Use loops and list methods.
In Module 8, we will explore Functions â Reusing Code. You will learn how to write reusable blocks of code, use parameters, and return values. You will be able to write cleaner and more organised programs. Get ready to level up your coding skills!
Module Introduction
Welcome back, coders! In Module 7, we learned how to organise data using lists and dictionaries. Now we are going to learn how to organise our code using functions. A function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, you can write a function once and call it whenever you need it. Think of it like a recipe: once you know how to make a cake, you can use that recipe many times. In this module, we will learn how to define functions, pass data to them (parameters), get results back (return values), and use them to make our code cleaner and more organised. Let's start building functions!
Chidi is 11 years old. He loves to cook. He learns a recipe for jollof rice from his grandmother. He writes it down: "Fry onions, add tomatoes, add rice, add water, cook for 20 minutes." Every time he wants to make jollof rice, he follows the same recipe. He doesn't need to invent it again â he just uses the recipe. In coding, a function is like a recipe. You write the instructions once, and you can use them over and over. Chidi also learns to make a cake and writes a recipe for that too. Now he has a collection of recipes. He can call them whenever he wants. Functions work the same way â they make your code reusable and organised!
Definition: A function is a block of code that performs a specific task. It can be used again and again by calling its name.
Why it's important: Functions make code shorter, easier to read, and reusable. You write once, use many times.
Simple explanation: A function is like a recipe â you write the instructions once, and you can use them whenever you need to.
Realâlife example: A recipe for baking a cake â you use it many times.
School example: A formula in maths â you use it for different problems.
Home example: A chore routine â you follow the same steps every week.
Nigerian example: A recipe for making jollof rice â you can use it every time.
+------------------------------------------+
| What is a Function? |
|------------------------------------------+
| def greet(): |
| print("Hello!") |
| |
| # Call the function |
| greet() # Output: Hello! |
| greet() # Output: Hello! |
| greet() # Output: Hello! |
| |
| Write once, use many times! |
+------------------------------------------+
Mini summary: A function is a reusable block of code. You define it once and call it whenever you need it.
Definition: To define a function, use the def keyword, followed by the function name and parentheses ( ). Then add a colon and indent the code.
Why it's important: Defining a function creates a new tool that you can use in your program.
Simple explanation: You are creating a new command that the computer can understand.
Realâlife example: Teaching someone a new word â they can now use it.
School example: Learning a new formula â you can now use it.
Home example: Creating a new chore routine.
Nigerian example: Learning a new local recipe.
+------------------------------------------+
| Defining a Function |
|------------------------------------------+
| def say_hello(): |
| print("Hello, World!") |
| |
| # The function is defined, but not yet |
| # executed. |
| # To execute it, you must call it. |
+------------------------------------------+
Mini summary: Use def to define a function. Indent the code that belongs to the function.
Definition: To call a function, use its name followed by parentheses ( ). This runs the code inside the function.
Why it's important: Calling a function is how you actually use the function you defined.
Simple explanation: You call someone by their name to get their attention â you call a function by its name to run it.
Realâlife example: Saying "Siri" to wake up your phone.
School example: Calling a student's name in class.
Home example: Calling a pet by its name.
Nigerian example: Calling a market vendor by name.
+------------------------------------------+
| Calling a Function |
|------------------------------------------+
| def say_hello(): |
| print("Hello!") |
| |
| # Call the function |
| say_hello() # Output: Hello! |
| say_hello() # Output: Hello! |
| say_hello() # Output: Hello! |
| |
| You can call it as many times as you |
| want. |
+------------------------------------------+
Mini summary: Call a function by its name followed by (). This runs the code inside.
Definition: Parameters are variables that you put inside the parentheses when defining a function. They allow you to pass data into the function.
Why it's important: Parameters make functions flexible. You can use the same function with different values.
Simple explanation: Like a recipe that says "add 2 cups of flour" â you can change the amount if you need to.
Realâlife example: A recipe for soup that lets you change the ingredients.
School example: A formula that lets you use different numbers.
Home example: A chore list that lets you change the tasks.
Nigerian example: A recipe that lets you adjust the spice level.
+------------------------------------------+
| Parameters Example |
|------------------------------------------+
| def greet(name): |
| print("Hello, " + name + "!") |
| |
| # Call with different arguments |
| greet("Chidi") # Output: Hello, Chidi! |
| greet("Ada") # Output: Hello, Ada! |
| greet("Ngozi") # Output: Hello, Ngozi! |
| |
| The parameter "name" changes each time. |
+------------------------------------------+
Mini summary: Parameters let you pass data into a function. They make functions flexible.
Definition: You can have multiple parameters in a function, separated by commas.
Why it's important: Multiple parameters let you pass more data, making functions more powerful.
Simple explanation: A recipe might need many ingredients â like flour, sugar, and eggs.
Realâlife example: A recipe that takes several ingredients.
School example: A formula with multiple variables.
Home example: A shopping list with many items.
Nigerian example: A dish that needs many spices.
+------------------------------------------+ | Multiple Parameters | |------------------------------------------+ | def add(a, b): | | result = a + b | | print(result) | | | | add(5, 3) # Output: 8 | | add(10, 20) # Output: 30 | | add(2.5, 4.5) # Output: 7.0 | | | | The function takes two numbers and | | adds them. | +------------------------------------------+
Mini summary: You can have multiple parameters in a function, separated by commas.
Definition: The return statement is used to send a value back from the function to the place where it was called.
Why it's important: return lets you get a result from a function to use elsewhere in your code.
Simple explanation: It's like asking a chef for the dish â they give it to you.
Realâlife example: A cashier gives you change after you pay.
School example: A teacher gives you your grade.
Home example: A calculator gives you the answer.
Nigerian example: A market woman gives you your change.
+------------------------------------------+ | Return Value Example | |------------------------------------------+ | def add(a, b): | | return a + b | | | | result = add(5, 3) | | print(result) # Output: 8 | | | | The function returns the sum, which | | is stored in the variable "result". | +------------------------------------------+
Mini summary: return sends a value back from a function. It lets you capture the result.
Definition: Functions help you avoid repeating code, make programs easier to read, and allow you to break big problems into smaller pieces.
Why it's important: Writing clean, organised code is essential for bigger projects.
Simple explanation: Functions help you organise your code like a neatly arranged toolbox.
Realâlife example: A chef uses different recipes for different dishes.
School example: You have different notebooks for different subjects.
Home example: You have different shelves for different items.
Nigerian example: A market has different sections for different goods.
+------------------------------------------+ | Why Use Functions? | |------------------------------------------+ | 1. Reuse code â write once, use many | | times. | | 2. Organise code â break into smaller | | pieces. | | 3. Easy to read â clear names tell | | what the function does. | | 4. Easy to test â test each function | | separately. | +------------------------------------------+
Mini summary: Functions make code reusable, organised, and easy to read.
Definition: Scope refers to where a variable can be accessed. Variables defined inside a function are local (only inside that function). Variables defined outside are global (accessible everywhere).
Why it's important: Understanding scope prevents errors and helps you manage variables correctly.
Simple explanation: A local variable is like a secret inside a room â only people in that room can see it.
Realâlife example: A secret family recipe â only family members know it.
School example: A class assignment â only that class works on it.
Home example: A room â only people in that room can see what's in it.
Nigerian example: A village secret â only elders know it.
+------------------------------------------+ | Scope Example | |------------------------------------------+ | # Global variable | | name = "Chidi" | | | | def my_function(): | | # Local variable | | city = "Lagos" | | print(name) # Can access global | | print(city) # Can access local | | | | my_function() | | print(name) # Works (global) | | print(city) # Error! (local) | | | | Local variables are only available | | inside the function. | +------------------------------------------+
Mini summary: Local variables exist only inside functions; global variables exist everywhere.
Definition: Python has many builtâin functions that you can use right away, like print(), input(), len(), and type().
Why it's important: They save you time because you don't have to write them yourself.
Simple explanation: It's like having preâmade tools in a toolbox.
Realâlife example: A can opener â you don't need to build one.
School example: A calculator â it's ready to use.
Home example: A microwave â it's ready to use.
Nigerian example: A grinding machine â it's ready to use.
+------------------------------------------+
| Builtâin Functions |
|------------------------------------------+
| # print() â outputs to screen |
| print("Hello") |
| |
| # input() â gets user input |
| name = input("Enter name: ") |
| |
| # len() â returns length of a list |
| items = [1, 2, 3] |
| print(len(items)) # Output: 3 |
| |
| # type() â returns the data type |
| print(type(10)) # Output: |
+------------------------------------------+
Mini summary: Builtâin functions are ready to use. They save you time and effort.
Definition: Let's build a function that performs a calculation and returns the result.
Why it's important: This shows how to combine parameters, return values, and logic in a function.
Simple explanation: We will create a function that adds two numbers.
Realâlife example: A simple calculator.
School example: A maths formula.
Home example: A tool for budgeting.
Nigerian example: A market calculator.
+------------------------------------------+ | Calculator Function | |------------------------------------------+ | def add(a, b): | | return a + b | | | | def subtract(a, b): | | return a - b | | | | def multiply(a, b): | | return a * b | | | | def divide(a, b): | | if b != 0: | | return a / b | | else: | | return "Cannot divide by zero" | | | | # Usage: | | print(add(10, 5)) # 15 | | print(subtract(10, 5)) # 5 | | print(multiply(10, 5)) # 50 | | print(divide(10, 5)) # 2.0 | +------------------------------------------+
Mini summary: A calculator function uses parameters, logic, and return values to perform calculations.
In this module, we learned about functions â reusable blocks of code. We defined functions using def, and called them by name. We passed data using parameters and got results using return. We learned about variable scope and saw examples of builtâin functions. You can now write clean, reusable, and organised code using functions. This is a major step in your coding journey!
Concept 1: Functions make code reusable. Write once, use many times.
Concept 2: Parameters pass data into functions. They make functions flexible.
Concept 3: Return values get results out of functions. They let you use the result.
Concept 4: Scope determines where variables are visible. Local variables are inside functions; global variables are everywhere.
How to define and call a function:
How to use parameters and return:
We've seen many realâlife examples in the lessons, such as recipes, formulas, and calculators. These show how functions are used in everyday life.
In Nigeria, functions are used in cooking recipes, market calculations, and local businesses. Understanding functions helps build practical applications for realâworld problems.
Imagine a robot that dances. You write a function called "dance()" and every time you call it, the robot dances. You can call it many times!
Another fun example: A function called "bark()" that prints "Woof!". You can use it to make a virtual dog bark.
Key points: Emphasize the concept of "write once, use many times". Use examples like recipes and formulas. Practice defining and calling functions with different parameters. Show the difference between local and global variables.
Activity idea: Have students write a function that calculates the area of a rectangle and then use it in a program.
Parents can help children understand functions by comparing them to recipes and formulas. Ask: "What is a recipe? How is it like a function?" Encourage them to think of everyday tasks that can be turned into functions.
Did you know that you can pass a function as an argument to another function? That's called a higherâorder function.
Did you know that functions can call other functions? That's called function composition.
+------------------------------------------+ | Function Flowchart | |------------------------------------------+ | +-------+ | | | Start | | | +---+---+ | | | | | v | | +-------+ | | | Define| | | | Function| | | +---+---+ | | | | | v | | +-------+ | | | Call | | | | Function| | | +---+---+ | | | | | v | | +-------+ | | | Execute| | | | Code | | | +---+---+ | | | | | v | | +-------+ | | | Return| | | | Result| | | +---+---+ | | | | | v | | +-------+ | | | End | | | +-------+ | +------------------------------------------+
| Concept | Local Variable | Global Variable |
|---|---|---|
| Scope | Inside function only | Everywhere in the program |
| Access | Only inside function | Accessible inside and outside |
| Lifetime | Exists while function runs | Exists throughout the program |
| Function Part | Purpose |
|---|---|
| def | Defines the function |
| Parameters | Receive data |
| return | Send data back |
| Call | Execute the function |
In this module, we learned about functions â the building blocks of reusable code. We defined functions using def, called them, passed data with parameters, and returned results. We explored variable scope and saw the difference between local and global variables. We also looked at builtâin functions and created our own. You can now write clean, organised, and reusable code. This is a crucial skill for any programmer!
Match the term with its description.
| Term | Description |
|---|---|
| def | a) Sends a value back |
| Parameter | b) Keyword to define a function |
| Return | c) Receives data in a function |
| Call | d) Run a function |
| Local variable | e) Variable inside a function |
Answers: def â b, Parameter â c, Return â a, Call â d, Local variable â e
Scenario 1: You want to write a program that calculates the area of a rectangle multiple times. What would you use to avoid rewriting the calculation each time?
Scenario 2: You have a program that prints a welcome message to users. You want to reuse the message in many places. How would you do it?
"Function Library" â In groups of 4, create a "library" of functions that do different tasks: add, subtract, multiply, divide, and greet. Each person writes one function. Combine them into a single program and test them.
Write a function called square that takes a number and returns its square. Then write a program that uses this function to print the squares of numbers 1 to 5.
"FunctionâPowered Calculator" â Build a calculator program that uses separate functions for addition, subtraction, multiplication, and division. The user should choose an operation and two numbers, and the program should call the correct function.
Write a function that checks if a number is even or odd. The function should take a number as a parameter and return True if even, False if odd.
"Temperature Converter Functions" â Write two functions: one that converts Celsius to Fahrenheit, and another that converts Fahrenheit to Celsius. Then write a program that uses these functions.
In Module 9, we will explore Debugging and ProblemâSolving. You will learn how to find and fix errors in your code, use debugging tools, and develop strategies for solving coding problems. You will become a more confident and independent coder!
Module Introduction
Welcome back, coders! In Module 8, we learned how to write reusable code with functions. Now we are going to learn one of the most important skills a programmer can have â debugging and problem-solving. Every programmer, no matter how experienced, makes mistakes. That's normal! The skill is not about never making mistakes â it's about knowing how to find and fix them quickly. Think of yourself as a detective. When your code doesn't work, you look for clues to find the bug. In this module, we will learn about the different types of errors (syntax, runtime, logic), how to read error messages, how to use print statements to debug, and how to develop a problem-solving mindset. By the end, you will be confident in tackling any coding problem. Let's become coding detectives!
Ngozi is 12 years old. She wrote a program to calculate the total price of items, but the answer was always wrong. She was frustrated. Her brother, who is a programmer, said: "You are a detective now. Don't get angry â get curious." He helped her look at the error message. It said "TypeError: can't multiply sequence by non-int". Ngozi realised she had forgotten to convert a string to a number. She fixed it, and the program worked. Ngozi learned that debugging is like solving a puzzle. Every bug is a clue. She became a great debugger. Now, when her code doesn't work, she calmly looks for clues and fixes the problem. You can be a coding detective too!
Definition: Debugging is the process of finding and fixing errors (called "bugs") in your code.
Why it's important: All programs have bugs. Debugging is how we make them work correctly.
Simple explanation: Debugging is like being a detective. You look for clues to find what's wrong.
Realâlife example: When a recipe doesn't work, you check if you missed an ingredient.
School example: When a maths problem doesn't work, you check your steps.
Home example: When a light doesn't turn on, you check the bulb.
Nigerian example: When a market seller gives you the wrong change, you check the calculation.
+------------------------------------------+ | What is Debugging? | |------------------------------------------+ | +-------+ | | | Code | â Error â Bug | | +-------+ | | | | | v | | +-------+ | | | Find | â Debug â Fix â Works! | | | Error | | | +-------+ | | | | Debugging is finding and fixing errors. | +------------------------------------------+
Mini summary: Debugging is the process of finding and fixing errors in your code. It's a normal part of coding.
Definition: A syntax error is a mistake in the grammar or rules of the programming language. The computer can't understand what you wrote.
Why it's important: Syntax errors are the most common mistakes. They are usually easy to fix.
Simple explanation: It's like writing "I go to school" instead of "I go to school." â you missed a word.
Realâlife example: Forgetting a period at the end of a sentence.
School example: Spelling a word wrong.
Home example: Forgetting to add sugar to a recipe.
Nigerian example: Writing "Naira" as "Nia" â it's a different thing!
+------------------------------------------+
| Syntax Error Example |
|------------------------------------------+
| # Missing colon |
| if age > 18 |
| print("Adult") |
| |
| # Correct version: |
| if age > 18: |
| print("Adult") |
| |
| The computer says: "SyntaxError: invalid syntax" |
| It expects a colon. |
+------------------------------------------+
Mini summary: Syntax errors are mistakes in grammar. The computer cannot understand your code.
Definition: A runtime error occurs when the computer is running the code and something unexpected happens (like dividing by zero).
Why it's important: Runtime errors can crash your program if not handled.
Simple explanation: It's like driving a car and suddenly the engine stops â something went wrong while it was running.
Realâlife example: A calculator that tries to divide by zero.
School example: A program that tries to open a file that doesn't exist.
Home example: A toaster that keeps heating because the timer is broken.
Nigerian example: A generator that stops because of a fuel problem.
+------------------------------------------+
| Runtime Error Example |
|------------------------------------------+
| # Division by zero |
| x = 10 / 0 |
| |
| # Correct version: |
| # Check if denominator is zero |
| if denominator != 0: |
| x = 10 / denominator |
| else: |
| print("Cannot divide by zero") |
| |
| Runtime error: "ZeroDivisionError" |
+------------------------------------------+
Mini summary: Runtime errors happen while the program is running. They are often caused by unexpected user input or other issues.
Definition: A logic error is a mistake in the program's logic. The program runs without crashing, but it gives the wrong result.
Why it's important: Logic errors are the hardest to find because the computer doesn't give an error message.
Simple explanation: It's like following a recipe but adding salt instead of sugar â the cake looks right but tastes wrong.
Realâlife example: A calculator that adds when it should subtract.
School example: A formula that multiplies when it should divide.
Home example: Putting the wrong ingredient in a recipe.
Nigerian example: A trader who calculates the total wrong.
+------------------------------------------+ | Logic Error Example | |------------------------------------------+ | # This program should add two numbers | | # But it subtracts instead | | result = a - b # Wrong logic! | | | | # Correct version: | | result = a + b | | | | The program runs, but the answer is | | wrong. No error message is shown! | +------------------------------------------+
Mini summary: Logic errors don't crash the program â they just give the wrong result. They are the hardest to find.
Definition: Error messages tell you what went wrong and where. They are your best friend when debugging.
Why it's important: Learning to read error messages saves you time and frustration.
Simple explanation: It's like a teacher marking your test â they point out where you made a mistake.
Realâlife example: A GPS that says "recalculating" when you make a wrong turn.
School example: A teacher who circles a misspelled word.
Home example: A washing machine that beeps when it's unbalanced.
Nigerian example: A POS machine that shows "insufficient funds".
+------------------------------------------+
| Reading Error Messages |
|------------------------------------------+
| Example: |
| File "main.py", line 5 |
| print("Hello) |
| ^ |
| SyntaxError: unterminated string literal |
| |
| This tells you: |
| - The error is in file "main.py" |
| - On line 5 |
| - You forgot a closing quote |
| |
| The error message gives you clues! |
+------------------------------------------+
Mini summary: Error messages give you important clues about what went wrong and where. Always read them carefully.
Definition: You can use print() statements to show the values of variables at different points in your program. This helps you see what your code is doing.
Why it's important: print() is a simple but powerful debugging tool. It helps you understand the flow of your program.
Simple explanation: It's like leaving breadcrumbs to see where you went.
Realâlife example: A detective leaving markers to track their path.
School example: A teacher checking students' work step by step.
Home example: Following a recipe and checking each step.
Nigerian example: A trader checking the total after each addition.
+------------------------------------------+
| Using print() for Debugging |
|------------------------------------------+
| # Debugging a calculation |
| a = 10 |
| b = 5 |
| print("a =", a) # Check value |
| print("b =", b) # Check value |
| result = a + b |
| print("result =", result) # Check result|
| |
| # If result is wrong, you can see the |
| # values of a and b before calculation. |
+------------------------------------------+
Mini summary: print() lets you see what your program is doing at each step. It's a simple and effective debugging tool.
Definition: A debugger is a tool that lets you run your program step by step, pause at certain lines, and inspect variables. Many coding environments have a builtâin debugger.
Why it's important: A debugger gives you more control and information than print() statements.
Simple explanation: It's like being able to pause a movie and look at each frame to see what's happening.
Realâlife example: A video player that lets you pause and go frame by frame.
School example: A microscope that lets you see tiny details.
Home example: A magnifying glass to look at small print.
Nigerian example: A magnifying glass for examining small details.
+------------------------------------------+ | Using a Debugger | |------------------------------------------+ | In VS Code, PyCharm, or online editors: | | 1. Set a breakpoint (click on the line) | | 2. Run the program in debug mode | | 3. The program pauses at the breakpoint | | 4. Inspect variables and step through | | the code | | 5. See exactly what happens step by step | | | | Debuggers are powerful tools! | +------------------------------------------+
Mini summary: A debugger lets you run your code step by step and inspect variables. It's a powerful tool.
Definition: Some mistakes are very common in coding. Learning them helps you avoid them.
Why it's important: Knowing common mistakes saves you time and frustration.
Simple explanation: If you know where people usually slip, you can watch your step.
Realâlife example: In a kitchen, people often burn onions â you can watch closely.
School example: Students often make mistakes in long division â you can doubleâcheck.
Home example: People often forget their keys â you can keep them in one place.
Nigerian example: People often forget their ATM cards â you can keep them in a safe place.
+------------------------------------------+ | Common Mistakes | |------------------------------------------+ | 1. Using '=' instead of '==' in conditions | | 2. Forgetting the colon (:) after if/for/while | | 3. Not indenting code correctly | | 4. Using the wrong variable name | | 5. Forgetting to convert input type | | 6. Offâbyâone errors in loops | | 7. Not handling division by zero | | 8. Using a variable before it's defined | +------------------------------------------+
Mini summary: Common mistakes include using '=' instead of '==', forgetting colons, and indentation issues.
Definition: Problem-solving is the process of finding a solution to a difficult or complex issue. It is a key skill for programmers.
Why it's important: Programming is fundamentally about solving problems. Good problemâsolvers are good programmers.
Simple explanation: It's like a puzzle â you look at it, think about it, and try different approaches.
Realâlife example: Figuring out how to fix a broken bike.
School example: Solving a challenging maths problem.
Home example: Planning a family trip.
Nigerian example: Figuring out how to start a business.
+------------------------------------------+ | Problem-Solving Strategies | |------------------------------------------+ | 1. Understand the problem. | | 2. Break it down into smaller pieces. | | 3. Try a simple solution first. | | 4. Test with small examples. | | 5. Use pseudocode or comments to plan. | | 6. Write code step by step. | | 7. Test frequently. | | 8. When stuck, take a break. | | 9. Ask for help. | | 10. Learn from mistakes. | +------------------------------------------+
Mini summary: Problem-solving strategies include understanding the problem, breaking it down, and testing frequently.
Definition: Rubber duck debugging is when you explain your code, line by line, to a rubber duck (or any object). The act of explaining often helps you find the bug.
Why it's important: It forces you to think clearly and step through your logic.
Simple explanation: You talk to a duck, and in doing so, you find the problem yourself.
Realâlife example: Explaining a problem to a friend and then finding the solution.
School example: Explaining your homework to a classmate.
Home example: Talking to yourself to solve a problem.
Nigerian example: Explaining a market issue to a friend.
+------------------------------------------+ | Rubber Duck Debugging | |------------------------------------------+ | 1. Place a rubber duck (or any object) | | on your desk. | | 2. Explain your code to the duck, line | | by line. | | 3. As you explain, you may find the bug. | | | | Why it works: | | Explaining forces you to think clearly | | about what each line does. | +------------------------------------------+
Mini summary: Rubber duck debugging is explaining your code to an object. It helps you find bugs by forcing you to think clearly.
Definition: When you are stuck, it's okay to ask for help. The key is to ask the right way â be clear about your problem.
Why it's important: Asking the right questions helps you get the right answers.
Simple explanation: It's like asking for directions â if you say "I'm lost," people can't help. If you say "I'm looking for the bank," they can.
Realâlife example: Asking a teacher for help with a specific problem.
School example: Asking your friend to explain a concept.
Home example: Asking a family member to help with a recipe.
Nigerian example: Asking a local expert about market prices.
+------------------------------------------+
| Asking for Help |
|------------------------------------------+
| Good: |
| "I'm trying to add two numbers, but |
| I get a TypeError. Here's my code: |
| num1 = input('Enter a number: ') |
| num2 = input('Enter a number: ') |
| result = num1 + num2 |
| I think I need to convert the input. |
| What should I do?" |
| |
| Bad: |
| "My code doesn't work. Help!" |
| |
| Be specific and show your code! |
+------------------------------------------+
Mini summary: When asking for help, be specific about the problem and show your code.
In this module, we learned about debugging and problem-solving. We discovered the three types of errors: syntax, runtime, and logic. We learned to read error messages and use print() to check values. We explored debugger tools, common mistakes, problem-solving strategies, and rubber duck debugging. We also learned how to ask for help effectively. You are now equipped to handle any coding challenge that comes your way!
Concept 1: Debugging is a normal part of coding. Everyone makes mistakes.
Concept 2: Read error messages carefully. They give you valuable clues.
Concept 3: Use print() to check values. It helps you see what's happening.
Concept 4: Break problems down. Solve them step by step.
How to debug a program:
We've seen many realâlife examples in the lessons, such as baking a cake, doing maths, and fixing a bike. These show how debugging and problem-solving are used in everyday life.
In Nigeria, debugging is used in building apps, fixing electronics, and solving everyday problems. The skills you learn here will help you in any technical or business field.
Imagine a robot that is supposed to say "Hello" but says "Goodbye" instead. You need to debug the robot's code to fix the message.
Another fun example: A game where your character won't jump. You debug the code to find the missing jump function.
Key points: Emphasize that debugging is not a sign of failure â it's a normal part of coding. Encourage students to read error messages carefully. Practice with examples of each error type. Show them how to use print() and debugger tools.
Activity idea: Provide code with preâwritten bugs and have students debug it.
Parents can help children by encouraging a growth mindset â mistakes are learning opportunities. Ask them to explain what they tried and what happened. Show them how to search for solutions online. Celebrate their debugging successes.
Did you know that the phrase "It's not a bug, it's a feature" is a common joke among programmers?
Did you know that some bugs are so complex they take weeks to find?
+------------------------------------------+ | Debugging Process | |------------------------------------------+ | +-------+ | | | Code | â Error | | +-------+ | | | | | v | | +-------+ | | | Read | â Error message | | | Error | | | +-------+ | | | | | v | | +-------+ | | | Find | â Locate the line | | | Line | | | +-------+ | | | | | v | | +-------+ | | | Check | â Check common issues | | | Code | | | +-------+ | | | | | v | | +-------+ | | | Fix | â Change code | | | Bug | | | +-------+ | | | | | v | | +-------+ | | | Test | â Run program again | | +-------+ | | | | | v | | +-------+ | | | Done | â Success! | | +-------+ | +------------------------------------------+
| Error Type | Description | Example |
|---|---|---|
| Syntax | Grammar mistake | Missing colon |
| Runtime | Happens during execution | Division by zero |
| Logic | Wrong result | Using '-' instead of '+' |
| Debugging Tool | Purpose |
|---|---|
| print() | Show variable values |
| Error messages | Clues about the error |
| Debugger | Step through code |
| Rubber duck | Explain code aloud |
In this module, we learned the essential skills of debugging and problem-solving. We discovered the three types of errors: syntax (grammar), runtime (execution), and logic (wrong result). We learned to read error messages, use print() to check values, and use debugger tools. We explored problem-solving strategies, rubber duck debugging, and how to ask for help. You are now equipped to face any coding challenge with confidence. Debugging is not a sign of failure â it's a sign that you are learning!
Match the term with its description.
| Term | Description |
|---|---|
| Syntax error | a) Wrong result |
| Runtime error | b) Grammar mistake |
| Logic error | c) Error while running |
| Debugger | d) Tool to step through code |
| print() | e) Shows variable values |
Answers: Syntax error â b, Runtime error â c, Logic error â a, Debugger â d, print() â e
Scenario 1: Your program crashes with a "ZeroDivisionError". What does this mean and how would you fix it?
Scenario 2: Your program runs without errors but gives the wrong answer. What type of error is this and how would you find it?
"Bug Hunt" â In groups of 4, you will be given a Python program with several bugs. Your task is to find and fix all the bugs. Use debugging strategies and tools. Each group presents their fixes.
Write a simple program that adds two numbers. Intentionally add a bug (like using '-' instead of '+'). Then debug it and fix it.
"Debugging Challenge" â Write a program with at least 3 bugs. Exchange programs with a classmate and debug each other's code. Write a report on the bugs you found and how you fixed them.
Write a program that asks for two numbers and divides them. Handle the case where the user enters zero as the second number.
"Calculator with Error Handling" â Build a calculator that handles errors. If the user enters a nonânumeric value, print a friendly error message. Use tryâexcept to handle errors gracefully.
In Module 10, we will build our Final Project â a complete program that uses everything we've learned. You will plan, design, and build a game or application from scratch. This is your chance to show off all your coding skills!
Module Introduction
Congratulations, coder! You have made it to the final module of the Fundamentals of Coding course. Over the past nine modules, you have learned about variables, data types, operators, control flow, loops, lists, dictionaries, functions, and debugging. You have all the tools you need to build something amazing. Now it's time to put everything together and build your own project. In this module, we will design and build a complete program â a Guessing Game where the user has to guess a secret number. You will plan the project, write pseudocode, create a flowchart, and then code it step by step. By the end, you will have a fully functional program that you can be proud of. Let's build something great!
Nkechi is 12 years old. She has learned a lot in her coding course. She is excited to build her own game. She decides to build a Number Guessing Game. She plans it out: the game will pick a secret number between 1 and 100. The user will have 10 attempts to guess it. The game will give hints: "Too high" or "Too low". If the user guesses correctly, they win. If they run out of attempts, they lose. Nkechi writes pseudocode and draws a flowchart. She then codes it step by step. She tests it and adds extra features â like keeping score and asking to play again. She is so proud of her game. She shows it to her family and they play it. Nkechi is now a real programmer! You can build your own game too.
Definition: A project is a program that you build from scratch. It solves a problem or provides entertainment.
Why it's important: Building a project shows that you can apply everything you've learned.
Simple explanation: A project is like building a house â you plan it, gather materials, and construct it step by step.
Realâlife example: Building a website or a game.
School example: A science fair project.
Home example: Building a piece of furniture.
Nigerian example: Starting a small business.
+------------------------------------------+ | Project Ideas | |------------------------------------------+ | - Number Guessing Game | | - Simple Calculator | | - Quiz Game | | - ToâDo List App | | - Mad Libs Story Generator | | - Rock, Paper, Scissors | | - Weather App | | - Password Generator | | | | Choose something that excites you! | +------------------------------------------+
Mini summary: Choose a project that you are excited about. It should be something you can build with the skills you have learned.
Definition: Planning is the process of thinking about what you want to build and how you will build it before you start coding.
Why it's important: Planning saves time and prevents confusion. It helps you stay organised.
Simple explanation: It's like drawing a map before a journey â you know where you are going.
Realâlife example: An architect draws a blueprint before building a house.
School example: An outline before writing an essay.
Home example: Making a shopping list before going to the market.
Nigerian example: A market woman plans what to buy before going to the market.
+------------------------------------------+ | Planning Steps | |------------------------------------------| | 1. What will the program do? | | 2. Who will use it? | | 3. What features will it have? | | 4. What data will it need? | | 5. What will the user experience be? | | 6. How will you test it? | +------------------------------------------+
Mini summary: Planning means thinking about what your program will do before you start writing code.
Definition: Pseudocode is a plan for your program written in plain English. It is not real code â it's a stepâbyâstep guide.
Why it's important: Pseudocode helps you organise your thoughts and plan your logic before coding.
Simple explanation: It's like a rough draft of your program.
Realâlife example: A recipe before cooking.
School example: An essay outline.
Home example: A toâdo list.
Nigerian example: A market list before shopping.
+------------------------------------------+ | Pseudocode for Guessing Game | |------------------------------------------| | 1. Generate a secret number between 1 | | and 100. | | 2. Set attempts = 0. | | 3. Set max_attempts = 10. | | 4. While attempts < max_attempts: | | Ask user for a guess. | | If guess == secret: | | Print "You win!" | | End game. | | Else if guess > secret: | | Print "Too high!" | | Else: | | Print "Too low!" | | attempts += 1. | | 5. If attempts == max_attempts: | | Print "You lose! The number was", | | secret. | +------------------------------------------+
Mini summary: Pseudocode is a plainâEnglish plan for your program. It helps you think before you code.
Definition: A flowchart is a visual diagram that shows the steps of your program using shapes and arrows.
Why it's important: A flowchart helps you see the flow of your program visually.
Simple explanation: It's like a map for your program.
Realâlife example: A map of a subway system.
School example: A diagram of the water cycle.
Home example: A family tree.
Nigerian example: A map of your local market.
+------------------------------------------+ | Flowchart for Guessing Game | |------------------------------------------+ | +----------+ | | | START | | | +----+-----+ | | | | | v | | +----+-----+ | | | Generate | | | | Secret | | | | Number | | | +----+-----+ | | | | | v | | +----+-----+ | | | attempts| | | | = 0 | | | +----+-----+ | | | | | v | | +----+-----+ | | | attempts <| | | | 10? | | | +----+-----+ | | | | | +---------+---------+ | | | | | | v v | | +-------+ +-----------+ | | | Ask | | Print | | | | guess | | "Lose" | | | +---+---+ +-----+-----+ | | | | | | v | | | +-------+ | | | | guess | | | | == | | | | secret? | | | | +---+---+ | | | | | | | +--------+ | | | | | | | v | | | +-------+ | | | | Print | | | | | "Win" | | | | +---+---+ | | | | | | | +----------+ | | | | | v | | +-------+ | | | END | | | +-------+ | +------------------------------------------+
Mini summary: A flowchart is a visual way to show the steps of your program.
Definition: The first step is to set up the basic structure of your program â import libraries, set up variables, and create the main loop.
Why it's important: A good structure makes it easier to build and debug.
Simple explanation: Like laying the foundation of a house.
Realâlife example: Preparing ingredients before cooking.
School example: Setting up your notebook for a project.
Home example: Clearing a desk before starting work.
Nigerian example: Setting up your shop for the day.
+------------------------------------------+
| Code Setup Example |
|------------------------------------------+
| import random |
| |
| # Variables |
| secret = random.randint(1, 100) |
| attempts = 0 |
| max_attempts = 10 |
| game_over = False |
| |
| print("Welcome to the Number Guessing Game!") |
| print("I'm thinking of a number between 1 and 100.") |
| print("You have", max_attempts, "attempts.") |
+------------------------------------------+
Mini summary: Set up the basic structure of your program before adding the main logic.
Definition: The main game loop is where the game runs. It repeats until the game is over.
Why it's important: The game loop handles all the interactions with the user.
Simple explanation: It's like the engine of a car â it keeps everything running.
Realâlife example: A restaurant taking orders repeatedly.
School example: A teacher asking questions repeatedly.
Home example: A washing machine cycle.
Nigerian example: A market seller serving customers repeatedly.
+------------------------------------------+
| Main Game Loop Example |
|------------------------------------------+
| while attempts < max_attempts: |
| guess = int(input("Enter your guess: ")) |
| attempts += 1 |
| if guess == secret: |
| print("You won! The number was", secret) |
| game_over = True |
| break |
| elif guess > secret: |
| print("Too high!") |
| else: |
| print("Too low!") |
| |
| # End of loop |
| if not game_over: |
| print("You lost! The number was", secret) |
+------------------------------------------+
Mini summary: The main game loop repeats the guessing process until the user wins or runs out of attempts.
Definition: Input validation checks that the user's input is valid (like a number between 1 and 100).
Why it's important: It prevents errors and makes the game userâfriendly.
Simple explanation: Like checking the ingredients before adding them to a recipe.
Realâlife example: Checking that a phone number has the right number of digits.
School example: Checking that a student has written their name correctly.
Home example: Checking that eggs are not cracked before using them.
Nigerian example: Checking that money is not counterfeit.
+------------------------------------------+
| Input Validation Example |
|------------------------------------------+
| while True: |
| try: |
| guess = int(input("Enter your guess: ")) |
| if 1 <= guess <= 100: |
| break |
| else: |
| print("Please enter a number between 1 and 100.") |
| except ValueError: |
| print("Please enter a valid number.") |
| |
| # The guess is now valid |
+------------------------------------------+
Mini summary: Input validation ensures the user enters valid data. It makes your program more robust.
Definition: Extra features make the game more fun and engaging.
Why it's important: They show that you can go beyond the basic requirements.
Simple explanation: Like adding toppings to a pizza.
Realâlife example: A game with levels.
School example: A project with extra credit.
Home example: Adding decorations to a room.
Nigerian example: Adding extra services to a business.
+------------------------------------------+ | Extra Features Ideas | |------------------------------------------+ | - Keep track of wins and losses. | | - Ask the user if they want to play | | again. | | - Give hints (e.g., odd/even). | | - Save high scores to a file. | | - Add levels (easy, medium, hard). | | - Add a timer. | | - Add a score multiplier. | +------------------------------------------+
Mini summary: Extra features make your program stand out and show off your skills.
Definition: Testing means running your program to find bugs. Debugging means fixing them.
Why it's important: Testing ensures your program works correctly.
Simple explanation: Like tasteâtesting a meal before serving it.
Realâlife example: Testâdriving a car before buying it.
School example: Reviewing your answers before submitting a test.
Home example: Checking the temperature of bath water.
Nigerian example: Counting money before leaving the market.
+------------------------------------------+ | Testing and Debugging | |------------------------------------------+ | 1. Run your program with different | | inputs. | | 2. Test the winning scenario. | | 3. Test the losing scenario. | | 4. Test invalid inputs. | | 5. Test edge cases (number 1, 100). | | 6. Use print() to check values. | | 7. Fix any bugs you find. | | 8. Test again. | +------------------------------------------+
Mini summary: Testing and debugging are essential to ensure your program works correctly.
Definition: The play again feature asks the user if they want to restart the game after it ends.
Why it's important: It makes the game more interactive and fun.
Simple explanation: Like watching a sequel to a movie.
Realâlife example: A restaurant asking if you want another serving.
School example: A teacher asking if you want another question.
Home example: A family member asking if you want more food.
Nigerian example: A market seller asking if you want more goods.
+------------------------------------------+
| Play Again Feature |
|------------------------------------------|
| while True: |
| # Game logic goes here |
| # ... |
| play_again = input("Play again? (y/n): ").lower() |
| if play_again != 'y': |
| break |
| # Reset game variables |
| secret = random.randint(1, 100) |
| attempts = 0 |
| |
| print("Thank you for playing!") |
+------------------------------------------+
Mini summary: The play again feature lets the user restart the game without running the program again.
Definition: The complete program is the final version of your game with all parts working together.
Why it's important: It shows that you can build a complete, working program.
Simple explanation: Like assembling all the pieces of a puzzle.
Realâlife example: A finished house.
School example: A complete essay.
Home example: A cooked meal.
Nigerian example: A successful business.
+------------------------------------------+
| Complete Program |
|------------------------------------------|
| import random |
| |
| def play_game(): |
| secret = random.randint(1, 100) |
| attempts = 0 |
| max_attempts = 10 |
| game_over = False |
| |
| print("I'm thinking of a number between 1 and 100.") |
| print("You have", max_attempts, "attempts.") |
| |
| while attempts < max_attempts: |
| try: |
| guess = int(input("Enter your guess: ")) |
| if guess < 1 or guess > 100: |
| print("Please enter a number between 1 and 100.") |
| continue |
| except ValueError: |
| print("Please enter a valid number.") |
| continue |
| |
| attempts += 1 |
| if guess == secret: |
| print("You won! The number was", secret) |
| game_over = True |
| break |
| elif guess > secret: |
| print("Too high!") |
| else: |
| print("Too low!") |
| |
| if not game_over: |
| print("You lost! The number was", secret) |
| |
| # Main loop |
| while True: |
| play_game() |
| play_again = input("Play again? (y/n): ").lower() |
| if play_again != 'y': |
| break |
| print("Thanks for playing!") |
+------------------------------------------+
Mini summary: The complete program combines all parts into a working game.
Definition: Presenting means showing your project to others and explaining how it works.
Why it's important: Sharing your work builds confidence and helps you learn from feedback.
Simple explanation: Like showing your art to family.
Realâlife example: A product launch.
School example: A class presentation.
Home example: Showing a photo album.
Nigerian example: A market seller showcasing their goods.
+------------------------------------------+ | Presentation Tips | |------------------------------------------+ | 1. Explain what your program does. | | 2. Show the code and explain key parts. | | 3. Run the program and demonstrate it. | | 4. Talk about challenges you faced. | | 5. Share what you learned. | | 6. Ask for feedback. | +------------------------------------------+
Mini summary: Presenting your project helps you celebrate your work and get feedback.
In this module, we planned, designed, and built a complete Number Guessing Game. We started by choosing a project and planning it with pseudocode and a flowchart. We coded the game step by step, added input validation, extra features, and a play again option. We tested and debugged our program. Finally, we presented our project. You have now built a complete program from scratch â a major achievement in your coding journey!
Concept 1: Planning is essential. Always plan before you code.
Concept 2: Build step by step. Start with the basics and add features later.
Concept 3: Test often. Debugging is easier when you test frequently.
Concept 4: Celebrate your work. You built something from scratch!
How to build a project:
We've seen many realâlife examples in the lessons, such as building a house, starting a business, and cooking a meal. These show how planning and building step by step works in many areas of life.
In Nigeria, planning is essential in business, farming, and daily life. Building a project is like starting a business â you plan, gather resources, build, and market your product.
Imagine you are building a LEGO castle. You don't just throw pieces together â you plan the design, find the right pieces, and build step by step. That's exactly how programming works!
Another fun example: Baking a cake. You need a recipe (pseudocode), follow steps (algorithm), and taste it along the way (testing).
Key points: Encourage students to choose a project they are passionate about. Emphasize the importance of planning. Allow time for testing and debugging. Celebrate their achievements.
Activity idea: Have students present their projects to the class and give feedback.
Parents can support children by encouraging them to plan before coding. Celebrate their successes and help them debug when they get stuck. Play their game and give constructive feedback.
Did you know that the world's first computer game was a tennis game on an oscilloscope?
Did you know that many games are built with Python using libraries like Pygame?
+------------------------------------------+ | Project Lifecycle | |------------------------------------------+ | +-------+ | | | Choose| | | +---+---+ | | | | | v | | +-------+ | | | Plan | | | +---+---+ | | | | | v | | +-------+ | | | Build | | | +---+---+ | | | | | v | | +-------+ | | | Test | | | +---+---+ | | | | | v | | +-------+ | | | Present| | | +-------+ | +------------------------------------------+
| Phase | Description | Tools |
|---|---|---|
| Plan | Think about what to build | Pseudocode, Flowchart |
| Build | Write the code | Python, IDE |
| Test | Run the code and find errors | print(), Debugger |
| Present | Show your work | Presentation, Demo |
In this final module, you built a complete program from start to finish. You chose a project, planned it with pseudocode and a flowchart, coded it step by step, added extra features, and tested it. You have now experienced the full software development lifecycle. You have all the skills you need to build any program you can imagine. This is just the beginning of your coding journey. Keep building, keep learning, and keep creating. You are now a coder!
Match the term with its description.
| Term | Description |
|---|---|
| Plan | a) Extra function in a program |
| Pseudocode | b) A visual diagram |
| Flowchart | c) Think before you code |
| Feature | d) A plainâEnglish plan |
| Debug | e) Find and fix errors |
Answers: Plan â c, Pseudocode â d, Flowchart â b, Feature â a, Debug â e
Scenario 1: You are building a quiz game. The game asks 5 multipleâchoice questions. The user scores points for each correct answer. How would you plan and build this game?
Scenario 2: You are building a toâdo list app. The app stores tasks and allows the user to add, delete, and mark tasks as done. How would you plan and build this app?
"Show and Tell" â In groups of 4, take turns presenting your project to the group. Explain how you built it, what challenges you faced, and what you learned. Give feedback to each other.
Write a reflection on your project. What did you build? What did you learn? What challenges did you face? What would you do differently next time?
"Choose Your Own Project" â Choose a project idea (from the list or your own) and build it from start to finish. Follow the planning, building, testing, and presenting steps.
Build a program that asks the user to guess a number. Add input validation and a play again feature. Test it thoroughly and submit the code.
"Multi-Level Game" â Extend the guessing game to have levels. Level 1: numbers 1-10, Level 2: numbers 1-50, Level 3: numbers 1-100. The player advances to the next level after winning. Build and test it.
Congratulations! You have completed the Fundamentals of Coding course. You have built a complete program from scratch. You are now ready to take your skills to the next level. Here are some ideas for what to learn next:
Keep learning, keep building, and keep creating. The world needs your ideas and your code. You've got this!
You have successfully completed the Fundamentals of Coding course! You have learned about:
You are now equipped with the foundational skills to write, debug, and build programs. This is just the beginning of your coding journey. Keep exploring, keep creating, and remember â you are a coder!