โ† Python For Automation ยท Lesson 14 of 14

Module Twelve

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

Course Outline

Course Outline ยท Python for Automation

๐Ÿ Python for Automation
A beginner-friendly course outline

๐Ÿ“Œ Course purpose: This course teaches you how to use Python to automate boring, repetitive tasks. You will learn to write scripts that read and write files, process data, send emails, scrape websites, and more. No prior programming experience is needed โ€” just curiosity and a willingness to learn.

๐Ÿ“‹ Course at a glance

AspectDetails
Target audienceComplete beginners, office workers, IT professionals, and anyone who wants to automate daily tasks
PrerequisitesBasic computer skills (file management, using a browser) โ€” no coding experience needed
Delivery modeSelf-paced with hands-on projects and exercises
Total duration~15โ€“20 hours (over 4โ€“6 weeks)
CertificationCertificate of Completion with a project portfolio
Main toolsPython 3, VS Code (or any text editor), command line / terminal

๐ŸŽฏ Course learning outcomes

By the end of this course, you will be able to:

  • โœ… Write and run Python scripts from scratch.
  • โœ… Automate file and folder operations (rename, move, delete, organise).
  • โœ… Read, write, and update Excel, CSV, and text files.
  • โœ… Send automated emails and notifications.
  • โœ… Extract data from websites (web scraping).
  • โœ… Schedule scripts to run automatically.
  • โœ… Create your own automation projects to save time.

๐Ÿ“š Module outline (12 modules)

ModuleTitle & focusKey activities & takeaways
1 Welcome to Python
Getting started with programming
Install Python, set up your code editor, run your first "Hello, World!" script. Understand what Python is and why it's great for automation.
๐Ÿ”น Task: Write and run your first Python program.
2 Python basics
Variables, data types, and simple operations
Learn about numbers, strings, booleans, lists, and dictionaries. Perform basic math and string operations.
๐Ÿ”น Task: Create a script that stores and displays information about yourself.
3 Control flow
Making decisions in code
Use if, else, and elif to make decisions. Use for and while loops to repeat actions.
๐Ÿ”น Task: Write a script that checks if a number is even or odd and prints a message.
4 Functions
Write reusable code
Create your own functions to organise code and avoid repetition. Understand parameters and return values.
๐Ÿ”น Task: Create a function that greets a user by name and a function that adds two numbers.
5 Working with files
Read, write, and manage files
Open, read, write, and append text files. Use Python to create and delete files and folders.
๐Ÿ”น Task: Write a script that reads a list of names from a file and creates a new file with a greeting for each name.
6 Automating file organisation
Clean up your folders
Use the os and shutil modules to move, copy, rename, and delete files automatically. Organise files by extension, date, or name.
๐Ÿ”น Task: Write a script that organises all files in your Downloads folder into subfolders by file type.
7 Working with CSV and Excel files
Automate data entry and reports
Use csv and openpyxl to read and write spreadsheets. Automate data processing and report generation.
๐Ÿ”น Task: Write a script that reads a CSV file, calculates totals, and writes a summary report to a new Excel file.
8 Automating emails and notifications
Send messages programmatically
Use SMTP to send automated emails. Send alerts and reports to yourself or your team.
๐Ÿ”น Task: Write a script that sends a daily summary email to your inbox.
9 Web scraping with Python
Extract data from websites
Use requests and BeautifulSoup to scrape information from web pages. Automate data collection from the web.
๐Ÿ”น Task: Write a script that scrapes the latest headlines from a news website and saves them to a file.
10 Automating browser tasks
Control your browser with Selenium
Use Selenium to automate interactions with web pages โ€” clicking buttons, filling forms, and navigating sites.
๐Ÿ”น Task: Write a script that logs into your email account and sends a test message.
11 Scheduling and running scripts
Make your scripts run automatically
Learn how to schedule Python scripts to run at specific times using Task Scheduler (Windows) or cron (macOS/Linux).
๐Ÿ”น Task: Schedule your automated email script to run every morning at 8am.
12 Putting it all together
Build your own automation project
Plan, design, and build a complete automation project of your choice. Showcase your skills and share with the community.
๐Ÿ”น Task: Create a final project that automates a real-world task in your work or personal life.

๐Ÿ“ Learning activities & assessment

ComponentDescription
Practical exercises After each module, complete a hands-on coding task to apply what you learned.
Mini-projects Each module ends with a small project that builds toward your final portfolio.
Final project Design and build an end-to-end automation project that solves a real problem.
Peer review Share your code and get feedback from fellow learners in the community.

๐Ÿ› ๏ธ Tools & resources provided

  • ๐Ÿ“˜ Code examples โ€” ready-to-run scripts for each topic.
  • ๐Ÿ“„ Cheatsheets โ€” quick reference for Python syntax and modules.
  • ๐ŸŽฅ Video tutorials โ€” walkthroughs for key concepts.
  • ๐Ÿ“‹ Project templates โ€” starter code for each project.
  • ๐Ÿ’ฌ Community forum โ€” ask questions and share ideas with other learners.

โณ Suggested timeline

WeekModules to coverEstimated time
Week 1Modules 1, 2, 33โ€“4 hours
Week 2Modules 4, 5, 64โ€“5 hours
Week 3Modules 7, 8, 94โ€“5 hours
Week 4Modules 10, 11, 124โ€“6 hours

๐Ÿ’ก What you will build (sample projects)

  • ๐Ÿ“ File Organiser: Automatically sort your Downloads folder into subfolders by file type.
  • ๐Ÿ“Š Report Generator: Read data from a CSV, calculate summaries, and create an Excel report.
  • ๐Ÿ“ง Email Sender: Send automated emails to a list of recipients with personalised content.
  • ๐ŸŒ Web Scraper: Extract product prices from an e-commerce website and save them to a spreadsheet.
  • ๐Ÿ“… Daily Planner: Create a script that compiles your daily tasks and sends you a morning reminder.

โ“ Frequently asked questions

QuestionAnswer
Do I need to know programming? No! This course is designed for complete beginners. We start from zero.
What computer do I need? Windows, macOS, or Linux โ€” any computer that can run Python 3.
How long does it take? About 15โ€“20 hours total. You can go at your own pace.
Will I learn to build real automation scripts? Yes! Every module includes hands-on tasks, and the final project is a complete automation script.
Is there a certificate? Yes, you will receive a Certificate of Completion after finishing the course.

๐ŸŽ“ Certificate & next steps

Upon completion of all modules and the final project, you will receive a Certificate of Completion and a digital badge. You can use your project portfolio to showcase your skills to employers or colleagues.

After this course, you can move on to advanced Python topics, web development, data science, or machine learning โ€” or just keep automating!


2

Phyton For Automation Video

3

Module One

Module One ยท Python for Automation

๐Ÿ Module One ยท Welcome to Python!


๐Ÿ“– Module Introduction

Hello, future automation expert! Welcome to the very first module of "Python for Automation". This is a very special course because it will teach you how to talk to computers using Python. Python is a programming language โ€” a way to give instructions to a computer.

In this module, we will start from the very beginning. We will learn what Python is, how to install it, and how to write your very first program. You don't need to know anything about coding. We will go slowly and use lots of examples. By the end of this module, you will have written your first Python program and will be ready to learn more!

๐ŸŽฏ Learning Objectives

  • Understand what Python is and why it is useful for automation.
  • Install Python on your computer.
  • Write and run your very first Python program.
  • Understand basic programming concepts like the "print" command.
  • Feel excited and confident to learn more.

๐Ÿ“š Warm-up Story ยท Aisha's Big Idea

Aisha is a teacher in Kano. Every day, she spent 2 hours organising student grades and sending emails to parents. It was boring and tiring. One day, her friend told her about Python. "Python can do that boring work for you," her friend said.

Aisha was curious. She opened her laptop and typed: print("Hello, world!"). Something magical happened โ€” the computer said "Hello, world!" back to her. She was amazed! She learned more and more. Now Python organises her grades, sends her emails, and even reminds her about meetings. Aisha saved hours every week. She became a happy teacher.

This story shows what Python can do for you. Let's learn how!

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is Python?

Definition: Python is a programming language. A programming language is a way to give instructions to a computer.

Why important: Python is one of the easiest languages to learn. It is also very powerful.

Simple explanation: Imagine you are telling a robot what to do. You need to use words the robot understands. Python is the language we use to tell the computer what to do.

Real-life example: When you send a text message, you use words. When you tell a computer what to do, you use Python.

School example: A teacher uses Python to send emails to all parents at once.

Home example: A parent uses Python to organise family photos.

Nigerian example: A business owner in Lagos uses Python to track sales.

Illustration:

    You ๐Ÿ‘ง  โ†’  Python ๐Ÿ  โ†’  Computer ๐Ÿ’ป
    (instructions)   (language)   (action)
            

Mini summary: Python is a language we use to talk to computers.


Lesson 2 ยท Why Use Python?

Definition: Python is used because it is easy to read, easy to write, and can do many things.

Why important: Python is one of the most popular programming languages in the world.

Simple explanation: Python is like a Swiss Army knife โ€” it has many tools and can do many jobs.

Real-life example: Python is used by Google, Netflix, and many other companies.

School example: A teacher uses Python to make quizzes.

Home example: Someone uses Python to download music.

Nigerian example: A developer in Abuja uses Python to build websites.

Illustration:

    Python Can Do:
    ๐Ÿ“Š Data analysis
    ๐ŸŒ Web development
    ๐Ÿค– Automation
    ๐Ÿงช Science
    ๐ŸŽฎ Games
            

Mini summary: Python is powerful and can do many things.


Lesson 3 ยท What is Automation?

Definition: Automation means making a computer do tasks for you automatically.

Why important: Automation saves time and reduces mistakes.

Simple explanation: Instead of doing the same boring task again and again, you write a program that does it for you.

Real-life example: A teacher uses Python to send weekly emails to parents automatically.

School example: A student uses Python to automatically sort their files.

Home example: A parent uses Python to automatically backup photos.

Nigerian example: A shop owner uses Python to automatically calculate sales.

Illustration:

    Boring Task  โ†’  Python Script  โ†’  Done Automatically!
    (you do it)      (you write it)    (computer does it)
            

Mini summary: Automation is making the computer do boring work for you.


Lesson 4 ยท Installing Python

Definition: Installing Python means putting the Python software on your computer.

Why important: You need Python installed to write and run Python programs.

Simple explanation: Like installing a game on your phone before you can play it.

Real-life example: Go to python.org, download, and install.

School example: A teacher asks students to install Python at home.

Home example: You install Python to help your child learn coding.

Nigerian example: You install Python on your laptop in Lagos.

Illustration:

    Steps to Install Python:
    1. Go to python.org
    2. Click "Download"
    3. Run the installer
    4. Click "Install"
    5. Done! โœ…
            

Mini summary: Install Python to start writing programs.


Lesson 5 ยท Your First Python Program

Definition: Your first program will be print("Hello, world!"). It tells the computer to show the words "Hello, world!" on the screen.

Why important: This is a tradition. It is the first program most people write.

Simple explanation: print is a command that shows text on the screen.

Real-life example: You are telling the computer to say "Hi".

School example: A student writes this program in class.

Home example: A parent writes this program with their child.

Nigerian example: A young coder in Nigeria writes their first program.

Illustration:

    Code:  print("Hello, world!")
    Output: Hello, world!
            

Mini summary: print shows text on the screen.


Lesson 6 ยท Using the Terminal / Command Prompt

Definition: The terminal (or command prompt) is a place where you type commands to the computer.

Why important: You run your Python programs from the terminal.

Simple explanation: Like a text-based conversation with your computer.

Real-life example: You type python hello.py to run your program.

School example: Students open the terminal to run their code.

Home example: You open the terminal to test your program.

Nigerian example: A coder in Kano uses the terminal to run Python.

Illustration:

    Terminal:
    $ python hello.py
    Hello, world!
            

Mini summary: The terminal is where you run your programs.


Lesson 7 ยท Understanding the Print Function

Definition: print() is a function that shows text on the screen.

Why important: It is the easiest way to see what your program is doing.

Simple explanation: print is like saying something out loud.

Real-life example: print("Hello") shows "Hello" on the screen.

School example: Students use print to display their names.

Home example: You use print to display a message.

Nigerian example: A coder uses print to show a greeting in Yoruba.

Illustration:

    print("Hello")
    print("My name is Aisha")
    print("I love Python")

    Output:
    Hello
    My name is Aisha
    I love Python
            

Mini summary: print() shows text on the screen.


Lesson 8 ยท Numbers and Text (Data Types)

Definition: Data types are the different kinds of information in Python. Two important types are strings (text) and integers (numbers).

Why important: You need to know what kind of information you are using.

Simple explanation: Numbers and text are different things in Python.

Real-life example: 5 is a number. "5" is text.

School example: A student writes 5 + 3 (math) vs "5" + "3" (combines text).

Home example: You write numbers for math and text for names.

Nigerian example: A coder uses numbers for calculations and text for names.

Illustration:

    Text (string):  "Hello"
    Number (int):   10
    Text:           "Aisha"
    Number:         7
            

Mini summary: Text is in quotes. Numbers are not.


Lesson 9 ยท Variables

Definition: A variable is a container for storing information.

Why important: Variables help you remember and reuse information.

Simple explanation: Like a box with a name. You put something in the box, and you can take it out later.

Real-life example: name = "Aisha" stores the name "Aisha".

School example: score = 100 stores a score.

Home example: age = 10 stores an age.

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

Illustration:

    name = "Aisha"
    age = 25
    city = "Kano"

    print(name)   # prints: Aisha
    print(age)    # prints: 25
            

Mini summary: Variables store information for later use.


Lesson 10 ยท Combining Variables and Print

Definition: You can combine variables and print to show information.

Why important: It makes your programs more interesting.

Simple explanation: You can print the value of a variable.

Real-life example: print(name) shows the name.

School example: print("Hello,", name) shows "Hello, Aisha".

Home example: print("Your age is", age).

Nigerian example: print("Welcome to", city).

Illustration:

    name = "Chidi"
    print("Hello,", name)

    Output: Hello, Chidi
            

Mini summary: Combine variables with print to show information.


Lesson 11 ยท Comments in Code

Definition: Comments are notes you write in your code. They are ignored by the computer.

Why important: Comments help you and others understand your code.

Simple explanation: Like writing notes on a paper to remember something.

Real-life example: # This is a comment is ignored by Python.

School example: Students write comments to explain their code.

Home example: You write comments to remember what your code does.

Nigerian example: A coder writes comments in Nigerian English.

Illustration:

    # This program prints a greeting
    print("Hello, world!")  # This shows "Hello, world!"
            

Mini summary: Comments are notes to help understand code.


Lesson 12 ยท Saving Your Python Code

Definition: You save your code in a file with a .py extension, like hello.py.

Why important: Saving allows you to run your code again later.

Simple explanation: Like saving a document in Word.

Real-life example: Save as first.py and run it.

School example: Students save their programs for homework.

Home example: You save your programs to share with others.

Nigerian example: A coder saves their programs for later use.

Illustration:

    File: hello.py
    Content:
    print("Hello, world!")

    To run:  python hello.py
            

Mini summary: Save your code in a .py file.


Lesson 13 ยท Running Your Program Again

Definition: You can run your saved program anytime by typing python filename.py.

Why important: You can run your programs as many times as you want.

Simple explanation: Like running a video game again.

Real-life example: python hello.py runs the program.

School example: Students run their programs to test them.

Home example: You run your program to see if it works.

Nigerian example: A coder runs their program to test it.

Illustration:

    $ python hello.py
    Hello, world!
            

Mini summary: Run your saved programs anytime.


Lesson 14 ยท Errors Happen (And That's OK!)

Definition: An error is when your code doesn't work. The computer will tell you what is wrong.

Why important: Errors are part of learning. Don't be afraid of them.

Simple explanation: Like making a mistake in a math problem. You just need to fix it.

Real-life example: If you forget a quote, Python will give an error.

School example: A student gets an error and fixes it.

Home example: You get an error and correct it.

Nigerian example: A coder gets an error and learns from it.

Illustration:

    print("Hello)  # Missing quote โ†’ Error!
    print("Hello") # Correct โ†’ Works!
            

Mini summary: Errors are normal. Just fix them and try again.


Lesson 15 ยท You Are a Programmer Now!

Definition: If you have written and run a Python program, you are a programmer.

Why important: This is the first step on an exciting journey.

Simple explanation: You gave instructions to a computer and it listened!

Real-life example: You can now say "I can code in Python".

School example: A student is proud of their first program.

Home example: A parent learns to code with their child.

Nigerian example: A young Nigerian coder starts their journey.

Illustration:

    You ๐Ÿง‘โ€๐Ÿ’ป  โ†’  Write Code  โ†’  Run  โ†’  Computer Works!
    You are a programmer! ๐ŸŽ‰
            

Mini summary: You are now a programmer. Well done!


๐Ÿ“Œ Key Vocabulary

  • Python: A programming language.
  • Program: A set of instructions for a computer.
  • Automation: Making the computer do work for you.
  • Print: A command to show text on the screen.
  • Variable: A container for storing information.
  • String: Text in quotes.
  • Integer: A whole number.
  • Comment: A note in code that is ignored.
  • Error: A mistake in code.
  • Terminal: A place to type commands.

๐Ÿง  Important Concepts

  • Python is a language: You use it to talk to computers.
  • Automation saves time: Let the computer do boring work.
  • Print shows output: Use print() to see results.
  • Variables store data: Use them to remember information.
  • Errors are learning: Don't be afraid to make mistakes.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Write and Run Your First Python Program

  1. Open a text editor: Notepad, VS Code, or any text editor.
  2. Type the code: print("Hello, world!")
  3. Save the file: Save as hello.py.
  4. Open the terminal: Command Prompt (Windows) or Terminal (Mac/Linux).
  5. Run the program: Type python hello.py and press Enter.
  6. See the output: The terminal will show Hello, world!.

Example:

    Step 1: Open Notepad
    Step 2: Type print("Hello, world!")
    Step 3: Save as hello.py
    Step 4: Open Terminal
    Step 5: Type python hello.py
    Step 6: See Hello, world!
            

๐ŸŒ Real-life Examples

  • Greeting: print("Good morning, class!")
  • Message: print("Welcome to Python!")
  • Name: name = "Aisha" then print(name)
  • Number: age = 25 then print(age)
  • Combined: print("Hello,", name)

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Greeting in Yoruba: print("แบธ kรกร bแปฬ€!")
  • City: city = "Lagos" then print(city)
  • Name: name = "Chidi" then print(name)
  • Message: print("Welcome to Nigeria!")
  • Combined: print("Hello,", name, "from", city)

๐ŸŽˆ Fun Examples children can relate to

  • print("I love pizza!")
  • print("My favourite animal is a dog.")
  • name = "Tom" then print(name)
  • print("My name is", name)
  • print("๐Ÿ Python is cool!")

๐Ÿ  Everyday Examples

  • Morning: print("Good morning, family!")
  • Chores: print("Don't forget to take out the trash.")
  • School: print("Have a great day at school!")
  • Food: print("Dinner is ready!")
  • Fun: print("Let's play a game!")

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to write their first program.
  • Emphasise that errors are part of learning.
  • Use local examples to make it relatable.
  • Celebrate every student's first program.
  • Make it fun and interactive.

๐Ÿ‘ช Parent Tips

  • Help your child install Python.
  • Write your first program together.
  • Celebrate when they make it work.
  • Encourage them to experiment.
  • Make learning Python a fun activity.

๐Ÿง Interesting Facts

  • Python was created in 1991.
  • Python is named after the TV show "Monty Python".
  • Python is used by NASA.
  • Python is one of the most popular programming languages.
  • Millions of people learn Python every year.

๐Ÿ’ก Did You Know?

  • Did you know that Python can be used to build games?
  • Did you know that Python is used in artificial intelligence?
  • Did you know that Python is free to download?
  • Did you know that Python can be used on any computer?
  • Did you know that Python is a great first language to learn?

๐Ÿงท Remember This

  • Python is a language to talk to computers.
  • Automation makes boring tasks easy.
  • print() shows text on the screen.
  • Variables store information.
  • Errors are learning opportunities.

โš ๏ธ Common Mistakes

  • Forgetting quotes: print(Hello) โ†’ should be print("Hello").
  • Forgetting parentheses: print "Hello" โ†’ should be print("Hello").
  • Mixing quotes: print("Hello') โ†’ be consistent.
  • Spelling errors: prin("Hello") โ†’ should be print("Hello").
  • Not saving files: Remember to save your code before running.

โœ… Best Practices

  • Always save your code with a .py extension.
  • Use comments to explain your code.
  • Start with simple programs and build up.
  • Read error messages carefully.
  • Practice, practice, practice!

๐ŸŽจ Illustrations, Diagrams & Tables

Python Installation Steps

    +------------------+
    | 1. Go to python.org |
    +------------------+
            |
            V
    +------------------+
    | 2. Click Download  |
    +------------------+
            |
            V
    +------------------+
    | 3. Run Installer   |
    +------------------+
            |
            V
    +------------------+
    | 4. Click Install   |
    +------------------+
            |
            V
    +------------------+
    | 5. Done! โœ…        |
    +------------------+
            

Print Function Examples

CodeOutput
print("Hello")Hello
print("Python")Python
print("1")1
print(2 + 3)5

Comparison: String vs Integer

Data TypeExampleWith Quotes?
String (text)"Hello"Yes
Integer (number)5No
String (text)"5"Yes
Integer (number)10No

๐Ÿ“ End-of-Module Summary

In this module, we learned the basics of Python. We discovered what Python is and why it is useful. We installed Python and wrote our very first program: print("Hello, world!"). We learned about variables, data types, and comments. We also learned about errors and how to fix them. With these foundations, you are ready to learn more about automation with Python!

โ“ Frequently Asked Questions (10)

  1. What is Python? A programming language.
  2. Is Python free? Yes, it is free.
  3. Can I use Python on my computer? Yes, it works on Windows, Mac, and Linux.
  4. What is print()? A command to show text.
  5. What is a variable? A container for information.
  6. What is a string? Text in quotes.
  7. What is an integer? A whole number.
  8. What are comments? Notes in code.
  9. What should I do if I get an error? Read the error message and fix it.
  10. Am I a programmer now? Yes, you are!

๐Ÿ“‹ Review Questions (15)

  1. What is Python?
  2. What is automation?
  3. How do you install Python?
  4. What is print() used for?
  5. How do you save a Python file?
  6. What is a variable?
  7. What is a string?
  8. What is an integer?
  9. What are comments?
  10. How do you run a Python program?
  11. What is an error?
  12. Why are errors okay?
  13. How do you fix an error?
  14. What does print("Hello") do?
  15. What is the extension for Python files?

โœ๏ธ Fill-in-the-Blank Exercises

  1. Python is a ______________ language. (programming)
  2. print() shows ______________ on the screen. (text)
  3. A variable stores ______________. (information)
  4. Text in quotes is called a ______________. (string)
  5. A whole number is called an ______________. (integer)

โœ… True or False Exercises

  1. Python is a programming language. (True)
  2. print() is used to hide text. (False)
  3. Variables store information. (True)
  4. Comments are read by Python. (False)
  5. Errors are bad and should be avoided completely. (False)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is Python?
    a) A programming language โœ…
    b) A type of snake
    c) A game
  2. What does print() do?
    a) Shows text โœ…
    b) Hides text
    c) Deletes text
  3. What is a variable?
    a) A container for information โœ…
    b) A type of food
    c) A game
  4. What is a string?
    a) Text in quotes โœ…
    b) A number
    c) A type of food
  5. What is an integer?
    a) A whole number โœ…
    b) Text in quotes
    c) A type of food
  6. What is a comment?
    a) A note in code โœ…
    b) A command
    c) A type of food
  7. How do you save a Python file?
    a) With a .py extension โœ…
    b) With a .txt extension
    c) With a .doc extension
  8. How do you run a Python program?
    a) Type python filename.py โœ…
    b) Double-click the file
    c) Open it in Word
  9. What should you do if you get an error?
    a) Read and fix it โœ…
    b) Ignore it
    c) Delete the file
  10. What does print("Hello") show?
    a) Hello โœ…
    b) Goodbye
    c) Nothing
  11. What is automation?
    a) Making the computer do work โœ…
    b) Playing games
    c) Sleeping
  12. What is a programming language?
    a) A way to talk to computers โœ…
    b) A type of food
    c) A game
  13. Can Python be used for automation?
    a) Yes โœ…
    b) No
  14. Is Python free?
    a) Yes โœ…
    b) No
  15. Can you write comments in Python?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. PythonA) Shows text on the screen
2. printB) A programming language
3. VariableC) A note in code
4. StringD) A container for information
5. CommentE) Text in quotes

(Answers: 1-B, 2-A, 3-D, 4-E, 5-C)

๐Ÿ“ Short Answer Questions

  1. What is Python in your own words?
  2. Write one way you can use Python for automation.
  3. What does print("Hello") do?

๐ŸŽญ Scenario-based Exercises

Scenario 1: You want to write a program that says "Welcome to Nigeria!" on the screen. Write the code.

Scenario 2: You get an error that says NameError: name 'print' is not defined. What might be wrong?

๐Ÿ‘ฅ Group Activity

In groups of 3, share the first program you wrote. Discuss what you learned. Then, write a program together that prints a greeting from your group.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Write a Python program that prints your name, your favourite food, and your favourite colour. Save it and run it.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • What was the hardest part of writing your first program?
  • What are you most excited to learn next?
  • How can Python help you in your daily life?

๐Ÿ› ๏ธ Mini Project

Write a Python program that prints a poem or a song you like. Include at least 5 lines. Save it as poem.py and run it.

๐Ÿ“ Practical Assignment

Write a program that prints a welcome message to your class. Use variables for your name, the class name, and the date. Print everything in one message.

๐Ÿ† Challenge Exercise

Write a program that prints a pattern using print() statements. For example:

    *
    **
    ***
    ****
            

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-programming, 2-text, 3-information, 4-string, 5-integer

True/False: 1-T, 2-F, 3-T, 4-F, 5-F

Matching: 1-B, 2-A, 3-D, 4-E, 5-C

๐ŸŽ Key Takeaways

  • Python is a programming language that is easy to learn.
  • You can use Python to automate boring tasks.
  • print() shows text on the screen.
  • Variables store information for later use.
  • Errors are normal and help you learn.

๐Ÿš€ Preparation for the next module

In Module Two, we will learn more about variables, data types, and how to do math with Python. Before the next session, try to write a program that prints your name and age. See you in Module Two!

See you in Module Two! ๐ŸŽ‰


End of Module One ยท Welcome to Python!

4

Module Two

Module Two ยท Python for Automation

๐Ÿ“ฆ Module Two ยท Variables and Data Types


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module One, we learned how to write our first Python program. We used print() to show text on the screen. But what if we want to store information and use it later? That's where variables come in!

In this module, we will learn about variables โ€” containers that hold information. We will also learn about different types of information: text (strings) and numbers (integers and floats). By the end of this module, you will be able to store information and use it in your programs.

๐ŸŽฏ Learning Objectives

  • Understand what variables are and why they are useful.
  • Learn about different data types: strings, integers, and floats.
  • Store and use information in variables.
  • Perform basic math operations with numbers.
  • Combine text and numbers in print statements.

๐Ÿ“š Warm-up Story ยท Tunde's Grade Calculator

Tunde is a student in Ibadan. He wanted to calculate his average grade for three subjects. He wrote his grades on paper, added them up, and divided by 3. But he made a mistake and got the wrong average.

His friend told him about Python. Tunde used variables to store his grades: math = 85, english = 90, science = 78. Then he wrote: average = (math + english + science) / 3 and print(average). Python did the math perfectly. Tunde never made a mistake again!

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is a Variable?

Definition: A variable is a container for storing information. It has a name and a value.

Why important: Variables allow you to remember and reuse information in your programs.

Simple explanation: Like a box with a label. You put something in the box, and you can take it out later.

Real-life example: name = "Aisha" stores the name "Aisha".

School example: score = 85 stores a test score.

Home example: age = 10 stores your age.

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

Illustration:

    +-------------------------+
    |  Variable: name          |
    |  Value: "Aisha"          |
    +-------------------------+
    |  Variable: age           |
    |  Value: 25               |
    +-------------------------+
            

Mini summary: Variables store information for later use.


Lesson 2 ยท Creating Variables

Definition: You create a variable by giving it a name and assigning a value with =.

Why important: This is how you store information in your program.

Simple explanation: You say name = "Aisha" to tell Python that the variable "name" has the value "Aisha".

Real-life example: favourite_food = "jollof rice".

School example: subject = "Math".

Home example: pet_name = "Bella".

Nigerian example: state = "Kano".

Illustration:

    name = "Aisha"      # text
    age = 25            # number
    city = "Lagos"      # text
    score = 95          # number
            

Mini summary: Use = to give a variable a value.


Lesson 3 ยท Rules for Variable Names

Definition: There are rules for naming variables. They must start with a letter or underscore, and can only contain letters, numbers, and underscores.

Why important: Following the rules ensures your code works.

Simple explanation: Like naming a pet โ€” there are some rules.

Real-life example: student_name is okay. 2nd_student is not okay.

School example: test_score is okay. test-score is not okay.

Home example: family_member is okay.

Nigerian example: city_name is okay.

Illustration:

    โœ… Good Names: name, age, city, student_1, first_name
    โŒ Bad Names: 2nd, my-name, class, student name (space)
            

Mini summary: Use letters, numbers, and underscores. No spaces or special characters.


Lesson 4 ยท Data Types

Definition: Data types are the different kinds of information you can store. The main ones are strings (text), integers (whole numbers), and floats (decimal numbers).

Why important: Different data types are used for different purposes.

Simple explanation: Different types of information โ€” like words and numbers.

Real-life example: "Hello" is text. 5 is a number. 3.14 is a decimal.

School example: name = "Aisha" (text). score = 85 (number).

Home example: price = 10.50 (decimal).

Nigerian example: population = 200_000_000 (number).

Illustration:

    Data Types:
    String (text):  "Hello", "Aisha", "Nigeria"
    Integer (whole number):  5, 10, 100
    Float (decimal number):  3.14, 2.5, 0.99
            

Mini summary: Strings are text. Integers are whole numbers. Floats are decimals.


Lesson 5 ยท Strings (Text)

Definition: A string is text. It is written inside quotes โ€” either single quotes ' ' or double quotes " ".

Why important: Strings are used for words, names, and any text.

Simple explanation: Anything inside quotes is a string.

Real-life example: name = "Aisha".

School example: subject = "Math".

Home example: meal = "Jollof rice".

Nigerian example: city = "Abuja".

Illustration:

    name = "Aisha"
    greeting = 'Hello!'
    message = "Welcome to Python"
            

Mini summary: Strings are text inside quotes.


Lesson 6 ยท Integers (Whole Numbers)

Definition: An integer is a whole number. It has no decimal point.

Why important: Integers are used for counting and math.

Simple explanation: Numbers like 1, 2, 3, 10, 100.

Real-life example: age = 25.

School example: score = 95.

Home example: children = 3.

Nigerian example: states = 36.

Illustration:

    age = 25
    score = 95
    students = 30
            

Mini summary: Integers are whole numbers without decimals.


Lesson 7 ยท Floats (Decimal Numbers)

Definition: A float is a number with a decimal point.

Why important: Floats are used for precise measurements.

Simple explanation: Numbers like 3.14, 2.5, 10.99.

Real-life example: price = 10.99.

School example: average = 85.5.

Home example: temperature = 36.5.

Nigerian example: naira = 1600.50.

Illustration:

    price = 10.99
    average = 85.5
    temperature = 36.5
            

Mini summary: Floats are numbers with decimals.


Lesson 8 ยท Math Operations

Definition: Python can do math with numbers. The main operations are + (add), - (subtract), * (multiply), / (divide), and ** (power).

Why important: Math is essential for many automation tasks.

Simple explanation: Like using a calculator.

Real-life example: total = 5 + 3 (8).

School example: average = (80 + 90 + 100) / 3.

Home example: total_cost = 10 * 5.

Nigerian example: total = 1000 + 500.

Illustration:

    print(5 + 3)   # 8
    print(10 - 4)  # 6
    print(3 * 4)   # 12
    print(10 / 2)  # 5
    print(2 ** 3)  # 8 (2 to the power of 3)
            

Mini summary: Python can add, subtract, multiply, divide, and more.


Lesson 9 ยท Combining Variables and Math

Definition: You can store numbers in variables and do math with them.

Why important: This makes your programs flexible and powerful.

Simple explanation: You put numbers in boxes and then do math with the boxes.

Real-life example: score1 = 85, score2 = 90, total = score1 + score2.

School example: math = 80, english = 85, average = (math + english) / 2.

Home example: apples = 5, oranges = 3, total = apples + oranges.

Nigerian example: naira = 500, kobo = 50, total = naira + kobo.

Illustration:

    score1 = 85
    score2 = 90
    total = score1 + score2
    print(total)  # 175
            

Mini summary: Use variables in math operations.


Lesson 10 ยท Combining Strings

Definition: You can combine (concatenate) strings using +.

Why important: This allows you to create new strings from existing ones.

Simple explanation: You join words together.

Real-life example: full_name = first_name + " " + last_name.

School example: greeting = "Hello, " + name.

Home example: message = "Good " + time_of_day.

Nigerian example: welcome = "Welcome to " + city.

Illustration:

    first_name = "Aisha"
    last_name = "Bello"
    full_name = first_name + " " + last_name
    print(full_name)  # Aisha Bello
            

Mini summary: Use + to join strings.


Lesson 11 ยท Type Conversion

Definition: Sometimes you need to convert one data type to another. For example, turning a number into a string to print it.

Why important: You cannot combine strings and numbers without converting.

Simple explanation: Like changing Naira to Kobo.

Real-life example: age = 25, print("I am " + str(age)).

School example: score = 85, print("Your score is " + str(score)).

Home example: price = 10, print("The price is " + str(price)).

Nigerian example: amount = 500, print("You have " + str(amount) + " Naira").

Illustration:

    age = 25
    print("I am " + str(age))  # I am 25
            

Mini summary: Use str() to convert numbers to strings.


Lesson 12 ยท Input from the User

Definition: You can ask the user for input using input().

Why important: This makes your program interactive.

Simple explanation: Like asking a question and waiting for an answer.

Real-life example: name = input("What is your name? ").

School example: age = input("How old are you? ").

Home example: food = input("What is your favourite food? ").

Nigerian example: city = input("Which city do you live in? ").

Illustration:

    name = input("Enter your name: ")
    print("Hello, " + name)
            

Mini summary: input() gets information from the user.


Lesson 13 ยท Comments in Code

Definition: Comments are notes you write in your code. They are ignored by the computer.

Why important: Comments help you and others understand your code.

Simple explanation: Like writing notes on a paper to remember something.

Real-life example: # This is a comment is ignored by Python.

School example: Students write comments to explain their code.

Home example: You write comments to remember what your code does.

Nigerian example: A coder writes comments in Nigerian English.

Illustration:

    # This program prints a greeting
    print("Hello, world!")  # This shows "Hello, world!"
            

Mini summary: Comments are notes to help understand code.


Lesson 14 ยท Putting It All Together

Definition: Now you can combine variables, data types, math, and input to create useful programs.

Why important: This is how you start building real automation tools.

Simple explanation: Like cooking โ€” you mix ingredients to make a meal.

Real-life example: A program that calculates your average grade.

School example: A program that asks for your name and says "Hello".

Home example: A program that calculates the total cost of items.

Nigerian example: A program that converts Naira to Dollars.

Illustration:

    name = input("Enter your name: ")
    age = int(input("Enter your age: "))
    print("Hello, " + name + "! You are " + str(age) + " years old.")
            

Mini summary: Combine all concepts to build useful programs.


Lesson 15 ยท You Are Making Progress!

Definition: You have learned about variables, data types, math, and input. This is a big step.

Why important: You are building the foundation for automation.

Simple explanation: You are learning to talk to computers!

Real-life example: You can now write programs that ask questions and do math.

School example: You can create interactive programs.

Home example: You can write programs to help with family tasks.

Nigerian example: You are becoming a Python coder in Nigeria!

Illustration:

    You ๐Ÿง‘โ€๐Ÿ’ป  โ†’  Write Code  โ†’  Run  โ†’  Computer Works!
    You are making great progress! ๐ŸŽ‰
            

Mini summary: You are making great progress. Keep going!


๐Ÿ“Œ Key Vocabulary

  • Variable: A container for storing information.
  • String: Text in quotes.
  • Integer: A whole number.
  • Float: A decimal number.
  • Data type: The type of information (text, number, etc.).
  • Concatenation: Joining strings together.
  • Type conversion: Changing one data type to another.
  • Input: Getting information from the user.
  • Comment: A note in code that is ignored.
  • Math operation: Adding, subtracting, multiplying, etc.

๐Ÿง  Important Concepts

  • Variables store information: Use them to remember data.
  • Different data types: Strings for text, integers for whole numbers, floats for decimals.
  • Math operations: Use +, -, *, /, ** for calculations.
  • String concatenation: Use + to join strings.
  • User input: Use input() to get information from the user.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Create a Program that Asks for a Name and Age

  1. Ask for the name: name = input("Enter your name: ")
  2. Ask for the age: age = int(input("Enter your age: "))
  3. Print a message: print("Hello, " + name + "! You are " + str(age) + " years old.")
  4. Save and run: Save as greeting.py and run.

Example:

    Step 1: name = input("Enter your name: ")
    Step 2: age = int(input("Enter your age: "))
    Step 3: print("Hello, " + name + "! You are " + str(age) + " years old.")
    Step 4: Run the program!
            

๐ŸŒ Real-life Examples

  • Greeting: name = input("What is your name? ") then print("Hello, " + name).
  • Math: num1 = 10, num2 = 5, print(num1 + num2).
  • String: first = "John", last = "Doe", print(first + " " + last).
  • Conversion: age = 25, print("I am " + str(age)).
  • Average: math = 80, english = 85, average = (math + english) / 2.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Greeting: name = input("What is your name? ") then print("Hello, " + name + "! Welcome to Nigeria.").
  • City: city = "Lagos", print("I live in " + city).
  • Currency: naira = 500, print("You have " + str(naira) + " Naira").
  • States: states = 36, print("Nigeria has " + str(states) + " states.").
  • Food: food = "Jollof rice", print("My favourite food is " + food).

๐ŸŽˆ Fun Examples children can relate to

  • name = input("What is your name? ") then print("Hello, " + name + "! I love Python!").
  • age = int(input("How old are you? ")) then print("You are " + str(age) + " years old.").
  • food = input("What is your favourite food? ") then print("I love " + food + " too!").
  • game = input("What is your favourite game? ") then print("Let's play " + game + "!").
  • animal = input("What is your favourite animal? ") then print("I like " + animal + " too!").

๐Ÿ  Everyday Examples

  • Morning: name = input("What is your name? ") then print("Good morning, " + name).
  • Chores: chore = input("What chore do you need to do? ") then print("Don't forget to " + chore).
  • Food: meal = input("What is for dinner? ") then print("I can't wait to eat " + meal).
  • Homework: subject = input("What subject is your homework? ") then print("Good luck with " + subject).
  • Family: sibling = input("What is your sibling's name? ") then print("Hello, " + sibling).

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to experiment with variables and data types.
  • Use local examples to make it relatable.
  • Emphasise the importance of variable names.
  • Have students create programs that ask for user input.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child understand variables and data types.
  • Write programs together that ask for names and ages.
  • Encourage them to create their own programs.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Python is used in schools all over the world.
  • Variables can store many types of information.
  • Python can handle very large numbers.
  • Strings can be very long โ€” even an entire book!
  • Python is used in many Nigerian companies.

๐Ÿ’ก Did You Know?

  • Did you know that you can store a whole sentence in a variable?
  • Did you know that Python can do very complex math?
  • Did you know that you can combine strings and numbers?
  • Did you know that input() always gives you a string?
  • Did you know that Python can convert between data types?

๐Ÿงท Remember This

  • Variables store information.
  • Strings are text in quotes.
  • Integers are whole numbers.
  • Floats are decimal numbers.
  • Use + to add numbers and join strings.
  • Use str() to convert numbers to strings.
  • Use int() to convert strings to integers.

โš ๏ธ Common Mistakes

  • Forgetting quotes: name = Aisha โ†’ should be name = "Aisha".
  • Mixing data types: print("Age is " + age) โ†’ use str(age).
  • Invalid variable names: my-name โ†’ use my_name.
  • Forgetting to convert: age = input("Enter age: ") gives a string โ€” use int() for math.
  • Not using parentheses: print "Hello" โ†’ should be print("Hello").

โœ… Best Practices

  • Use descriptive variable names: student_name instead of a.
  • Use comments to explain your code.
  • Convert input to the right data type.
  • Use str() to print numbers with text.
  • Test your programs with different inputs.

๐ŸŽจ Illustrations, Diagrams & Tables

Data Types in Python

Data TypeDescriptionExample
StringText in quotes"Hello", 'Aisha'
IntegerWhole number25, 100
FloatNumber with decimal3.14, 10.5

Math Operations

OperationSymbolExample
Addition+5 + 3 = 8
Subtraction-10 - 4 = 6
Multiplication*3 * 4 = 12
Division/10 / 2 = 5
Power**2 ** 3 = 8

Variable Name Rules

    โœ… Allowed: student_name, score2, first_name
    โŒ Not Allowed: 2nd_score, my-name, class (reserved word)
            

๐Ÿ“ End-of-Module Summary

In this module, we learned about variables and data types. We discovered that variables are containers for storing information. We learned about three data types: strings (text), integers (whole numbers), and floats (decimal numbers). We also learned how to do math with numbers and combine text. We even learned how to get input from the user. With these skills, you can now write programs that store, use, and display information. Great work!

โ“ Frequently Asked Questions (10)

  1. What is a variable? A container for storing information.
  2. What is a string? Text in quotes.
  3. What is an integer? A whole number.
  4. What is a float? A decimal number.
  5. How do I create a variable? name = "Aisha".
  6. How do I do math? total = 5 + 3.
  7. How do I combine strings? full = first + " " + last.
  8. How do I get user input? name = input("Enter name: ").
  9. What is type conversion? Changing one data type to another.
  10. How do I convert a number to a string? str(number).

๐Ÿ“‹ Review Questions (15)

  1. What is a variable?
  2. What is a string?
  3. What is an integer?
  4. What is a float?
  5. How do you create a variable?
  6. What is concatenation?
  7. How do you do addition in Python?
  8. How do you get user input?
  9. What is type conversion?
  10. How do you convert a number to a string?
  11. What are the rules for variable names?
  12. What is a comment?
  13. How do you write a comment?
  14. What is the output of print(5 + 3)?
  15. What is the output of print("Hello" + " " + "World")?

โœ๏ธ Fill-in-the-Blank Exercises

  1. A ______________ stores information. (variable)
  2. Text in quotes is called a ______________. (string)
  3. A whole number is called an ______________. (integer)
  4. A decimal number is called a ______________. (float)
  5. Use ________ to get user input. (input)

โœ… True or False Exercises

  1. Variables store information. (True)
  2. Strings are written without quotes. (False)
  3. Integers are whole numbers. (True)
  4. Floats are decimal numbers. (True)
  5. input() gets information from the user. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is a variable?
    a) A container for information โœ…
    b) A type of food
    c) A game
  2. What is a string?
    a) Text in quotes โœ…
    b) A number
    c) A type of food
  3. What is an integer?
    a) A whole number โœ…
    b) Text in quotes
    c) A decimal number
  4. What is a float?
    a) A decimal number โœ…
    b) A whole number
    c) Text in quotes
  5. How do you create a variable?
    a) name = "Aisha" โœ…
    b) name = Aisha
    c) name = 'Aisha
  6. How do you do addition?
    a) 5 + 3 โœ…
    b) 5 - 3
    c) 5 * 3
  7. How do you get user input?
    a) input() โœ…
    b) print()
    c) str()
  8. What is type conversion?
    a) Changing data types โœ…
    b> Changing variables
    c) Changing names
  9. How do you convert a number to a string?
    a) str() โœ…
    b) int()
    c) float()
  10. What is concatenation?
    a) Joining strings โœ…
    b> Multiplying numbers
    c) Dividing numbers
  11. What are rules for variable names?
    a) No spaces โœ…
    b) Can start with numbers
    c) No underscores
  12. What is a comment?
    a) A note in code โœ…
    b) A command
    c) A variable
  13. What is the output of print(5 + 3)?
    a) 8 โœ…
    b) 53
    c) 15
  14. What is the output of print("Hello" + " " + "World")?
    a) Hello World โœ…
    b) HelloWorld
    c) HelloWorld
  15. Can Python do math?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. VariableA) A whole number
2. StringB) A container for information
3. IntegerC) Text in quotes
4. FloatD) Gets information from the user
5. input()E) A decimal number

(Answers: 1-B, 2-C, 3-A, 4-E, 5-D)

๐Ÿ“ Short Answer Questions

  1. What is a variable and why is it useful?
  2. What is the difference between an integer and a float?
  3. Write a program that asks for a name and prints "Hello, [name]!".

๐ŸŽญ Scenario-based Exercises

Scenario 1: You want to create a program that asks for a user's age and tells them how old they will be in 10 years. Write the code.

Scenario 2: You have two numbers in variables a and b. Write code to add them and print the result.

๐Ÿ‘ฅ Group Activity

In groups of 3, create a program that asks for each group member's name and age. Then print a message that includes everyone's name and the total age of the group.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Write a program that asks for your first name, last name, and year of birth. Then print your full name and your age (assuming the current year is 2026).

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • What is the most interesting thing you learned about variables?
  • How can you use variables in everyday life?
  • What other data types do you think exist?

๐Ÿ› ๏ธ Mini Project

Create a program that acts as a simple calculator. Ask the user for two numbers and then print the sum, difference, product, and quotient.

๐Ÿ“ Practical Assignment

Write a program that asks for your favourite food, your favourite colour, and your favourite animal. Then print a message that includes all three.

๐Ÿ† Challenge Exercise

Write a program that converts Celsius to Fahrenheit. Ask the user for the temperature in Celsius and print the Fahrenheit equivalent. Formula: F = C * 9/5 + 32.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-variable, 2-string, 3-integer, 4-float, 5-input

True/False: 1-T, 2-F, 3-T, 4-T, 5-T

Matching: 1-B, 2-C, 3-A, 4-E, 5-D

๐ŸŽ Key Takeaways

  • Variables store information for later use.
  • Strings are text inside quotes.
  • Integers are whole numbers.
  • Floats are decimal numbers.
  • Python can do math with numbers.
  • Use input() to get information from the user.
  • Use str() and int() to convert data types.

๐Ÿš€ Preparation for the next module

In Module Three, we will learn about lists and loops. We will learn how to store multiple items in a list and how to repeat actions using loops. Before the next session, think of a list of things you use every day.

See you in Module Three! ๐ŸŽ‰


End of Module Two ยท Variables and Data Types

5

Module Three

Module Three ยท Python for Automation

๐Ÿ“‹ Module Three ยท Lists and Loops


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Two, we learned about variables and data types. We learned how to store single pieces of information. But what if we need to store many things, like a list of names or a list of numbers? That's where lists come in.

In this module, we will learn about lists โ€” containers that can hold many items. We will also learn about loops โ€” a way to repeat actions automatically. Loops are very powerful for automation. By the end of this module, you will be able to store lists of data and process them automatically.

๐ŸŽฏ Learning Objectives

  • Understand what lists are and how to create them.
  • Access items in a list by their position.
  • Add, remove, and change items in a list.
  • Use for loops to repeat actions.
  • Use loops to process lists automatically.

๐Ÿ“š Warm-up Story ยท Grace's Shopping List

Grace is a student in Enugu. Every week, she writes a shopping list on paper. But sometimes she forgets to bring the list to the market. One day, she thought: "What if I could store my shopping list on my computer and print it whenever I need it?"

Her friend told her about Python lists. Grace wrote: shopping_list = ["rice", "beans", "oil", "salt", "sugar"]. Then she used a loop: for item in shopping_list: print(item). Python printed her entire shopping list. Grace never forgot her list again!

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is a List?

Definition: A list is a container that can hold multiple items. It is created using square brackets [] and items are separated by commas.

Why important: Lists allow you to store and manage many pieces of information at once.

Simple explanation: Like a shopping list with many items.

Real-life example: fruits = ["apple", "banana", "orange"].

School example: subjects = ["Math", "English", "Science"].

Home example: family = ["Mum", "Dad", "Sister"].

Nigerian example: cities = ["Lagos", "Abuja", "Kano"].

Illustration:

    +-----------------------------+
    |  fruits = ["apple", "banana", "orange"]  |
    +-----------------------------+
            

Mini summary: Lists hold multiple items.


Lesson 2 ยท Creating Lists

Definition: You create a list by putting items inside square brackets [], separated by commas.

Why important: This is how you store many items in one variable.

Simple explanation: Like a box with many compartments.

Real-life example: colours = ["red", "green", "blue"].

School example: students = ["Aisha", "Chidi", "Bola"].

Home example: chores = ["sweep", "wash", "cook"].

Nigerian example: states = ["Lagos", "Kano", "Kaduna"].

Illustration:

    fruits = ["apple", "banana", "orange"]
    numbers = [1, 2, 3, 4, 5]
    mixed = ["Aisha", 25, "Lagos"]
            

Mini summary: Use [] with commas to create a list.


Lesson 3 ยท Accessing Items in a List

Definition: You can access items in a list using their index โ€” a number that tells the position. Indexes start at 0.

Why important: You need to get specific items from your list.

Simple explanation: Like the position of a book on a shelf.

Real-life example: fruits[0] gives the first item.

School example: students[1] gives the second student.

Home example: chores[2] gives the third chore.

Nigerian example: states[0] gives the first state.

Illustration:

    fruits = ["apple", "banana", "orange"]
    print(fruits[0])  # apple
    print(fruits[1])  # banana
    print(fruits[2])  # orange
            

Mini summary: Use indexes starting at 0 to access items.


Lesson 4 ยท Changing Items in a List

Definition: You can change an item in a list by assigning a new value to its index.

Why important: This allows you to update information.

Simple explanation: Like crossing out an item on a shopping list and writing a new one.

Real-life example: fruits[1] = "mango" changes the second item.

School example: students[0] = "Ada" changes the first student.

Home example: chores[2] = "clean" changes the third chore.

Nigerian example: states[1] = "Oyo" changes the second state.

Illustration:

    fruits = ["apple", "banana", "orange"]
    fruits[1] = "mango"
    print(fruits)  # ["apple", "mango", "orange"]
            

Mini summary: Change items by assigning a new value to an index.


Lesson 5 ยท Adding Items to a List

Definition: You can add items to a list using append() (adds to the end) or insert() (adds at a position).

Why important: You often need to add new items.

Simple explanation: Like adding a new item to a shopping list.

Real-life example: fruits.append("grape") adds "grape" to the end.

School example: students.append("Chidi") adds a student.

Home example: chores.append("dust") adds a chore.

Nigerian example: states.append("Edo") adds a state.

Illustration:

    fruits = ["apple", "banana"]
    fruits.append("orange")
    print(fruits)  # ["apple", "banana", "orange"]
            

Mini summary: Use append() to add items.


Lesson 6 ยท Removing Items from a List

Definition: You can remove items using remove() (by value) or pop() (by index).

Why important: You may need to delete items.

Simple explanation: Like crossing out an item on a shopping list.

Real-life example: fruits.remove("banana") removes "banana".

School example: students.pop(0) removes the first student.

Home example: chores.remove("sweep") removes "sweep".

Nigerian example: states.pop(2) removes the third state.

Illustration:

    fruits = ["apple", "banana", "orange"]
    fruits.remove("banana")
    print(fruits)  # ["apple", "orange"]
            

Mini summary: Use remove() or pop() to remove items.


Lesson 7 ยท List Length

Definition: You can find the number of items in a list using len().

Why important: This tells you how many items you have.

Simple explanation: Like counting the items on a shopping list.

Real-life example: len(fruits) gives the number of fruits.

School example: len(students) gives the number of students.

Home example: len(chores) gives the number of chores.

Nigerian example: len(states) gives the number of states.

Illustration:

    fruits = ["apple", "banana", "orange"]
    print(len(fruits))  # 3
            

Mini summary: Use len() to get the number of items.


Lesson 8 ยท What is a Loop?

Definition: A loop is a way to repeat a block of code multiple times. The for loop is used to iterate over items in a list.

Why important: Loops allow you to do the same action many times automatically.

Simple explanation: Like reading every item on a shopping list.

Real-life example: for fruit in fruits: print(fruit) prints each fruit.

School example: for student in students: print("Hello, " + student).

Home example: for chore in chores: print(chore).

Nigerian example: for state in states: print(state).

Illustration:

    fruits = ["apple", "banana", "orange"]
    for fruit in fruits:
        print(fruit)

    Output:
    apple
    banana
    orange
            

Mini summary: for loops repeat actions for each item.


Lesson 9 ยท The For Loop

Definition: The for loop is used to repeat a block of code for each item in a sequence (like a list).

Why important: This is one of the most powerful tools in programming.

Simple explanation: You say "for each item, do this".

Real-life example: for i in range(5): print(i) prints 0 to 4.

School example: for number in numbers: print(number * 2) doubles each number.

Home example: for name in family: print("Hello, " + name).

Nigerian example: for city in cities: print(city + " is in Nigeria").

Illustration:

    cities = ["Lagos", "Abuja", "Kano"]
    for city in cities:
        print(city + " is a city in Nigeria.")

    Output:
    Lagos is a city in Nigeria.
    Abuja is a city in Nigeria.
    Kano is a city in Nigeria.
            

Mini summary: for loops process each item in a list.


Lesson 10 ยท The Range Function

Definition: range() generates a sequence of numbers. It is often used with for loops to repeat an action a certain number of times.

Why important: This allows you to repeat an action a specific number of times.

Simple explanation: Like saying "do this 5 times".

Real-life example: for i in range(5): print("Hello") prints "Hello" 5 times.

School example: for i in range(10): print(i) prints 0 to 9.

Home example: for i in range(3): print("Clean the room").

Nigerian example: for i in range(4): print("Nigeria") prints "Nigeria" 4 times.

Illustration:

    for i in range(5):
        print(i)

    Output:
    0
    1
    2
    3
    4
            

Mini summary: range() generates a sequence of numbers.


Lesson 11 ยท Looping Through Lists

Definition: You can loop through a list to process each item automatically.

Why important: This is how you automate tasks that involve many items.

Simple explanation: Like a robot going through each item on a list.

Real-life example: for item in shopping_list: print(item) prints each item.

School example: for score in scores: total = total + score adds all scores.

Home example: for name in family: print("Good morning, " + name).

Nigerian example: for state in states: print(state + " is a state in Nigeria").

Illustration:

    scores = [85, 90, 78, 92]
    total = 0
    for score in scores:
        total = total + score
    print(total)  # 345
            

Mini summary: Loops process each item in a list automatically.


Lesson 12 ยท While Loops

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

Why important: This is useful when you don't know how many times to repeat.

Simple explanation: Like saying "keep doing this until I say stop".

Real-life example: while i < 5: print(i); i = i + 1.

School example: while answer != "yes": answer = input("Say yes: ").

Home example: while not done: print("Working...").

Nigerian example: while count < 10: print(count); count = count + 1.

Illustration:

    i = 0
    while i < 5:
        print(i)
        i = i + 1

    Output:
    0
    1
    2
    3
    4
            

Mini summary: while loops repeat while a condition is true.


Lesson 13 ยท Breaking a Loop

Definition: You can stop a loop early using break.

Why important: This allows you to exit a loop when a condition is met.

Simple explanation: Like saying "stop right now".

Real-life example: for i in range(10): if i == 5: break; print(i) prints 0-4.

School example: for number in numbers: if number < 0: break.

Home example: while True: answer = input("Stop? "); if answer == "yes": break.

Nigerian example: for i in range(10): if i == 5: break; print(i).

Illustration:

    for i in range(10):
        if i == 5:
            break
        print(i)

    Output:
    0
    1
    2
    3
    4
            

Mini summary: break stops a loop early.


Lesson 14 ยท Skipping in a Loop

Definition: You can skip an iteration using continue.

Why important: This allows you to skip certain items.

Simple explanation: Like saying "skip this one and continue".

Real-life example: for i in range(5): if i == 2: continue; print(i) prints 0,1,3,4.

School example: for number in numbers: if number % 2 == 0: continue; print(number) prints odd numbers.

Home example: for chore in chores: if chore == "sweep": continue; print(chore).

Nigerian example: for city in cities: if city == "Abuja": continue; print(city).

Illustration:

    for i in range(5):
        if i == 2:
            continue
        print(i)

    Output:
    0
    1
    3
    4
            

Mini summary: continue skips an iteration.


Lesson 15 ยท Putting It All Together

Definition: You can combine lists and loops to automate tasks that involve many items.

Why important: This is how you build powerful automation tools.

Simple explanation: Like a robot that processes a whole list of tasks.

Real-life example: A program that processes a list of student grades and calculates the average.

School example: A program that prints a welcome message for each student in a list.

Home example: A program that prints all the items on a shopping list.

Nigerian example: A program that prints the name of each state in Nigeria.

Illustration:

    students = ["Aisha", "Chidi", "Bola"]
    for student in students:
        print("Welcome, " + student + "!")

    Output:
    Welcome, Aisha!
    Welcome, Chidi!
    Welcome, Bola!
            

Mini summary: Lists and loops together create powerful automation.


๐Ÿ“Œ Key Vocabulary

  • List: A container for multiple items.
  • Index: The position of an item in a list (starting at 0).
  • Append: Add an item to the end of a list.
  • Remove: Delete an item from a list.
  • Loop: Repeating code multiple times.
  • For loop: Repeats for each item in a sequence.
  • Range: Generates a sequence of numbers.
  • While loop: Repeats while a condition is true.
  • Break: Stops a loop early.
  • Continue: Skips an iteration.

๐Ÿง  Important Concepts

  • Lists hold many items: Use them to store collections of data.
  • Indexes start at 0: The first item is at position 0.
  • For loops process lists: They repeat for each item.
  • Range creates sequences: Use it to control how many times a loop runs.
  • Loops automate repetition: They do the work for you.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Create a Program that Processes a Shopping List

  1. Create a list: shopping_list = ["rice", "beans", "oil", "salt"]
  2. Loop through the list: for item in shopping_list:
  3. Print each item: print(item)
  4. Save and run: Save as shopping.py and run.

Example:

    Step 1: shopping_list = ["rice", "beans", "oil", "salt"]
    Step 2: for item in shopping_list:
    Step 3:     print(item)
    Step 4: Run the program!
            

๐ŸŒ Real-life Examples

  • Shopping List: shopping_list = ["rice", "beans", "oil"] then for item in shopping_list: print(item).
  • Student Names: students = ["Aisha", "Chidi", "Bola"] then for name in students: print("Hello, " + name).
  • Scores: scores = [85, 90, 78] then total = sum(scores).
  • Repeat Task: for i in range(5): print("Clean the room").
  • Countdown: for i in range(5, 0, -1): print(i) prints 5,4,3,2,1.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • States: states = ["Lagos", "Abuja", "Kano", "Kaduna"] then for state in states: print(state + " is a state in Nigeria").
  • Foods: foods = ["Jollof rice", "Egusi soup", "Pounded yam"] then for food in foods: print("I love " + food).
  • Cities: cities = ["Lagos", "Ibadan", "Enugu"] then for city in cities: print(city + " is a city in Nigeria").
  • Languages: languages = ["Yoruba", "Hausa", "Igbo"] then for lang in languages: print(lang + " is spoken in Nigeria").
  • Rivers: rivers = ["Niger", "Benue", "Cross River"] then for river in rivers: print(river + " is a river in Nigeria").

๐ŸŽˆ Fun Examples children can relate to

  • animals = ["cat", "dog", "rabbit"] then for animal in animals: print("I like " + animal).
  • games = ["football", "basketball", "tennis"] then for game in games: print("Let's play " + game).
  • colours = ["red", "blue", "green"] then for colour in colours: print("My favourite colour is " + colour).
  • fruits = ["apple", "banana", "orange"] then for fruit in fruits: print(fruit + " is delicious").
  • subjects = ["Math", "Science", "English"] then for subject in subjects: print("I study " + subject).

๐Ÿ  Everyday Examples

  • Chores: chores = ["sweep", "wash", "cook"] then for chore in chores: print("I need to " + chore).
  • Family: family = ["Mum", "Dad", "Sister"] then for member in family: print("Hello, " + member).
  • School: teachers = ["Mr. A", "Ms. B"] then for teacher in teachers: print("Good morning, " + teacher).
  • Food: meals = ["breakfast", "lunch", "dinner"] then for meal in meals: print("Time for " + meal).
  • Week: days = ["Monday", "Tuesday", "Wednesday"] then for day in days: print("Today is " + day).

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to create lists of things they use every day.
  • Use local examples to make it relatable.
  • Have students write programs that process lists.
  • Emphasise the power of loops for automation.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child create lists of family members, chores, or shopping items.
  • Write programs together that loop through lists.
  • Encourage them to think of tasks that can be automated.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Lists are used in almost every Python program.
  • Loops make automation possible.
  • Python can process millions of items in a list quickly.
  • Lists can hold any data type, including other lists.
  • Loops are used in every programming language.

๐Ÿ’ก Did You Know?

  • Did you know that you can create a list of lists?
  • Did you know that you can loop through a list and change items?
  • Did you know that range() can start at any number and step by any amount?
  • Did you know that you can break out of a loop when you find what you are looking for?
  • Did you know that loops are used in video games to process game states?

๐Ÿงท Remember This

  • Lists hold many items.
  • Indexes start at 0.
  • append() adds to the end.
  • remove() deletes by value.
  • for loops process each item.
  • range() generates numbers.
  • while loops repeat while true.
  • break stops a loop.
  • continue skips an iteration.

โš ๏ธ Common Mistakes

  • Index out of range: Accessing an index that doesn't exist.
  • Forgetting colons: for item in list: needs a colon.
  • Forgetting indentation: The loop body must be indented.
  • Infinite loops: A while loop that never stops.
  • Using remove() on an item not in the list.

โœ… Best Practices

  • Use descriptive list names: student_names instead of list1.
  • Make sure loops have a way to stop.
  • Use append() to add items.
  • Use len() to get list length.
  • Test loops with small lists first.

๐ŸŽจ Illustrations, Diagrams & Tables

List Operations

OperationExampleResult
Createfruits = ["apple", "banana"]["apple", "banana"]
Accessfruits[0]"apple"
Changefruits[1] = "mango"["apple", "mango"]
Addfruits.append("orange")["apple", "mango", "orange"]
Removefruits.remove("mango")["apple", "orange"]
Lengthlen(fruits)2

For Loop Flowchart

    +----------------------+
    | for item in list:    |
    +----------------------+
              |
              V
    +----------------------+
    | Execute block of code |
    +----------------------+
              |
              V
    +----------------------+
    | Any items left? ----> Yes ---> Loop again
    +----------------------+
              |
              No
              V
    +----------------------+
    | Exit loop            |
    +----------------------+
            

Comparison: For vs While

For LoopWhile Loop
Use when you know the number of iterationsUse when you don't know
Iterates over a sequenceIterates while a condition is true
for i in range(5):while i < 5:

๐Ÿ“ End-of-Module Summary

In this module, we learned about lists and loops. We discovered that lists can hold many items and that we can access, change, add, and remove items. We also learned about for loops and while loops, which allow us to repeat actions automatically. With lists and loops, we can process large amounts of data and automate repetitive tasks. Great work!

โ“ Frequently Asked Questions (10)

  1. What is a list? A container for multiple items.
  2. How do I access an item? list[index].
  3. What index does the first item have? 0.
  4. How do I add an item? list.append(item).
  5. How do I remove an item? list.remove(item).
  6. What is a for loop? A loop that repeats for each item.
  7. What is range()? Generates a sequence of numbers.
  8. What is a while loop? Repeats while a condition is true.
  9. What does break do? Stops a loop early.
  10. What does continue do? Skips an iteration.

๐Ÿ“‹ Review Questions (15)

  1. What is a list?
  2. How do you create a list?
  3. How do you access the first item in a list?
  4. What is the index of the first item?
  5. How do you add an item to the end of a list?
  6. How do you remove an item from a list?
  7. How do you find the number of items in a list?
  8. What is a for loop?
  9. What does range(5) do?
  10. What is a while loop?
  11. What does break do?
  12. What does continue do?
  13. How do you loop through a list?
  14. What is the output of for i in range(3): print(i)?
  15. What is the output of for i in range(2, 5): print(i)?

โœ๏ธ Fill-in-the-Blank Exercises

  1. A ______________ holds multiple items. (list)
  2. The first item in a list has an index of ______________. (0)
  3. Use ________ to add an item to the end of a list. (append)
  4. A for loop repeats for each item in a ______________. (list)
  5. range(5) generates numbers from 0 to ______________. (4)

โœ… True or False Exercises

  1. Lists can hold many items. (True)
  2. The index of the first item is 1. (False)
  3. append() adds an item to the beginning. (False)
  4. for loops repeat for each item. (True)
  5. while loops repeat while a condition is true. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is a list?
    a) A container for multiple items โœ…
    b) A single item
    c) A type of food
  2. What index does the first item have?
    a) 0 โœ…
    b) 1
    c) 2
  3. How do you add an item to the end?
    a) append() โœ…
    b) add()
    c) push()
  4. How do you remove an item?
    a) remove() โœ…
    b) delete()
    c) pop()
  5. How do you get the number of items?
    a) len() โœ…
    b) size()
    c) count()
  6. What does a for loop do?
    a) Repeats for each item โœ…
    b) Repeats forever
    c) Stops immediately
  7. What does range(5) generate?
    a) 0,1,2,3,4 โœ…
    b) 1,2,3,4,5
    c) 0,1,2,3,4,5
  8. What does a while loop do?
    a) Repeats while true โœ…
    b) Repeats forever
    c) Repeats once
  9. What does break do?
    a) Stops a loop โœ…
    b) Continues a loop
    c) Skips an iteration
  10. What does continue do?
    a) Skips an iteration โœ…
    b) Stops a loop
    c) Repeats forever
  11. How do you access the second item?
    a) list[1] โœ…
    b) list[2]
    c) list[0]
  12. Can lists hold different data types?
    a) Yes โœ…
    b) No
  13. What is the output of for i in range(3): print(i)?
    a) 0,1,2 โœ…
    b) 1,2,3
    c) 0,1,2,3
  14. What is the output of for i in range(2, 5): print(i)?
    a) 2,3,4 โœ…
    b) 2,3,4,5
    c) 3,4,5
  15. Can you loop through a list?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. ListA) Repeats while true
2. IndexB) A container for multiple items
3. appendC) Position of an item
4. for loopD) Adds an item to the end
5. while loopE) Repeats for each item

(Answers: 1-B, 2-C, 3-D, 4-E, 5-A)

๐Ÿ“ Short Answer Questions

  1. What is a list and how do you create one?
  2. What is the difference between a for loop and a while loop?
  3. Write a program that prints all items in a list of fruits.

๐ŸŽญ Scenario-based Exercises

Scenario 1: You have a list of student names. Write a program that prints "Hello, [name]!" for each student.

Scenario 2: You have a list of numbers. Write a program that calculates the total sum using a loop.

๐Ÿ‘ฅ Group Activity

In groups of 3, create a list of all the countries in Africa you can think of. Then write a program that prints each country and says "[country] is in Africa".

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Create a list of your favourite foods. Write a program that prints each food and says "I love [food]!"

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • What are some tasks you can automate with lists and loops?
  • How can loops make your life easier?
  • What other data structures would you like to learn?

๐Ÿ› ๏ธ Mini Project

Create a program that holds a list of your favourite movies. Use a loop to print each movie with a number (1, 2, 3, ...).

๐Ÿ“ Practical Assignment

Write a program that asks the user to enter 5 names and stores them in a list. Then loop through the list and print each name with "Welcome, [name]!".

๐Ÿ† Challenge Exercise

Write a program that creates a list of numbers from 1 to 10. Then use a loop to print only the even numbers.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-list, 2-0, 3-append, 4-list, 5-4

True/False: 1-T, 2-F, 3-F, 4-T, 5-T

Matching: 1-B, 2-C, 3-D, 4-E, 5-A

๐ŸŽ Key Takeaways

  • Lists store multiple items.
  • Indexes start at 0.
  • Use append() to add items.
  • Use remove() to delete items.
  • for loops repeat for each item.
  • while loops repeat while true.
  • break stops a loop.
  • continue skips an iteration.

๐Ÿš€ Preparation for the next module

In Module Four, we will learn about conditions and decision making. We will learn how to make our programs choose different paths based on conditions. Before the next session, think of a decision you make every day.

See you in Module Four! ๐ŸŽ‰


End of Module Three ยท Lists and Loops

6

Module Four

Module Four ยท Python for Automation

๐Ÿค” Module Four ยท Conditions and Decision Making


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Three, we learned about lists and loops. We learned how to repeat actions. But what if we need to make decisions? What if our program needs to choose between different options? That's where conditions come in.

In this module, we will learn about if statements โ€” a way to make decisions in code. We will learn how to compare values and take different actions based on the result. By the end of this module, you will be able to write programs that make decisions automatically.

๐ŸŽฏ Learning Objectives

  • Understand what conditions are and why they are important.
  • Use if, elif, and else statements.
  • Compare numbers and strings using comparison operators.
  • Use conditions to control the flow of your program.
  • Build programs that make decisions.

๐Ÿ“š Warm-up Story ยท Chioma's Grade Checker

Chioma is a student in Ibadan. She wanted to know if she passed her exams. She had to check each subject and see if her score was above 50. It was boring and tiring.

Her friend told her about Python conditions. Chioma wrote: score = 65. Then she wrote: if score >= 50: print("You passed!") else: print("You failed."). Python told her she passed! Chioma was so happy. Now she uses Python to check all her grades.

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is a Condition?

Definition: A condition is a statement that can be true or false. It is used to make decisions in a program.

Why important: Conditions allow programs to choose different paths.

Simple explanation: Like asking a question that has a yes/no answer.

Real-life example: "Is it raining?" If yes, take an umbrella.

School example: "Did you pass the test?" If yes, celebrate.

Home example: "Is dinner ready?" If yes, eat.

Nigerian example: "Is it market day?" If yes, go to the market.

Illustration:

    Condition: Is it true?
    Answer: Yes or No
            

Mini summary: A condition is a true/false question.


Lesson 2 ยท Comparison Operators

Definition: Comparison operators are symbols used to compare values. They return True or False.

Why important: They are used to write conditions.

Simple explanation: Like comparing two numbers to see which is bigger.

Real-life example: 5 > 3 is True.

School example: score >= 50 checks if score is at least 50.

Home example: age == 10 checks if age is 10.

Nigerian example: price < 1000 checks if price is less than 1000.

Illustration:

    Comparison Operators:
    ==  equal to
    !=  not equal to
    >   greater than
    <   less than
    >=  greater than or equal to
    <=  less than or equal to
            

Mini summary: Comparison operators compare values.


Lesson 3 ยท The If Statement

Definition: The if statement is used to run code only if a condition is true.

Why important: This is how you make decisions in Python.

Simple explanation: If something is true, do something.

Real-life example: if age >= 18: print("You can vote").

School example: if score >= 50: print("Pass").

Home example: if weather == "rainy": print("Take an umbrella").

Nigerian example: if city == "Lagos": print("Lagos is in Nigeria").

Illustration:

    age = 18
    if age >= 18:
        print("You can vote.")

    Output: You can vote.
            

Mini summary: if runs code only when the condition is true.


Lesson 4 ยท The Else Statement

Definition: The else statement is used with if to run code when the condition is false.

Why important: This allows you to handle both true and false cases.

Simple explanation: If something is true, do A. Otherwise, do B.

Real-life example: if age >= 18: print("You can vote") else: print("You are too young").

School example: if score >= 50: print("Pass") else: print("Fail").

Home example: if weather == "rainy": print("Take umbrella") else: print("Enjoy the sun").

Nigerian example: if city == "Lagos": print("Lagos is in Nigeria") else: print("Not in Nigeria").

Illustration:

    age = 15
    if age >= 18:
        print("You can vote.")
    else:
        print("You are too young.")

    Output: You are too young.
            

Mini summary: else runs code when the condition is false.


Lesson 5 ยท The Elif Statement

Definition: elif (short for "else if") is used to check multiple conditions.

Why important: This allows you to handle many different cases.

Simple explanation: If condition 1 is true, do A. Else if condition 2 is true, do B. Otherwise, do C.

Real-life example: if grade >= 90: print("A") elif grade >= 80: print("B") else: print("C").

School example: A grading system with A, B, C, D.

Home example: if day == "Monday": print("Start the week") elif day == "Friday": print("TGIF") else: print("Midweek").

Nigerian example: if state == "Lagos": print("South-West") elif state == "Kano": print("North-West") else: print("Other").

Illustration:

    score = 85
    if score >= 90:
        print("A")
    elif score >= 80:
        print("B")
    elif score >= 70:
        print("C")
    else:
        print("D")

    Output: B
            

Mini summary: elif checks multiple conditions.


Lesson 6 ยท Comparing Strings

Definition: You can compare strings using == and !=. You can also use in to check if a string contains another string.

Why important: This allows you to make decisions based on text.

Simple explanation: Like checking if a word is in a sentence.

Real-life example: if name == "Aisha": print("Hello Aisha").

School example: if subject == "Math": print("It's math time").

Home example: if food == "rice": print("I love rice").

Nigerian example: if city == "Abuja": print("Abuja is the capital").

Illustration:

    name = "Chidi"
    if name == "Chidi":
        print("Hello, Chidi!")

    Output: Hello, Chidi!
            

Mini summary: Compare strings with == and !=.


Lesson 7 ยท Logical Operators

Definition: Logical operators combine conditions. The main ones are and, or, and not.

Why important: This allows you to create complex conditions.

Simple explanation: Like saying "and", "or", and "not" in a sentence.

Real-life example: if age >= 18 and citizen == True: print("Can vote").

School example: if score >= 50 and score < 100: print("Pass").

Home example: if day == "Saturday" or day == "Sunday": print("Weekend").

Nigerian example: if city == "Lagos" or city == "Abuja": print("Big city").

Illustration:

    age = 20
    citizen = True
    if age >= 18 and citizen:
        print("You can vote.")

    Output: You can vote.
            

Mini summary: and, or, and not combine conditions.


Lesson 8 ยท The In Operator

Definition: The in operator checks if an item is in a list or a string.

Why important: This is useful for checking membership.

Simple explanation: Like checking if an item is on a list.

Real-life example: if "apple" in fruits: print("Apple is in the list").

School example: if "Aisha" in students: print("Aisha is in the class").

Home example: if "rice" in shopping_list: print("Buy rice").

Nigerian example: if "Lagos" in states: print("Lagos is a state").

Illustration:

    fruits = ["apple", "banana", "orange"]
    if "banana" in fruits:
        print("Banana is in the list.")

    Output: Banana is in the list.
            

Mini summary: in checks if an item is in a list or string.


Lesson 9 ยท Nested If Statements

Definition: You can put an if statement inside another if statement. This is called a nested if.

Why important: This allows you to check multiple levels of conditions.

Simple explanation: Like asking a question and then asking another question based on the first answer.

Real-life example: if age >= 18: if citizen: print("Can vote").

School example: if score >= 50: if score >= 90: print("A") else: print("Pass").

Home example: if weather == "rainy": if have_umbrella: print("Go out") else: print("Stay inside").

Nigerian example: if state == "Lagos": if capital == "Ikeja": print("Correct").

Illustration:

    age = 20
    citizen = True
    if age >= 18:
        if citizen:
            print("You can vote.")
        else:
            print("You are not a citizen.")
    else:
        print("You are too young.")

    Output: You can vote.
            

Mini summary: Nested if statements check conditions inside conditions.


Lesson 10 ยท Using Conditions with Loops

Definition: You can use conditions inside loops to make decisions while repeating.

Why important: This allows you to process data and make decisions automatically.

Simple explanation: Like checking each item in a list and deciding what to do with it.

Real-life example: for score in scores: if score >= 50: print("Pass") else: print("Fail").

School example: Processing grades and printing pass/fail.

Home example: Checking each chore on a list and printing "Done" or "Not done".

Nigerian example: for city in cities: if city in states: print(city + " is a state").

Illustration:

    scores = [85, 45, 78, 92]
    for score in scores:
        if score >= 50:
            print("Pass")
        else:
            print("Fail")

    Output:
    Pass
    Fail
    Pass
    Pass
            

Mini summary: Use conditions inside loops to process data.


Lesson 11 ยท Making Decisions in Automation

Definition: Automation often involves making decisions. Conditions allow programs to make those decisions automatically.

Why important: This is how you build smart automation tools.

Simple explanation: Like a robot that checks something and decides what to do.

Real-life example: A program that checks if a file exists and renames it.

School example: A program that checks if a student's grade is high enough.

Home example: A program that checks if it's time to water the plants.

Nigerian example: A program that checks if the market is open.

Illustration:

    temp = 30
    if temp > 35:
        print("It's hot, stay inside.")
    elif temp > 20:
        print("It's nice weather.")
    else:
        print("It's cold, wear a jacket.")
            

Mini summary: Conditions make automation smart.


Lesson 12 ยท Putting It All Together

Definition: You can combine variables, lists, loops, and conditions to build powerful programs.

Why important: This is how you build real-world applications.

Simple explanation: Like putting all the pieces together to build something amazing.

Real-life example: A program that processes a list of students and calculates their grades.

School example: A program that takes a list of numbers and prints the even ones.

Home example: A program that checks a shopping list and prints what you need.

Nigerian example: A program that checks a list of states and prints the ones in the South.

Illustration:

    students = [("Aisha", 85), ("Chidi", 45), ("Bola", 78)]
    for name, score in students:
        if score >= 50:
            print(name + " passed.")
        else:
            print(name + " failed.")

    Output:
    Aisha passed.
    Chidi failed.
    Bola passed.
            

Mini summary: Combine concepts to build powerful programs.


Lesson 13 ยท You Are Making Great Progress!

Definition: You have learned about variables, lists, loops, and conditions. This is a big achievement.

Why important: You are building the foundation for automation.

Simple explanation: You are becoming a real Python coder!

Real-life example: You can now write programs that make decisions.

School example: You can automate grading and other tasks.

Home example: You can automate chores and reminders.

Nigerian example: You are becoming a Python coder in Nigeria!

Illustration:

    You ๐Ÿง‘โ€๐Ÿ’ป  โ†’  Write Code  โ†’  Run  โ†’  Computer Works!
    You are making great progress! ๐ŸŽ‰
            

Mini summary: You are making great progress. Keep going!


๐Ÿ“Œ Key Vocabulary

  • Condition: A true/false statement.
  • If statement: Runs code if a condition is true.
  • Else statement: Runs code if a condition is false.
  • Elif statement: Checks multiple conditions.
  • Comparison operator: Compares values (>, <, ==, etc.).
  • Logical operator: Combines conditions (and, or, not).
  • Nested if: An if inside another if.
  • Decision making: Choosing between options.
  • Automation: Making the computer do work.
  • Control flow: The order in which code runs.

๐Ÿง  Important Concepts

  • Conditions are true/false: They control the flow of your program.
  • If, elif, else: These allow you to make decisions.
  • Comparison operators: Used to compare values.
  • Logical operators: Combine conditions.
  • Decision making: Programs that choose different paths.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Write a Program that Checks if a Number is Even or Odd

  1. Get a number: num = int(input("Enter a number: "))
  2. Check if it's even: if num % 2 == 0:
  3. Print even message: print("Even")
  4. Else print odd: else: print("Odd")
  5. Save and run: Save as even_odd.py and run.

Example:

    Step 1: num = int(input("Enter a number: "))
    Step 2: if num % 2 == 0:
    Step 3:     print("Even")
    Step 4: else:
    Step 5:     print("Odd")
    Step 6: Run the program!
            

๐ŸŒ Real-life Examples

  • Grade Check: if score >= 50: print("Pass") else: print("Fail")
  • Voting: if age >= 18: print("Can vote") else: print("Too young")
  • Weather: if temp > 30: print("Hot") else: print("Cool")
  • Login: if username == "admin" and password == "1234": print("Welcome")
  • Shopping: if item in shopping_list: print("Buy it")

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • City: if city == "Lagos": print("Lagos is in South-West") elif city == "Kano": print("Kano is in North-West")
  • Food: if food == "Jollof rice": print("I love Jollof") elif food == "Egusi": print("I love Egusi")
  • State: if state == "Lagos": print("State in Nigeria") else: print("Not a Nigerian state")
  • Language: if language == "Yoruba": print("South-West") elif language == "Hausa": print("North")
  • Currency: if amount > 1000: print("Expensive") else: print("Affordable")

๐ŸŽˆ Fun Examples children can relate to

  • age = 10 then if age >= 18: print("Adult") else: print("Child")
  • day = "Monday" then if day == "Saturday" or day == "Sunday": print("Weekend") else: print("School day")
  • favourite_food = "pizza" then if favourite_food == "pizza": print("I love pizza!")
  • score = 90 then if score >= 80: print("Great job!")
  • game = "football" then if game == "football": print("Let's play football!")

๐Ÿ  Everyday Examples

  • Morning: if time < 12: print("Good morning") else: print("Good afternoon")
  • Chores: if chore == "done": print("Great work") else: print("Do it now")
  • Weather: if weather == "rainy": print("Take umbrella") else: print("Enjoy the sun")
  • Food: if meal == "breakfast": print("It's breakfast time")
  • Homework: if homework_done == True: print("Good job") else: print("Finish your homework")

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to write programs that make decisions.
  • Use local examples to make it relatable.
  • Have students create grading programs.
  • Emphasise the importance of conditions in automation.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child create programs that make decisions.
  • Write programs together that check ages or scores.
  • Encourage them to think of decisions they can automate.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Conditions are used in every program.
  • Decision making is a core part of AI.
  • Python can compare almost anything.
  • Conditions can be combined in many ways.
  • Automation relies heavily on decision making.

๐Ÿ’ก Did You Know?

  • Did you know that you can compare strings in Python?
  • Did you know that and and or can combine many conditions?
  • Did you know that you can have multiple elif statements?
  • Did you know that conditions are used in web development, games, and AI?
  • Did you know that you can use in to check if an item is in a list?

๐Ÿงท Remember This

  • Conditions are true/false.
  • if runs code when true.
  • elif checks more conditions.
  • else runs when all are false.
  • Use ==, !=, >, <, >=, <= to compare.
  • Use and, or, not to combine.

โš ๏ธ Common Mistakes

  • Using = instead of ==: if age = 18 is wrong. Use ==.
  • Forgetting colons: if age > 18 needs a colon: if age > 18:.
  • Forgetting indentation: The code inside if must be indented.
  • Not using elif: Using many if statements when elif is better.
  • Mixing up and and or: Make sure you use the right one.

โœ… Best Practices

  • Use elif for multiple conditions.
  • Use and and or carefully.
  • Use in to check membership in lists.
  • Use parentheses to make complex conditions clear.
  • Test your conditions with different inputs.

๐ŸŽจ Illustrations, Diagrams & Tables

If Statement Flowchart

    +----------------------+
    | Condition            |
    +----------------------+
              |
              V
    +----------------------+
    | Is it True?          |
    +----------------------+
              |
       Yes ---+--- No
        |          |
        V          V
    +--------+  +--------+
    | Do A   |  | Do B   |
    +--------+  +--------+
            

Comparison Operators

OperatorMeaningExample
==Equal to5 == 5 is True
!=Not equal to5 != 3 is True
>Greater than5 > 3 is True
<Less than3 < 5 is True
>=Greater than or equal to5 >= 5 is True
<=Less than or equal to3 <= 5 is True

If-Elif-Else Structure

    if condition1:
        # code block 1
    elif condition2:
        # code block 2
    elif condition3:
        # code block 3
    else:
        # code block 4
            

๐Ÿ“ End-of-Module Summary

In this module, we learned about conditions and decision making. We discovered that conditions are true/false statements that control the flow of our programs. We learned about if, elif, and else statements, as well as comparison and logical operators. We also learned how to use conditions with loops to process data. With these skills, you can now write programs that make decisions automatically. Great work!

โ“ Frequently Asked Questions (10)

  1. What is a condition? A true/false statement.
  2. What does if do? Runs code when true.
  3. What does else do? Runs code when false.
  4. What does elif do? Checks more conditions.
  5. What is ==? Checks if two values are equal.
  6. What is !=? Checks if two values are not equal.
  7. What does and do? Combines conditions (both must be true).
  8. What does or do? Combines conditions (one must be true).
  9. What does in do? Checks if an item is in a list or string.
  10. Can I use conditions in loops? Yes, and it's very useful.

๐Ÿ“‹ Review Questions (15)

  1. What is a condition?
  2. What does if do?
  3. What does else do?
  4. What does elif do?
  5. What is the difference between == and =?
  6. What does != mean?
  7. What does > do?
  8. What does < do?
  9. What does and do?
  10. What does or do?
  11. What does not do?
  12. What does in do?
  13. How do you write an if statement?
  14. How do you write an if-else statement?
  15. How do you write an if-elif-else statement?

โœ๏ธ Fill-in-the-Blank Exercises

  1. A ______________ is a true/false statement. (condition)
  2. The if statement runs code when the condition is ______________. (true)
  3. The else statement runs code when the condition is ______________. (false)
  4. == checks if two values are ______________. (equal)
  5. and combines conditions and requires ______________ to be true. (both)

โœ… True or False Exercises

  1. Conditions are true/false statements. (True)
  2. if runs code when false. (False)
  3. else runs code when true. (False)
  4. == checks if values are equal. (True)
  5. and requires both conditions to be true. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is a condition?
    a) A true/false statement โœ…
    b) A type of loop
    c) A variable
  2. What does if do?
    a) Runs code when true โœ…
    b) Runs code when false
    c) Runs code always
  3. What does else do?
    a) Runs code when true
    b) Runs code when false โœ…
    c) Runs code always
  4. What does elif do?
    a) Checks more conditions โœ…
    b) Stops the program
    c) Runs code always
  5. What does == do?
    a) Checks if equal โœ…
    b) Assigns a value
    c) Checks if greater
  6. What does != do?
    a) Checks if not equal โœ…
    b) Checks if equal
    c) Assigns a value
  7. What does and do?
    a) Combines conditions (both true) โœ…
    b) Combines conditions (one true)
    c) Negates a condition
  8. What does or do?
    a) Combines conditions (both true)
    b) Combines conditions (one true) โœ…
    c) Negates a condition
  9. What does in do?
    a) Checks if an item is in a list โœ…
    b) Checks if items are equal
    c) Checks if items are greater
  10. What is the output of if 5 > 3: print("True")?
    a) True โœ…
    b) False
    c) Nothing
  11. What is the output of if 5 < 3: print("True") else: print("False")?
    a) True
    b) False โœ…
    c) Nothing
  12. What is the output of if 5 == 5: print("Equal")?
    a) Equal โœ…
    b) Not Equal
    c) Nothing
  13. What is the output of if 5 != 3: print("Not Equal")?
    a) Not Equal โœ…
    b) Equal
    c) Nothing
  14. Can you use in with strings?
    a) Yes โœ…
    b) No
  15. Can you use conditions with loops?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. ifA) Runs code when false
2. elseB) Runs code when true
3. elifC) Checks equality
4. ==D) Checks more conditions
5. andE) Combines conditions (both true)

(Answers: 1-B, 2-A, 3-D, 4-C, 5-E)

๐Ÿ“ Short Answer Questions

  1. What is the difference between if and else?
  2. What is the difference between == and =?
  3. Write a program that checks if a number is even or odd.

๐ŸŽญ Scenario-based Exercises

Scenario 1: You want to write a program that asks for a user's age and tells them if they can vote (age >= 18). Write the code.

Scenario 2: You have a list of student scores. Write a program that prints "Pass" for scores >= 50 and "Fail" for scores < 50.

๐Ÿ‘ฅ Group Activity

In groups of 3, create a program that asks for a grade (0-100) and prints the letter grade (A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: below 60).

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Create a program that asks for a number and prints "Even" if it's even, "Odd" if it's odd, and "Zero" if it's 0.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • How can conditions be used in automation?
  • What are some examples of decisions programs can make?
  • Why is decision making important in programming?

๐Ÿ› ๏ธ Mini Project

Create a program that asks for a user's name and age. If the age is 18 or older, print "Welcome, [name]! You can vote." Otherwise, print "Sorry, [name]. You are too young to vote."

๐Ÿ“ Practical Assignment

Write a program that takes a list of numbers and prints only the numbers that are greater than 10.

๐Ÿ† Challenge Exercise

Write a program that asks for a number and prints "Positive" if it's > 0, "Negative" if it's < 0, and "Zero" if it's 0.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-condition, 2-true, 3-false, 4-equal, 5-both

True/False: 1-T, 2-F, 3-F, 4-T, 5-T

Matching: 1-B, 2-A, 3-D, 4-C, 5-E

๐ŸŽ Key Takeaways

  • Conditions are true/false statements.
  • if, elif, and else control the flow of your program.
  • Comparison operators compare values.
  • Logical operators combine conditions.
  • Use conditions with loops to process data automatically.

๐Ÿš€ Preparation for the next module

In Module Five, we will learn about functions โ€” how to write reusable code that you can call again and again. Before the next session, think of a task you do repeatedly.

See you in Module Five! ๐ŸŽ‰


End of Module Four ยท Conditions and Decision Making

7

Module Five

Module Five ยท Python for Automation

๐Ÿ”ง Module Five ยท Functions


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Four, we learned about conditions and decision making. We learned how to make our programs choose different paths. But what if we need to repeat a block of code in many different places? Writing the same code again and again is boring and wastes time. That's where functions come in.

In this module, we will learn about functions โ€” reusable blocks of code that you can call whenever you need them. Functions make your code organised, reusable, and easier to understand. By the end of this module, you will be able to write your own functions and use them in your programs.

๐ŸŽฏ Learning Objectives

  • Understand what functions are and why they are useful.
  • Define and call your own functions.
  • Use parameters to make functions flexible.
  • Return values from functions.
  • Build reusable code for automation.

๐Ÿ“š Warm-up Story ยท Ade's Greeting Function

Ade is a teacher in Ibadan. Every morning, he greeted each student individually. He said "Good morning, Aisha!", "Good morning, Chidi!", and so on. It took him a long time.

His friend told him about Python functions. Ade wrote: def greet(name): print("Good morning, " + name + "!"). Then he called: greet("Aisha"), greet("Chidi"). Python did all the greetings for him. Ade saved time and energy.

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is a Function?

Definition: A function is a reusable block of code that performs a specific task.

Why important: Functions help you avoid repeating code. They make your code organised and easy to read.

Simple explanation: Like a recipe. You write it once, and you can use it many times.

Real-life example: print() is a function that shows text on the screen.

School example: A function that calculates the average of a list of numbers.

Home example: A function that makes a cup of tea (you follow the same steps every time).

Nigerian example: A function that prepares Jollof rice (same steps, different quantities).

Illustration:

    +----------------------+
    |  def greet(name):    |
    |    print("Hello " + name) |
    +----------------------+
              |
              V
    +----------------------+
    |  greet("Aisha") โ†’ "Hello Aisha" |
    |  greet("Chidi") โ†’ "Hello Chidi" |
    +----------------------+
            

Mini summary: Functions are reusable blocks of code.


Lesson 2 ยท Defining a Function

Definition: You define a function using the def keyword, followed by the function name and parentheses ().

Why important: This is how you create your own functions.

Simple explanation: Like writing a recipe in a cookbook.

Real-life example: def say_hello(): print("Hello!")

School example: def welcome(): print("Welcome to class!")

Home example: def clean_room(): print("Cleaning room...")

Nigerian example: def greet_yoruba(): print("แบธ kรกร bแปฬ€!")

Illustration:

    def say_hello():
        print("Hello, world!")

    # This creates a function called say_hello
            

Mini summary: Use def to define a function.


Lesson 3 ยท Calling a Function

Definition: Calling a function means running the code inside it. You call a function by writing its name with parentheses.

Why important: This is how you use the function.

Simple explanation: Like following a recipe.

Real-life example: say_hello() runs the function.

School example: welcome() runs the welcome function.

Home example: clean_room() runs the cleaning function.

Nigerian example: greet_yoruba() runs the greeting function.

Illustration:

    def say_hello():
        print("Hello, world!")

    say_hello()  # This calls the function
    # Output: Hello, world!
            

Mini summary: Call a function by writing its name with ().


Lesson 4 ยท Parameters

Definition: Parameters are variables that you pass to a function. They make functions flexible.

Why important: Parameters allow you to use the same function with different values.

Simple explanation: Like adding different ingredients to a recipe.

Real-life example: def greet(name): print("Hello, " + name).

School example: def grade(score): if score >= 50: print("Pass").

Home example: def make_tea(type): print("Making " + type + " tea").

Nigerian example: def welcome(city): print("Welcome to " + city).

Illustration:

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

    greet("Aisha")  # Hello, Aisha
    greet("Chidi")  # Hello, Chidi
            

Mini summary: Parameters are variables that you pass to a function.


Lesson 5 ยท Multiple Parameters

Definition: You can have multiple parameters by separating them with commas.

Why important: This makes functions even more flexible.

Simple explanation: Like a recipe that needs multiple ingredients.

Real-life example: def add(a, b): return a + b.

School example: def average(score1, score2): return (score1 + score2) / 2.

Home example: def make_sandwich(bread, filling): print("Making a " + filling + " sandwich with " + bread).

Nigerian example: def greet(name, city): print("Hello, " + name + " from " + city).

Illustration:

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

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

Mini summary: Use commas to have multiple parameters.


Lesson 6 ยท Return Values

Definition: A function can return a value using the return statement. The value can be used in the rest of the program.

Why important: This allows functions to produce results that you can use.

Simple explanation: Like getting a result from a calculation.

Real-life example: def add(a, b): return a + b.

School example: def average(scores): return sum(scores) / len(scores).

Home example: def square(number): return number * number.

Nigerian example: def convert_to_naira(dollar): return dollar * 1600.

Illustration:

    def square(number):
        return number * number

    result = square(5)
    print(result)  # 25
            

Mini summary: Use return to send a value back.


Lesson 7 ยท Using Functions in Automation

Definition: Functions are very useful for automation. You can write a function once and use it many times.

Why important: This saves time and makes your code clean.

Simple explanation: Like a machine that does a task automatically.

Real-life example: A function that calculates tax for different amounts.

School example: A function that calculates the average of a list of grades.

Home example: A function that converts between units.

Nigerian example: A function that converts Naira to dollars.

Illustration:

    def calculate_tax(amount):
        tax = amount * 0.1
        return tax

    price = 1000
    tax = calculate_tax(price)
    print("Tax: " + str(tax))  # Tax: 100.0
            

Mini summary: Functions are powerful tools for automation.


Lesson 8 ยท Default Parameter Values

Definition: You can set default values for parameters. If the user doesn't provide a value, the default is used.

Why important: This makes functions easier to use.

Simple explanation: Like a default setting on a device.

Real-life example: def greet(name="Friend"): print("Hello, " + name).

School example: def pass_mark(mark=50): print("Pass mark is " + str(mark)).

Home example: def make_tea(type="green"): print("Making " + type + " tea").

Nigerian example: def welcome(city="Nigeria"): print("Welcome to " + city).

Illustration:

    def greet(name="Friend"):
        print("Hello, " + name)

    greet()          # Hello, Friend
    greet("Aisha")   # Hello, Aisha
            

Mini summary: Default parameters provide a fallback value.


Lesson 9 ยท Functions with Conditions

Definition: You can use conditions inside functions to make decisions.

Why important: This makes your functions smarter.

Simple explanation: Like a recipe that changes based on what you have.

Real-life example: def check_age(age): if age >= 18: print("Adult") else: print("Child").

School example: def grade(score): if score >= 50: return "Pass" else: return "Fail".

Home example: def is_weekend(day): if day == "Saturday" or day == "Sunday": return True else: return False.

Nigerian example: def region(state): if state == "Lagos": return "South-West" else: return "Other".

Illustration:

    def grade(score):
        if score >= 50:
            return "Pass"
        else:
            return "Fail"

    print(grade(75))  # Pass
    print(grade(45))  # Fail
            

Mini summary: Use conditions inside functions to make decisions.


Lesson 10 ยท Functions with Loops

Definition: You can use loops inside functions to process data.

Why important: This allows you to automate repetitive tasks.

Simple explanation: Like a machine that processes a list of items.

Real-life example: def sum_list(numbers): total = 0; for num in numbers: total += num; return total.

School example: def average(numbers): total = sum(numbers); return total / len(numbers).

Home example: def print_shopping_list(items): for item in items: print(item).

Nigerian example: def print_states(states): for state in states: print(state + " is in Nigeria").

Illustration:

    def sum_list(numbers):
        total = 0
        for num in numbers:
            total += num
        return total

    print(sum_list([1, 2, 3, 4, 5]))  # 15
            

Mini summary: Use loops inside functions to process data.


Lesson 11 ยท Organising Code with Functions

Definition: Functions help you organise your code into logical parts.

Why important: Well-organised code is easier to read, debug, and maintain.

Simple explanation: Like organising a toolbox with different compartments.

Real-life example: A program with separate functions for input, processing, and output.

School example: A program with a function for each task.

Home example: A program with a function for each family member.

Nigerian example: A program with a function for each state.

Illustration:

    def get_input():
        # gets input from user

    def process_data(data):
        # processes the data

    def show_output(result):
        # shows the result
            

Mini summary: Functions organise your code.


Lesson 12 ยท Reusing Functions

Definition: Once you write a function, you can use it in any program.

Why important: This saves you from rewriting code.

Simple explanation: Like sharing a recipe with a friend.

Real-life example: You write a function to calculate tax and use it in many projects.

School example: You write a function to calculate the average and use it for different classes.

Home example: You write a function to convert units and use it for different recipes.

Nigerian example: You write a function to greet in Yoruba and use it in different programs.

Illustration:

    # In one program
    def add(a, b):
        return a + b

    # In another program
    result = add(10, 20)  # 30
            

Mini summary: Reuse functions in different programs.


Lesson 13 ยท Functions and Scope

Definition: Scope is where a variable exists. Variables inside a function are local โ€” they exist only inside that function.

Why important: This helps prevent conflicts between variables.

Simple explanation: Like each person having their own name tag.

Real-life example: A variable inside a function is separate from a variable outside.

School example: def my_function(): x = 10 โ€” x only exists inside.

Home example: def clean_room(): room = "living room" โ€” room only exists inside.

Nigerian example: def greet(): message = "Hello" โ€” message only exists inside.

Illustration:

    def my_function():
        x = 10
        print(x)  # Works

    my_function()
    print(x)  # Error! x does not exist outside
            

Mini summary: Variables inside functions are local.


Lesson 14 ยท Documenting Functions

Definition: You can add a docstring (a description) to a function to explain what it does.

Why important: Documentation helps you and others understand the function.

Simple explanation: Like writing a note to explain something.

Real-life example: def add(a, b): """Adds two numbers.""" return a + b

School example: def average(scores): """Returns the average of a list."""

Home example: def make_tea(): """Makes a cup of tea."""

Nigerian example: def greet(name): """Greets a person."""

Illustration:

    def add(a, b):
        """Adds two numbers and returns the result."""
        return a + b
            

Mini summary: Document your functions with docstrings.


Lesson 15 ยท You Are Ready!

Definition: You have learned the most important concepts: variables, lists, loops, conditions, and functions.

Why important: You are now ready to start building real automation projects.

Simple explanation: You have all the tools you need.

Real-life example: You can now write programs that automate tasks.

School example: You can automate grading and reports.

Home example: You can automate chores and reminders.

Nigerian example: You are a Python coder ready to solve problems!

Illustration:

    Variables + Lists + Loops + Conditions + Functions = Automation
    You are ready! ๐ŸŽ‰
            

Mini summary: You are ready to build automation projects!


๐Ÿ“Œ Key Vocabulary

  • Function: A reusable block of code.
  • Define: To create a function using def.
  • Call: To run a function.
  • Parameter: A variable passed to a function.
  • Return: To send a value back.
  • Default parameter: A parameter with a default value.
  • Scope: Where a variable exists.
  • Docstring: A description of a function.
  • Reusable: Can be used multiple times.
  • Organised: Code that is neat and easy to understand.

๐Ÿง  Important Concepts

  • Functions are reusable: Write once, use many times.
  • Parameters add flexibility: Pass different values.
  • Return values produce results: Use the output of a function.
  • Functions organise code: Keeps your code clean.
  • Functions are the building blocks of automation.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Write and Use a Function

  1. Define the function: def greet(name):
  2. Write the code: print("Hello, " + name)
  3. Call the function: greet("Aisha")
  4. Use the result: If it returns a value, store it in a variable.

Example:

    Step 1: def greet(name):
    Step 2:     print("Hello, " + name)
    Step 3: greet("Aisha")  # Output: Hello, Aisha
            

๐ŸŒ Real-life Examples

  • Greeting: def greet(name): print("Hello, " + name)
  • Math: def add(a, b): return a + b
  • Average: def average(numbers): return sum(numbers) / len(numbers)
  • Tax: def calculate_tax(amount): return amount * 0.1
  • Conversion: def celsius_to_fahrenheit(c): return c * 9/5 + 32

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Greeting Yoruba: def greet_yoruba(name): print("แบธ kรกร bแปฬ€, " + name)
  • Naira to Dollar: def naira_to_dollar(naira): return naira / 1600
  • State Check: def region(state): if state == "Lagos": return "South-West" else: return "Other"
  • Food: def make_jollof(rice, chicken): print("Making Jollof rice with " + chicken)
  • City: def is_lagos(city): return city == "Lagos"

๐ŸŽˆ Fun Examples children can relate to

  • def say_hello(): print("Hello, world!")
  • def square(number): return number * number
  • def favourite_food(food): print("I love " + food)
  • def is_even(number): return number % 2 == 0
  • def birthday(name): print("Happy Birthday, " + name)

๐Ÿ  Everyday Examples

  • Cleaning: def clean_room(room): print("Cleaning " + room)
  • Cooking: def make_tea(type="green"): print("Making " + type + " tea")
  • Homework: def check_homework(done): if done: print("Great job") else: print("Do it now")
  • Chores: def do_chore(chore): print("Doing " + chore)
  • Reminder: def remind(task): print("Reminder: " + task)

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to write functions for repetitive tasks.
  • Use local examples to make it relatable.
  • Have students create functions that calculate averages, greet people, etc.
  • Emphasise the power of reusing code.
  • Celebrate every function they write.

๐Ÿ‘ช Parent Tips

  • Help your child write functions for everyday tasks.
  • Write programs together that use functions.
  • Encourage them to think of tasks that can be automated.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Functions are used in every programming language.
  • Python has many built-in functions like print() and len().
  • Functions make code easier to test.
  • Functions help you organise large programs.
  • Good programmers write functions for every task.

๐Ÿ’ก Did You Know?

  • Did you know that you can call a function inside another function?
  • Did you know that functions can have default parameters?
  • Did you know that functions can return multiple values?
  • Did you know that you can pass any data type to a function?
  • Did you know that functions are the building blocks of automation?

๐Ÿงท Remember This

  • Functions are reusable blocks of code.
  • Use def to define a function.
  • Call a function by writing its name with ().
  • Parameters pass values to functions.
  • Return values send results back.

โš ๏ธ Common Mistakes

  • Forgetting colons: def greet() needs a colon: def greet():
  • Forgetting indentation: The code inside the function must be indented.
  • Not returning a value: Forgetting to use return when needed.
  • Using a variable that doesn't exist: The parameter name must match.
  • Calling a function with the wrong number of arguments.

โœ… Best Practices

  • Use descriptive function names.
  • Add docstrings to explain the function.
  • Keep functions short and focused.
  • Use parameters to make functions flexible.
  • Test functions with different inputs.

๐ŸŽจ Illustrations, Diagrams & Tables

Function Structure

    +----------------------+
    | def function_name(parameters): |
    |    # code block      |
    |    return result     |
    +----------------------+
            

Function Example

FunctionInputOutput
add(a, b)5, 38
greet(name)"Aisha""Hello, Aisha"
square(n)416

Comparison: With and Without Functions

Without FunctionsWith Functions
Repeated codeOne function used many times
Hard to readEasy to read
Hard to changeEasy to change
Long programsShort programs

๐Ÿ“ End-of-Module Summary

In this module, we learned about functions. We discovered that functions are reusable blocks of code that help us avoid repetition. We learned how to define functions, call them, use parameters, and return values. We also learned about default parameters, scope, and documenting functions. Functions are a powerful tool for automation. With functions, you can write clean, organised, and reusable code. Great work!

โ“ Frequently Asked Questions (10)

  1. What is a function? A reusable block of code.
  2. How do you define a function? def function_name():
  3. How do you call a function? function_name()
  4. What are parameters? Variables passed to a function.
  5. What does return do? Sends a value back.
  6. What is a default parameter? A parameter with a default value.
  7. What is scope? Where a variable exists.
  8. What is a docstring? A description of a function.
  9. Why are functions useful? They make code reusable and organised.
  10. Can functions be used in automation? Yes, they are essential.

๐Ÿ“‹ Review Questions (15)

  1. What is a function?
  2. How do you define a function?
  3. How do you call a function?
  4. What are parameters?
  5. What does return do?
  6. What is a default parameter?
  7. What is scope?
  8. What is a docstring?
  9. Why are functions useful?
  10. How do you pass multiple parameters?
  11. How do you return a value?
  12. What is the difference between a parameter and an argument?
  13. Can you use conditions inside functions?
  14. Can you use loops inside functions?
  15. What is the keyword to define a function?

โœ๏ธ Fill-in-the-Blank Exercises

  1. A ______________ is a reusable block of code. (function)
  2. Use the ________ keyword to define a function. (def)
  3. Call a function by writing its name with ______________. (parentheses)
  4. _____________ pass values to a function. (Parameters)
  5. Use ________ to send a value back. (return)

โœ… True or False Exercises

  1. Functions are reusable blocks of code. (True)
  2. You define a function with func. (False)
  3. Parameters pass values to functions. (True)
  4. return sends a value back. (True)
  5. Functions cannot be used in automation. (False)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is a function?
    a) A reusable block of code โœ…
    b) A variable
    c) A loop
  2. How do you define a function?
    a) def function_name(): โœ…
    b) function function_name():
    c) func function_name():
  3. How do you call a function?
    a) function_name() โœ…
    b) call function_name()
    c) run function_name()
  4. What are parameters?
    a) Variables passed to a function โœ…
    b) Variables inside a function
    c) Variables outside a function
  5. What does return do?
    a) Sends a value back โœ…
    b) Prints a value
    c) Stops the program
  6. What is a default parameter?
    a) A parameter with a default value โœ…
    b) A parameter without a value
    c) A parameter that is required
  7. What is scope?
    a) Where a variable exists โœ…
    b) A type of function
    c) A type of loop
  8. What is a docstring?
    a) A description of a function โœ…
    b) A type of variable
    c) A type of loop
  9. Why are functions useful?
    a) They make code reusable โœ…
    b) They make code longer
    c) They make code harder
  10. How do you pass multiple parameters?
    a) Separate with commas โœ…
    b) Separate with spaces
    c) Separate with dots
  11. What is the keyword to define a function?
    a) def โœ…
    b) func
    c) function
  12. Can you use conditions inside functions?
    a) Yes โœ…
    b) No
  13. Can you use loops inside functions?
    a) Yes โœ…
    b) No
  14. What is the output of def add(a, b): return a + b with add(5, 3)?
    a) 8 โœ…
    b) 5
    c) 3
  15. Can functions have no parameters?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. FunctionA) Sends a value back
2. ParameterB) A reusable block of code
3. ReturnC) A variable passed to a function
4. DefineD) A description of a function
5. DocstringE) To create a function

(Answers: 1-B, 2-C, 3-A, 4-E, 5-D)

๐Ÿ“ Short Answer Questions

  1. What is a function and why is it useful?
  2. Write a function that takes a name and prints "Hello, [name]!".
  3. Write a function that takes two numbers and returns their sum.

๐ŸŽญ Scenario-based Exercises

Scenario 1: You need to greet many students every morning. Write a function that takes a name and prints a greeting.

Scenario 2: You need to calculate the area of a circle for different radii. Write a function that takes the radius and returns the area.

๐Ÿ‘ฅ Group Activity

In groups of 3, write a function that takes a list of numbers and returns the sum, average, and maximum. Test it with different lists.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Write a function that takes a number and returns "Even" if it's even and "Odd" if it's odd. Test it with different numbers.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • How can functions help you automate tasks?
  • What are some tasks you do repeatedly that could be turned into a function?
  • Why is code organisation important?

๐Ÿ› ๏ธ Mini Project

Create a program that uses functions to greet different people, calculate the average of a list of numbers, and check if a number is even or odd.

๐Ÿ“ Practical Assignment

Write a function that calculates the tax on an amount. Tax is 10% of the amount. Test it with different amounts.

๐Ÿ† Challenge Exercise

Write a function that takes a list of numbers and returns a new list with only the even numbers. Use a loop inside the function.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-function, 2-def, 3-parentheses, 4-Parameters, 5-return

True/False: 1-T, 2-F, 3-T, 4-T, 5-F

Matching: 1-B, 2-C, 3-A, 4-E, 5-D

๐ŸŽ Key Takeaways

  • Functions are reusable blocks of code.
  • Use def to define a function.
  • Use parameters to pass values.
  • Use return to send a value back.
  • Functions make code organised and reusable.

๐Ÿš€ Preparation for the next module

In Module Six, we will learn about working with files. We will learn how to read, write, and manage files using Python. Before the next session, think of a file you would like to create or read.

See you in Module Six! ๐ŸŽ‰


End of Module Five ยท Functions

8

Module Six

Module Six ยท Python for Automation

๐Ÿ“ Module Six ยท Working with Files


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Five, we learned about functions. We learned how to write reusable code. But what if we need to save information permanently? What if we want to read data from a file or save data to a file? That's where file handling comes in.

In this module, we will learn how to work with files in Python. We will learn how to open files, read from them, write to them, and close them. By the end of this module, you will be able to create programs that read and write data to files. This is very useful for automation!

๐ŸŽฏ Learning Objectives

  • Understand why file handling is important.
  • Open and close files in Python.
  • Read data from files.
  • Write data to files.
  • Use file handling in automation.

๐Ÿ“š Warm-up Story ยท Bola's Grade Book

Bola is a teacher in Lagos. She used to write student grades in a notebook. But the notebook got lost, and she had to remember all the grades. It was a disaster.

Her friend told her about Python file handling. Bola wrote a program that saved grades to a file. She wrote: with open("grades.txt", "w") as file: file.write("Aisha: 85\nChidi: 90"). The grades were saved forever. She could read them back anytime. Bola never lost her grades again!

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is File Handling?

Definition: File handling is the process of reading and writing data to files stored on your computer.

Why important: Files allow you to save data permanently so you can use it again later.

Simple explanation: Like saving a document in Word, but using Python.

Real-life example: Saving a list of student names to a file.

School example: Saving grades to a text file.

Home example: Saving a shopping list to a file.

Nigerian example: Saving a list of customers to a file.

Illustration:

    +----------------------+
    | Python Program       |
    |  reads/writes data   |
    +----------------------+
              |
              V
    +----------------------+
    | File (on disk)       |
    |  stores data         |
    +----------------------+
            

Mini summary: File handling is reading and writing files.


Lesson 2 ยท Opening a File

Definition: You open a file using the open() function. It takes two arguments: the file name and the mode.

Why important: You must open a file before you can read or write it.

Simple explanation: Like opening a book before you can read it.

Real-life example: file = open("data.txt", "r") opens a file for reading.

School example: file = open("grades.txt", "w") opens a file for writing.

Home example: file = open("shopping.txt", "a") opens a file for appending.

Nigerian example: file = open("students.txt", "r") opens a file for reading.

Illustration:

    file = open("filename.txt", "mode")
    Modes:
    "r"  Read (default)
    "w"  Write (overwrites)
    "a"  Append (adds to end)
            

Mini summary: Use open() to open a file.


Lesson 3 ยท Reading from a File

Definition: You read from a file using methods like read(), readline(), or readlines().

Why important: This allows you to get data from a file.

Simple explanation: Like reading the words in a book.

Real-life example: content = file.read() reads the whole file.

School example: line = file.readline() reads one line.

Home example: lines = file.readlines() reads all lines into a list.

Nigerian example: file.read() reads all text from a file.

Illustration:

    file = open("data.txt", "r")
    content = file.read()
    print(content)
    file.close()
            

Mini summary: Use read(), readline(), or readlines() to read files.


Lesson 4 ยท Writing to a File

Definition: You write to a file using write().

Why important: This allows you to save data to a file.

Simple explanation: Like writing in a notebook.

Real-life example: file.write("Hello, world!") writes text.

School example: file.write("Pass\n") writes a grade.

Home example: file.write("Milk\n") writes to a shopping list.

Nigerian example: file.write("Aisha: 85\n") writes a grade.

Illustration:

    file = open("output.txt", "w")
    file.write("Hello, world!")
    file.close()
            

Mini summary: Use write() to write to a file.


Lesson 5 ยท Appending to a File

Definition: Appending means adding data to the end of a file without overwriting existing data.

Why important: This is useful for adding new data to an existing file.

Simple explanation: Like adding new pages to a notebook.

Real-life example: file = open("data.txt", "a") opens for append.

School example: file.write("New student\n") adds a student.

Home example: file.write("Bread\n") adds to a shopping list.

Nigerian example: file.write("Chidi: 90\n") adds a grade.

Illustration:

    file = open("shopping.txt", "a")
    file.write("Bread\n")
    file.close()
            

Mini summary: Use "a" mode to append to a file.


Lesson 6 ยท Closing a File

Definition: You close a file using close().

Why important: Closing a file frees up system resources and ensures all data is saved.

Simple explanation: Like closing a book when you are done reading.

Real-life example: file.close() closes the file.

School example: Always close files after working with them.

Home example: Remember to close files to save data.

Nigerian example: file.close() is good practice.

Illustration:

    file = open("data.txt", "r")
    # work with the file
    file.close()  # Always close!
            

Mini summary: Always close files after using them.


Lesson 7 ยท Using With Statement

Definition: The with statement automatically closes the file for you.

Why important: It ensures the file is properly closed, even if an error occurs.

Simple explanation: Like having an automatic book closer.

Real-life example: with open("data.txt", "r") as file: content = file.read()

School example: with open("grades.txt", "w") as file: file.write("85")

Home example: with open("shopping.txt", "a") as file: file.write("Eggs\n")

Nigerian example: with open("students.txt", "r") as file: data = file.read()

Illustration:

    with open("data.txt", "r") as file:
        content = file.read()
    # File is automatically closed here
            

Mini summary: Use with for safe file handling.


Lesson 8 ยท Reading Line by Line

Definition: You can read a file line by line using a for loop.

Why important: This is efficient for large files.

Simple explanation: Like reading a book one page at a time.

Real-life example: for line in file: print(line)

School example: for line in file: print("Student: " + line)

Home example: for line in file: print(line.strip())

Nigerian example: for line in file: print(line)

Illustration:

    with open("names.txt", "r") as file:
        for line in file:
            print(line.strip())
            

Mini summary: Use loops to read files line by line.


Lesson 9 ยท Writing Multiple Lines

Definition: You can write multiple lines to a file by using \n for new lines.

Why important: This allows you to create structured files.

Simple explanation: Like writing a list with each item on a new line.

Real-life example: file.write("Line 1\nLine 2\nLine 3")

School example: file.write("Aisha: 85\nChidi: 90\n")

Home example: file.write("Milk\nBread\nEggs\n")

Nigerian example: file.write("Lagos\nAbuja\nKano\n")

Illustration:

    with open("grades.txt", "w") as file:
        file.write("Aisha: 85\n")
        file.write("Chidi: 90\n")
        file.write("Bola: 78\n")
            

Mini summary: Use \n to write multiple lines.


Lesson 10 ยท Checking if a File Exists

Definition: You can check if a file exists using the os.path module.

Why important: This prevents errors when trying to open a file that doesn't exist.

Simple explanation: Like checking if a book is on the shelf before reading it.

Real-life example: import os; if os.path.exists("data.txt"): print("File exists")

School example: if os.path.exists("grades.txt"): file = open("grades.txt", "r")

Home example: if os.path.exists("shopping.txt"): print("Found it")

Nigerian example: if os.path.exists("students.txt"): print("File found")

Illustration:

    import os
    if os.path.exists("data.txt"):
        print("File exists")
    else:
        print("File not found")
            

Mini summary: Use os.path.exists() to check if a file exists.


Lesson 11 ยท Using Files in Automation

Definition: File handling is essential for automation. You can read data from files, process it, and save results.

Why important: Many automation tasks involve reading and writing files.

Simple explanation: Like a factory that takes raw materials (input files) and produces products (output files).

Real-life example: A program that reads a list of email addresses and sends emails.

School example: A program that reads student grades and calculates averages.

Home example: A program that reads a shopping list and prints it.

Nigerian example: A program that reads a list of customers and sends messages.

Illustration:

    # Read names from a file
    with open("names.txt", "r") as file:
        for name in file:
            print("Hello, " + name.strip())
            

Mini summary: File handling is key to automation.


Lesson 12 ยท File Paths

Definition: A file path tells Python where the file is located on your computer.

Why important: You need to provide the correct path to open a file.

Simple explanation: Like an address that tells you where a house is.

Real-life example: open("C:/Users/name/data.txt", "r")

School example: open("grades.txt", "r") (same folder)

Home example: open("Documents/shopping.txt", "r")

Nigerian example: open("students.txt", "r")

Illustration:

    # Same folder
    file = open("data.txt", "r")

    # Different folder
    file = open("folder/data.txt", "r")
            

Mini summary: File paths tell Python where to find the file.


Lesson 13 ยท You Are Ready!

Definition: You have learned all the basics of file handling.

Why important: You can now build programs that read and write data to files.

Simple explanation: You can now save and load data permanently.

Real-life example: You can build a program that keeps a to-do list in a file.

School example: You can build a program that stores student grades.

Home example: You can build a program that stores a shopping list.

Nigerian example: You can build a program that stores customer information.

Illustration:

    Variables + Lists + Loops + Conditions + Functions + Files = Automation
    You are ready! ๐ŸŽ‰
            

Mini summary: You are ready to build file-based automation projects.


๐Ÿ“Œ Key Vocabulary

  • File: A container for storing data.
  • File handling: Reading and writing files.
  • Open: To make a file accessible.
  • Close: To release a file.
  • Read: To get data from a file.
  • Write: To save data to a file.
  • Append: To add data to the end.
  • With statement: Automatically closes files.
  • File path: The location of a file.
  • Exist: To be present.

๐Ÿง  Important Concepts

  • Open before using: Always open a file before reading or writing.
  • Close after using: Always close a file to save data.
  • Use with statement: It automatically closes files.
  • Check if file exists: Prevent errors.
  • File handling is key to automation.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Read a File and Print Its Content

  1. Open the file: with open("data.txt", "r") as file:
  2. Read the content: content = file.read()
  3. Print the content: print(content)
  4. Run the program: It will show the file content.

Example:

    Step 1: with open("data.txt", "r") as file:
    Step 2:     content = file.read()
    Step 3:     print(content)
    Step 4: Run the program!
            

๐ŸŒ Real-life Examples

  • Reading: with open("data.txt", "r") as file: print(file.read())
  • Writing: with open("output.txt", "w") as file: file.write("Hello")
  • Appending: with open("log.txt", "a") as file: file.write("New entry\n")
  • Reading lines: with open("names.txt", "r") as file: for line in file: print(line.strip())
  • Checking existence: import os; if os.path.exists("data.txt"): print("Exists")

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Reading students: with open("students.txt", "r") as file: for name in file: print("Student: " + name.strip())
  • Writing grades: with open("grades.txt", "w") as file: file.write("Aisha: 85\nChidi: 90\n")
  • Appending: with open("sales.txt", "a") as file: file.write("1000 Naira\n")
  • Reading cities: with open("cities.txt", "r") as file: for city in file: print(city.strip())
  • Checking file: import os; if os.path.exists("states.txt"): print("File found")

๐ŸŽˆ Fun Examples children can relate to

  • with open("favourite_foods.txt", "w") as file: file.write("Pizza\nIce cream\nChocolate")
  • with open("games.txt", "r") as file: for game in file: print("I like " + game.strip())
  • with open("friends.txt", "a") as file: file.write("Aisha\n")
  • with open("toys.txt", "r") as file: content = file.read(); print(content)
  • import os; if os.path.exists("pet_names.txt"): print("Found it")

๐Ÿ  Everyday Examples

  • To-do list: with open("todo.txt", "r") as file: for task in file: print("- " + task.strip())
  • Grocery list: with open("groceries.txt", "a") as file: file.write("Milk\n")
  • Journal: with open("journal.txt", "a") as file: file.write("Today was a good day.\n")
  • Reminders: with open("reminders.txt", "r") as file: print(file.read())
  • Recipes: with open("recipe.txt", "r") as file: for line in file: print(line.strip())

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to create and read files.
  • Use local examples to make it relatable.
  • Have students write programs that read and write data.
  • Emphasise the importance of closing files.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child create and read files.
  • Write programs together that save and read data.
  • Encourage them to think of data they can save in files.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Files are how data is stored on your computer.
  • Python can read and write many file types.
  • File handling is used in almost every program.
  • Automation often involves reading and writing files.
  • Files allow you to share data between programs.

๐Ÿ’ก Did You Know?

  • Did you know that you can read and write CSV files with Python?
  • Did you know that you can store data in JSON format?
  • Did you know that Python can read Excel files?
  • Did you know that you can create new files with Python?
  • Did you know that file handling is a key automation skill?

๐Ÿงท Remember This

  • Open a file before using it.
  • Close a file after using it.
  • Use with for safe file handling.
  • Use "r" for reading, "w" for writing, "a" for appending.
  • Check if a file exists to avoid errors.

โš ๏ธ Common Mistakes

  • Forgetting to close: Files should be closed.
  • Wrong mode: Using "r" for writing.
  • File not found: Opening a file that doesn't exist.
  • Not using with: Forgetting the with statement.
  • Wrong file path: Not using the correct path.

โœ… Best Practices

  • Use with for all file operations.
  • Check if a file exists before reading.
  • Use strip() when reading lines.
  • Use descriptive file names.
  • Test your file operations with different files.

๐ŸŽจ Illustrations, Diagrams & Tables

File Modes

ModeDescription
"r"Read (default)
"w"Write (overwrites)
"a"Append (adds to end)
"r+"Read and write

File Operations

OperationCode
Read entire filefile.read()
Read one linefile.readline()
Read all linesfile.readlines()
Writefile.write(text)
Appendfile.write(text)

File Handling Flowchart

    +----------------------+
    | Open file            |
    +----------------------+
              |
              V
    +----------------------+
    | Read or Write data   |
    +----------------------+
              |
              V
    +----------------------+
    | Close file           |
    +----------------------+
            

๐Ÿ“ End-of-Module Summary

In this module, we learned about file handling in Python. We discovered how to open, read, write, and close files. We learned about different file modes: read, write, and append. We also learned about the with statement, which automatically closes files. File handling is a key skill for automation. It allows you to save data permanently and build powerful programs. Great work!

โ“ Frequently Asked Questions (10)

  1. What is file handling? Reading and writing files.
  2. How do you open a file? open("filename.txt", "mode")
  3. What is the with statement? Automatically closes files.
  4. What is the "r" mode? Read mode.
  5. What is the "w" mode? Write mode.
  6. What is the "a" mode? Append mode.
  7. How do you read a file? file.read()
  8. How do you write to a file? file.write(text)
  9. How do you close a file? file.close()
  10. How do you check if a file exists? os.path.exists()

๐Ÿ“‹ Review Questions (15)

  1. What is file handling?
  2. How do you open a file?
  3. What are the different file modes?
  4. What is the with statement?
  5. How do you read a file?
  6. How do you write to a file?
  7. How do you append to a file?
  8. How do you close a file?
  9. How do you read a file line by line?
  10. How do you check if a file exists?
  11. What is the default mode for open()?
  12. What does the "w" mode do?
  13. What does the "a" mode do?
  14. Why should you close a file?
  15. What is the advantage of using with?

โœ๏ธ Fill-in-the-Blank Exercises

  1. File handling is reading and ______________ files. (writing)
  2. Use open() to ______________ a file. (open)
  3. The "r" mode is for ______________. (reading)
  4. The "w" mode is for ______________. (writing)
  5. The with statement automatically ______________ files. (closes)

โœ… True or False Exercises

  1. File handling is reading and writing files. (True)
  2. You do not need to close files. (False)
  3. The "w" mode appends to a file. (False)
  4. The with statement automatically closes files. (True)
  5. You can check if a file exists. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is file handling?
    a) Reading and writing files โœ…
    b) Deleting files
    c) Renaming files
  2. How do you open a file?
    a) open("file.txt", "r") โœ…
    b) open("file.txt")
    c) file.open("file.txt")
  3. What is the "r" mode?
    a) Read โœ…
    b) Write
    c) Append
  4. What is the "w" mode?
    a) Read
    b) Write โœ…
    c) Append
  5. What is the "a" mode?
    a) Read
    b) Write
    c) Append โœ…
  6. What does the with statement do?
    a) Opens and closes files โœ…
    b) Only opens files
    c) Only closes files
  7. How do you read a file?
    a) file.read() โœ…
    b) file.write()
    c) file.close()
  8. How do you write to a file?
    a) file.read()
    b) file.write() โœ…
    c) file.close()
  9. How do you close a file?
    a) file.close() โœ…
    b) file.stop()
    c) file.end()
  10. How do you check if a file exists?
    a) os.path.exists() โœ…
    b) file.exists()
    c) exists.file()
  11. What is the default mode for open()?
    a) "r" โœ…
    b) "w"
    c) "a"
  12. What does the "w" mode do to an existing file?
    a) Overwrites it โœ…
    b) Appends to it
    c) Reads it
  13. What does the "a" mode do?
    a) Adds to the end โœ…
    b) Overwrites
    c) Reads
  14. Why close a file?
    a) To free resources โœ…
    b) To delete it
    c) To rename it
  15. Can you read a file line by line?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. ReadA) Write to a file
2. WriteB) Get data from a file
3. AppendC) Automatically closes files
4. withD) Add to the end
5. closeE) Release a file

(Answers: 1-B, 2-A, 3-D, 4-C, 5-E)

๐Ÿ“ Short Answer Questions

  1. What is file handling and why is it important?
  2. Write code to open a file for reading and print its content.
  3. Write code to write "Hello, world!" to a file.

๐ŸŽญ Scenario-based Exercises

Scenario 1: You have a file called grades.txt with student names and grades. Write a program that reads the file and prints each name and grade.

Scenario 2: You want to save a list of tasks to a file. Write a program that asks the user for tasks and saves them to tasks.txt.

๐Ÿ‘ฅ Group Activity

In groups of 3, create a program that reads a list of names from a file, adds "Hello, " to each name, and writes the new list to another file.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Create a program that reads a file of numbers, calculates their sum, and writes the sum to another file.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • How can file handling help you in your daily life?
  • What kind of data would you like to store in files?
  • Why is it important to close files?

๐Ÿ› ๏ธ Mini Project

Create a program that acts as a simple to-do list manager. It should allow the user to add tasks, view tasks, and save tasks to a file.

๐Ÿ“ Practical Assignment

Write a program that reads a file of student grades, calculates the average, and writes the average to another file.

๐Ÿ† Challenge Exercise

Write a program that reads a file of names and scores, finds the student with the highest score, and writes their name to a file.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-writing, 2-open, 3-reading, 4-writing, 5-closes

True/False: 1-T, 2-F, 3-F, 4-T, 5-T

Matching: 1-B, 2-A, 3-D, 4-C, 5-E

๐ŸŽ Key Takeaways

  • File handling is reading and writing files.
  • Use open() to open a file.
  • Use "r" for reading, "w" for writing, "a" for appending.
  • Use with for safe file handling.
  • Always close files or use with.

๐Ÿš€ Preparation for the next module

In Module Seven, we will learn about working with CSV and Excel files. We will learn how to read and write spreadsheets using Python. Before the next session, think of a spreadsheet you use regularly.

See you in Module Seven! ๐ŸŽ‰


End of Module Six ยท Working with Files

9

Module Seven

Module Seven ยท Python for Automation

๐Ÿ“Š Module Seven ยท Working with CSV and Excel Files


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Six, we learned how to read and write text files. But many real-world tasks involve spreadsheets โ€” like CSV files and Excel files. Spreadsheets are used everywhere: in schools, businesses, and even at home.

In this module, we will learn how to work with CSV and Excel files in Python. We will learn how to read data from spreadsheets, process it, and write results to new spreadsheets. By the end of this module, you will be able to automate tasks that involve spreadsheets!

๐ŸŽฏ Learning Objectives

  • Understand what CSV and Excel files are.
  • Read and write CSV files using Python.
  • Read and write Excel files using Python.
  • Process data from spreadsheets.
  • Automate tasks with spreadsheet data.

๐Ÿ“š Warm-up Story ยท Chidi's Grade Spreadsheet

Chidi is a teacher in Enugu. He used to enter student grades into an Excel spreadsheet by hand. It took hours, and he often made mistakes.

His friend told him about Python and CSV files. Chidi wrote a program that read grades from a CSV file, calculated averages, and saved the results to a new CSV file. He saved hours of work and never made a mistake again. Now he loves using Python for spreadsheets!

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is a CSV File?

Definition: CSV stands for Comma-Separated Values. It is a simple file format where data is separated by commas.

Why important: CSV files are used to store tabular data (like spreadsheets). They are easy to read and write.

Simple explanation: Like a table where each row is a line and each column is separated by a comma.

Real-life example: A CSV file with student names and grades: Aisha,85\nChidi,90\nBola,78

School example: A teacher saves student grades in a CSV file.

Home example: A shopping list saved as CSV.

Nigerian example: A business saves sales data in a CSV file.

Illustration:

    CSV File:
    Name,Age,City
    Aisha,25,Lagos
    Chidi,30,Abuja
    Bola,28,Kano
            

Mini summary: CSV files store data in a simple text format with commas.


Lesson 2 ยท Reading CSV Files

Definition: You can read CSV files using Python's csv module.

Why important: This allows you to get data from spreadsheets.

Simple explanation: Like reading a table row by row.

Real-life example: import csv; with open("data.csv", "r") as file: reader = csv.reader(file); for row in reader: print(row)

School example: Reading a CSV file of student grades.

Home example: Reading a CSV shopping list.

Nigerian example: Reading a CSV file of customer data.

Illustration:

    import csv
    with open("students.csv", "r") as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)
            

Mini summary: Use csv.reader to read CSV files.


Lesson 3 ยท Writing CSV Files

Definition: You can write CSV files using csv.writer.

Why important: This allows you to save data to spreadsheets.

Simple explanation: Like writing a table row by row.

Real-life example: import csv; with open("output.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Name", "Grade"])

School example: Saving grades to a CSV file.

Home example: Saving a shopping list to CSV.

Nigerian example: Saving customer data to CSV.

Illustration:

    import csv
    with open("output.csv", "w") as file:
        writer = csv.writer(file)
        writer.writerow(["Name", "Age", "City"])
        writer.writerow(["Aisha", "25", "Lagos"])
            

Mini summary: Use csv.writer to write CSV files.


Lesson 4 ยท Reading CSV with DictReader

Definition: DictReader reads CSV files into dictionaries, using the first row as keys.

Why important: This makes it easier to access data by column name.

Simple explanation: Like having a table where you can look up values by column name.

Real-life example: reader = csv.DictReader(file); for row in reader: print(row["Name"])

School example: Accessing student grades by subject.

Home example: Accessing shopping list items by category.

Nigerian example: Accessing customer data by field.

Illustration:

    import csv
    with open("students.csv", "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            print(row["Name"], row["Grade"])
            

Mini summary: DictReader uses column names as keys.


Lesson 5 ยท Writing CSV with DictWriter

Definition: DictWriter writes dictionaries to CSV files.

Why important: This makes it easy to write data with column names.

Simple explanation: Like writing a table using dictionaries.

Real-life example: writer = csv.DictWriter(file, fieldnames=["Name", "Grade"]); writer.writeheader(); writer.writerow({"Name": "Aisha", "Grade": 85})

School example: Writing grades with student names.

Home example: Writing a shopping list with items and quantities.

Nigerian example: Writing customer data.

Illustration:

    import csv
    with open("output.csv", "w") as file:
        writer = csv.DictWriter(file, fieldnames=["Name", "Grade"])
        writer.writeheader()
        writer.writerow({"Name": "Aisha", "Grade": 85})
            

Mini summary: DictWriter writes dictionaries to CSV.


Lesson 6 ยท What is an Excel File?

Definition: Excel files (.xlsx) are spreadsheet files created by Microsoft Excel.

Why important: Excel files are very common in businesses and schools.

Simple explanation: Like a digital notebook with rows and columns.

Real-life example: A teacher uses an Excel file for grades.

School example: A school uses Excel for student records.

Home example: A family uses Excel for a budget.

Nigerian example: A business uses Excel for sales data.

Illustration:

    Excel File:
    +-------+-------+--------+
    | Name  | Age   | City   |
    +-------+-------+--------+
    | Aisha | 25    | Lagos  |
    | Chidi | 30    | Abuja  |
    +-------+-------+--------+
            

Mini summary: Excel files are common spreadsheet files.


Lesson 7 ยท Installing openpyxl

Definition: openpyxl is a Python library for reading and writing Excel files.

Why important: You need to install it to work with Excel files.

Simple explanation: Like installing an app on your phone.

Real-life example: pip install openpyxl

School example: Installing openpyxl to work with grade spreadsheets.

Home example: Installing openpyxl to manage a budget.

Nigerian example: Installing openpyxl for business data.

Illustration:

    pip install openpyxl
            

Mini summary: Use pip to install openpyxl.


Lesson 8 ยท Reading Excel Files

Definition: You can read Excel files using openpyxl.

Why important: This allows you to get data from Excel spreadsheets.

Simple explanation: Like opening an Excel file and reading its content.

Real-life example: from openpyxl import load_workbook; wb = load_workbook("data.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)

School example: Reading a grade spreadsheet.

Home example: Reading a budget spreadsheet.

Nigerian example: Reading sales data from Excel.

Illustration:

    from openpyxl import load_workbook
    wb = load_workbook("students.xlsx")
    sheet = wb.active
    for row in sheet.iter_rows(values_only=True):
        print(row)
            

Mini summary: Use load_workbook to read Excel files.


Lesson 9 ยท Writing Excel Files

Definition: You can write Excel files using openpyxl.

Why important: This allows you to save data to Excel spreadsheets.

Simple explanation: Like creating a new Excel file.

Real-life example: from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Name"; sheet["B1"] = "Grade"; wb.save("output.xlsx")

School example: Saving grades to an Excel file.

Home example: Saving a budget to Excel.

Nigerian example: Saving sales data to Excel.

Illustration:

    from openpyxl import Workbook
    wb = Workbook()
    sheet = wb.active
    sheet["A1"] = "Name"
    sheet["B1"] = "Grade"
    sheet["A2"] = "Aisha"
    sheet["B2"] = 85
    wb.save("output.xlsx")
            

Mini summary: Use Workbook to write Excel files.


Lesson 10 ยท Using Data from Spreadsheets in Automation

Definition: You can use data from spreadsheets to automate tasks like sending emails, calculating reports, and more.

Why important: Spreadsheets are a common source of data for automation.

Simple explanation: Like reading a list of customers and sending them emails.

Real-life example: A program that reads a list of students and sends each one a report.

School example: A program that calculates final grades from a spreadsheet.

Home example: A program that tracks expenses from a budget spreadsheet.

Nigerian example: A program that processes sales data.

Illustration:

    # Read names and grades, calculate averages
    with open("students.csv", "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            name = row["Name"]
            grade = int(row["Grade"])
            print(name + " got " + str(grade))
            

Mini summary: Use spreadsheet data for automation.


Lesson 11 ยท Putting It All Together

Definition: You can combine CSV, Excel, and other Python skills to build powerful automation tools.

Why important: This is how you solve real-world problems.

Simple explanation: Like building a machine that processes data.

Real-life example: A program that reads student grades, calculates averages, and saves the results.

School example: A program that automates grade processing.

Home example: A program that tracks monthly expenses.

Nigerian example: A program that processes business sales data.

Illustration:

    # Read CSV, process data, write Excel
    import csv
    from openpyxl import Workbook

    # Read CSV
    with open("data.csv", "r") as file:
        reader = csv.DictReader(file)
        data = list(reader)

    # Process data
    for row in data:
        row["Grade"] = int(row["Grade"]) + 5  # Bonus

    # Write Excel
    wb = Workbook()
    sheet = wb.active
    sheet["A1"] = "Name"
    sheet["B1"] = "Grade"
    for i, row in enumerate(data, start=2):
        sheet["A" + str(i)] = row["Name"]
        sheet["B" + str(i)] = row["Grade"]
    wb.save("output.xlsx")
            

Mini summary: Combine skills to build automation tools.


Lesson 12 ยท You Are an Automation Expert!

Definition: You have learned how to work with CSV and Excel files.

Why important: You can now automate many tasks involving spreadsheets.

Simple explanation: You are ready to solve real-world problems with Python.

Real-life example: You can build a program that processes data for your school or business.

School example: You can automate grade processing.

Home example: You can automate expense tracking.

Nigerian example: You can build tools for Nigerian businesses.

Illustration:

    CSV + Excel + Python = Automation Power! ๐ŸŽ‰
            

Mini summary: You are ready to build real automation projects!


๐Ÿ“Œ Key Vocabulary

  • CSV: Comma-Separated Values โ€” a simple text format for tables.
  • Excel: A spreadsheet file format (.xlsx).
  • Spreadsheet: A table of data in rows and columns.
  • Row: A horizontal line of data.
  • Column: A vertical line of data.
  • Reader: Reads CSV files.
  • Writer: Writes CSV files.
  • DictReader: Reads CSV into dictionaries.
  • DictWriter: Writes dictionaries to CSV.
  • openpyxl: A Python library for Excel.

๐Ÿง  Important Concepts

  • CSV is simple: It's just text with commas.
  • Excel is powerful: It has many features.
  • Python can handle both: Use csv and openpyxl.
  • Data processing: Read data, process it, write results.
  • Automation: Use Python to automate spreadsheet tasks.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Read a CSV File and Print Each Row

  1. Import the csv module: import csv
  2. Open the file: with open("data.csv", "r") as file:
  3. Create a reader: reader = csv.reader(file)
  4. Loop through rows: for row in reader: print(row)
  5. Run the program: It will print each row.

Example:

    Step 1: import csv
    Step 2: with open("data.csv", "r") as file:
    Step 3:     reader = csv.reader(file)
    Step 4:     for row in reader:
    Step 5:         print(row)
            

๐ŸŒ Real-life Examples

  • Reading CSV: import csv; with open("data.csv", "r") as file: reader = csv.reader(file); for row in reader: print(row)
  • Writing CSV: import csv; with open("output.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Name", "Score"])
  • Reading Excel: from openpyxl import load_workbook; wb = load_workbook("data.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)
  • Writing Excel: from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Hello"; wb.save("output.xlsx")
  • Processing Data: with open("data.csv", "r") as file: reader = csv.DictReader(file); for row in reader: print(row["Name"])

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Reading students: import csv; with open("students.csv", "r") as file: reader = csv.DictReader(file); for row in reader: print(row["Name"] + " from " + row["City"])
  • Writing grades: import csv; with open("grades.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Name", "Grade"]); writer.writerow(["Aisha", 85])
  • Reading Excel: from openpyxl import load_workbook; wb = load_workbook("sales.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)
  • Writing Excel: from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Product"; sheet["B1"] = "Sales"; wb.save("sales.xlsx")
  • Processing data: with open("customers.csv", "r") as file: reader = csv.DictReader(file); for row in reader: print("Hello, " + row["Name"])

๐ŸŽˆ Fun Examples children can relate to

  • import csv; with open("fruits.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Fruit", "Colour"]); writer.writerow(["Apple", "Red"])
  • import csv; with open("fruits.csv", "r") as file: reader = csv.reader(file); for row in reader: print(row)
  • from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Game"; sheet["B1"] = "Players"; wb.save("games.xlsx")
  • from openpyxl import load_workbook; wb = load_workbook("games.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)
  • import csv; with open("toys.csv", "r") as file: reader = csv.DictReader(file); for row in reader: print(row["Toy"])

๐Ÿ  Everyday Examples

  • Grocery list: import csv; with open("shopping.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Item", "Quantity"]); writer.writerow(["Milk", 2])
  • Budget: from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Expense"; sheet["B1"] = "Amount"; wb.save("budget.xlsx")
  • Reading budget: from openpyxl import load_workbook; wb = load_workbook("budget.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)
  • To-do list: import csv; with open("tasks.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Task", "Done"]); writer.writerow(["Clean room", "No"])
  • Reading tasks: import csv; with open("tasks.csv", "r") as file: reader = csv.reader(file); for row in reader: print(row)

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to create and read CSV and Excel files.
  • Use local examples to make it relatable.
  • Have students write programs that process spreadsheet data.
  • Emphasise the power of automating spreadsheet tasks.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child create and read CSV and Excel files.
  • Write programs together that process data.
  • Encourage them to think of data they can automate.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • CSV is one of the oldest data formats.
  • Excel is used by millions of people worldwide.
  • Python can process huge spreadsheets.
  • Automation with spreadsheets saves hours of work.
  • Many businesses use Python to process Excel data.

๐Ÿ’ก Did You Know?

  • Did you know that CSV files can be opened by Excel?
  • Did you know that openpyxl can read and write Excel files?
  • Did you know that you can automate data entry with Python?
  • Did you know that you can process thousands of rows in seconds?
  • Did you know that Python is used by many Nigerian businesses?

๐Ÿงท Remember This

  • CSV stands for Comma-Separated Values.
  • Use csv.reader to read CSV files.
  • Use csv.writer to write CSV files.
  • Use openpyxl for Excel files.
  • Spreadsheets are a great source of data for automation.

โš ๏ธ Common Mistakes

  • Forgetting to import: import csv or from openpyxl import load_workbook
  • Wrong file path: Using the wrong file name or location.
  • Not closing files: Use with to manage files.
  • Data type errors: Convert strings to numbers when needed.
  • Missing headers: Forgetting to write headers in CSV or Excel.

โœ… Best Practices

  • Always use with when opening files.
  • Use DictReader and DictWriter for easier data access.
  • Check your data types (convert to int, float, etc.).
  • Use descriptive column names.
  • Test your code with small files first.

๐ŸŽจ Illustrations, Diagrams & Tables

CSV vs Excel

CSVExcel
Plain textBinary format
Small file sizeLarger file size
SimpleFeature-rich
Read with csvRead with openpyxl

CSV Reading Methods

MethodDescription
csv.reader()Reads CSV rows as lists
csv.DictReader()Reads CSV rows as dictionaries

Excel Reading Methods

MethodDescription
load_workbook()Loads an Excel file
sheet.iter_rows()Iterates over rows
sheet["A1"]Accesses a cell

Spreadsheet Automation Flowchart

    +----------------------+
    | Read Data from CSV or Excel |
    +----------------------+
              |
              V
    +----------------------+
    | Process Data         |
    | (calculate, filter, etc.) |
    +----------------------+
              |
              V
    +----------------------+
    | Write Results to CSV or Excel |
    +----------------------+
            

๐Ÿ“ End-of-Module Summary

In this module, we learned how to work with CSV and Excel files in Python. We discovered that CSV files are simple text files with commas, while Excel files are more powerful and feature-rich. We learned to read and write both formats using the csv and openpyxl libraries. With these skills, you can automate tasks that involve spreadsheets, such as processing grades, sales data, and more. Great work!

โ“ Frequently Asked Questions (10)

  1. What is CSV? Comma-Separated Values โ€” a simple text format.
  2. What is Excel? A spreadsheet file format (.xlsx).
  3. How do you read a CSV file? Using csv.reader.
  4. How do you write a CSV file? Using csv.writer.
  5. What is DictReader? Reads CSV as dictionaries.
  6. What is DictWriter? Writes dictionaries to CSV.
  7. How do you read an Excel file? Using openpyxl.load_workbook.
  8. How do you write an Excel file? Using openpyxl.Workbook.
  9. What is openpyxl? A library for Excel files.
  10. Can I automate spreadsheet tasks with Python? Yes, absolutely!

๐Ÿ“‹ Review Questions (15)

  1. What is a CSV file?
  2. What is an Excel file?
  3. How do you read a CSV file?
  4. How do you write a CSV file?
  5. What is DictReader?
  6. What is DictWriter?
  7. How do you install openpyxl?
  8. How do you read an Excel file?
  9. How do you write an Excel file?
  10. What is the difference between CSV and Excel?
  11. What is a row in a spreadsheet?
  12. What is a column in a spreadsheet?
  13. How do you access a cell in Excel using openpyxl?
  14. Can you process data from a spreadsheet?
  15. What is one way to automate spreadsheet tasks?

โœ๏ธ Fill-in-the-Blank Exercises

  1. CSV stands for ______________. (Comma-Separated Values)
  2. Use csv.______________ to read CSV files. (reader)
  3. Use csv.______________ to write CSV files. (writer)
  4. ______________ is a library for Excel files. (openpyxl)
  5. Use openpyxl.______________ to load an Excel file. (load_workbook)

โœ… True or False Exercises

  1. CSV files are more complex than Excel files. (False)
  2. DictReader reads CSV rows as dictionaries. (True)
  3. openpyxl is used for CSV files. (False)
  4. You can process data from spreadsheets with Python. (True)
  5. Excel files are plain text. (False)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What does CSV stand for?
    a) Comma-Separated Values โœ…
    b) Computer-Saved Values
    c) Common-Separated Values
  2. What is Excel?
    a) A spreadsheet file format โœ…
    b) A text file format
    c) A programming language
  3. How do you read a CSV file?
    a) csv.reader โœ…
    b) csv.writer
    c) csv.read
  4. How do you write a CSV file?
    a) csv.reader
    b) csv.writer โœ…
    c) csv.write
  5. What is DictReader?
    a) Reads CSV as dictionaries โœ…
    b) Reads CSV as lists
    c) Writes CSV as dictionaries
  6. What is DictWriter?
    a) Reads CSV as dictionaries
    b) Writes dictionaries to CSV โœ…
    c) Writes CSV as lists
  7. How do you install openpyxl?
    a) pip install openpyxl โœ…
    b) install openpyxl
    c) pip get openpyxl
  8. How do you read an Excel file?
    a) openpyxl.load_workbook โœ…
    b) openpyxl.read_excel
    c) openpyxl.open
  9. How do you write an Excel file?
    a) openpyxl.Workbook โœ…
    b) openpyxl.write_excel
    c) openpyxl.create
  10. What is the difference between CSV and Excel?
    a) CSV is plain text, Excel is binary โœ…
    b) CSV is binary, Excel is plain text
    c) They are the same
  11. What is a row in a spreadsheet?
    a) Horizontal line of data โœ…
    b) Vertical line of data
    c) A single cell
  12. What is a column in a spreadsheet?
    a) Horizontal line of data
    b) Vertical line of data โœ…
    c) A single cell
  13. How do you access a cell in Excel using openpyxl?
    a) sheet["A1"] โœ…
    b) sheet.cell("A1")
    c) sheet.get("A1")
  14. Can you process data from a spreadsheet?
    a) Yes โœ…
    b) No
  15. Is Python useful for automating spreadsheet tasks?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. CSVA) A spreadsheet file format
2. ExcelB) Comma-Separated Values
3. DictReaderC) Reads CSV as dictionaries
4. openpyxlD) A library for Excel files
5. RowE) Horizontal line of data

(Answers: 1-B, 2-A, 3-C, 4-D, 5-E)

๐Ÿ“ Short Answer Questions

  1. What is a CSV file and how do you read it in Python?
  2. What is openpyxl and how do you use it?
  3. Write a program that reads a CSV file and prints each row.

๐ŸŽญ Scenario-based Exercises

Scenario 1: You have a CSV file with student names and grades. Write a program that reads the file and calculates the average grade.

Scenario 2: You have a list of sales data in Excel. Write a program that reads the data and writes it to a CSV file.

๐Ÿ‘ฅ Group Activity

In groups of 3, create a CSV file with student data (Name, Age, City). Write a program that reads the file and prints a summary (number of students, average age, etc.).

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Create a program that reads a CSV file of products (Name, Price, Quantity) and calculates the total value of each product (Price * Quantity).

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • How can you use Python to automate spreadsheet tasks?
  • What kind of data would you like to process?
  • What are the benefits of automating spreadsheet tasks?

๐Ÿ› ๏ธ Mini Project

Create a program that reads a CSV file of student grades, calculates the average for each student, and writes the results to a new Excel file.

๐Ÿ“ Practical Assignment

Write a program that reads a CSV file of sales data, calculates total sales per product, and writes the results to a new CSV file.

๐Ÿ† Challenge Exercise

Write a program that reads an Excel file of student data, finds the student with the highest grade, and writes their name to a CSV file.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-Comma-Separated Values, 2-reader, 3-writer, 4-openpyxl, 5-load_workbook

True/False: 1-F, 2-T, 3-F, 4-T, 5-F

Matching: 1-B, 2-A, 3-C, 4-D, 5-E

๐ŸŽ Key Takeaways

  • CSV files are simple text files with commas.
  • Excel files are powerful spreadsheet files.
  • Use csv module for CSV files.
  • Use openpyxl for Excel files.
  • Python can automate many spreadsheet tasks.

๐Ÿš€ Preparation for the next module

In Module Eight, we will learn about automating emails and notifications. We will learn how to send emails automatically with Python. Before the next session, think of an email you send regularly.

See you in Module Eight! ๐ŸŽ‰


End of Module Seven ยท Working with CSV and Excel Files

10

Module Eight

Module Eight ยท Python for Automation

๐Ÿ“ง Module Eight ยท Automating Emails and Notifications


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Seven, we learned how to work with CSV and Excel files. Now we will learn how to send emails automatically with Python. Email is one of the most common ways people communicate. Being able to send emails automatically is a very powerful skill.

In this module, we will learn how to use Python to send emails. We will learn about SMTP, how to connect to an email server, and how to send messages. By the end of this module, you will be able to send emails automatically!

๐ŸŽฏ Learning Objectives

  • Understand what SMTP is and why it is used.
  • Learn how to send emails with Python.
  • Send emails with different content (subject, body, attachments).
  • Use email automation in real-world tasks.
  • Practice sending notifications automatically.

๐Ÿ“š Warm-up Story ยท Ngozi's Automated Report

Ngozi is a manager in Lagos. Every week, she had to send a sales report to her team. She would copy data from a spreadsheet, paste it into an email, and send it to 20 people. It took her 30 minutes every week.

Her IT friend showed her Python. Ngozi wrote a program that read data from a CSV file and sent an email to each person on the list. Now the program does all the work in 2 minutes. Ngozi spends her time on more important tasks!

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is SMTP?

Definition: SMTP stands for Simple Mail Transfer Protocol. It is the protocol used to send emails.

Why important: SMTP is how your program talks to the email server to send messages.

Simple explanation: Like the post office for email.

Real-life example: Gmail and Yahoo use SMTP to send emails.

School example: A teacher uses SMTP to send grades to students.

Home example: A parent uses SMTP to send a reminder.

Nigerian example: A business uses SMTP to send invoices.

Illustration:

    Your Program  โ†’  SMTP Server  โ†’  Recipient
    (sends email)   (processes)   (receives)
            

Mini summary: SMTP is the system that sends emails.


Lesson 2 ยท Setting Up for Email Automation

Definition: You need an email account and a password to send emails. You also need the server address and port number.

Why important: This is how your program connects to the email service.

Simple explanation: Like having a key to a post office box.

Real-life example: Gmail uses smtp.gmail.com and port 587.

School example: A school email account.

Home example: A personal email account.

Nigerian example: Using Gmail or Yahoo.

Illustration:

    Email: your_email@gmail.com
    Password: your_password
    Server: smtp.gmail.com
    Port: 587
            

Mini summary: You need an email account and server settings.


Lesson 3 ยท Sending a Simple Email

Definition: You can send an email using Python's smtplib library.

Why important: This is the foundation of email automation.

Simple explanation: Like writing a letter and mailing it.

Real-life example: smtplib.SMTP connects to the server and sends the email.

School example: Sending a grade report.

Home example: Sending a reminder.

Nigerian example: Sending a business invoice.

Illustration:

    import smtplib
    from email.message import EmailMessage

    msg = EmailMessage()
    msg.set_content("Hello, this is a test email.")
    msg["Subject"] = "Test Email"
    msg["From"] = "your_email@gmail.com"
    msg["To"] = "recipient@email.com"

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login("your_email@gmail.com", "your_password")
        server.send_message(msg)
            

Mini summary: Use smtplib and EmailMessage to send emails.


Lesson 4 ยท Understanding the Code

Definition: Let's break down the email-sending code into parts.

Why important: Understanding each part helps you customize your emails.

Simple explanation: Like knowing what each ingredient does in a recipe.

Real-life example: msg["Subject"] sets the subject line.

School example: msg["To"] sets the recipient.

Home example: msg.set_content() sets the message body.

Nigerian example: server.login() logs you into your email.

Illustration:

    Parts:
    1. Import libraries: smtplib, EmailMessage
    2. Create message: EmailMessage()
    3. Set content: msg.set_content()
    4. Set subject: msg["Subject"]
    5. Set sender: msg["From"]
    6. Set receiver: msg["To"]
    7. Connect to server: smtplib.SMTP()
    8. Login: server.login()
    9. Send: server.send_message()
            

Mini summary: The code has clear parts for creating and sending an email.


Lesson 5 ยท Sending to Multiple Recipients

Definition: You can send the same email to many people by putting their emails in a list.

Why important: This saves time when you need to send the same message to many people.

Simple explanation: Like sending a group message.

Real-life example: msg["To"] = "person1@email.com, person2@email.com"

School example: Sending grades to all students.

Home example: Sending a family announcement.

Nigerian example: Sending a business newsletter.

Illustration:

    recipients = ["aisha@email.com", "chidi@email.com", "bola@email.com"]
    msg["To"] = ", ".join(recipients)
            

Mini summary: Use commas to send to multiple recipients.


Lesson 6 ยท Personalising Emails

Definition: You can personalise emails by using different content for each recipient.

Why important: Personalised emails are more effective and friendly.

Simple explanation: Like writing a letter with the person's name.

Real-life example: "Hello Aisha, your grade is 85."

School example: Sending individual grade reports.

Home example: Sending birthday wishes.

Nigerian example: Sending personalised invoices.

Illustration:

    for recipient in recipients:
        msg = EmailMessage()
        msg.set_content(f"Hello {recipient['name']}, your grade is {recipient['grade']}.")
        msg["To"] = recipient["email"]
        # Send email
            

Mini summary: Use loops to personalise emails.


Lesson 7 ยท Sending Emails with Attachments

Definition: You can send attachments like PDFs, images, or Excel files.

Why important: Sometimes you need to send documents with your email.

Simple explanation: Like attaching a file to a letter.

Real-life example: Sending a report as an attachment.

School example: Sending homework assignments.

Home example: Sending family photos.

Nigerian example: Sending invoices as PDF.

Illustration:

    with open("report.pdf", "rb") as file:
        file_data = file.read()
    msg.add_attachment(file_data, maintype="application", subtype="pdf", filename="report.pdf")
            

Mini summary: Use add_attachment to send files.


Lesson 8 ยท Scheduling Emails

Definition: You can schedule emails to be sent at a specific time.

Why important: This is useful for regular reports or reminders.

Simple explanation: Like setting an alarm.

Real-life example: Sending a weekly report every Friday.

School example: Sending a grade report at the end of the term.

Home example: Sending a birthday reminder.

Nigerian example: Sending a monthly business report.

Illustration:

    import time
    while True:
        if time.strftime("%A") == "Friday":
            send_email()
            time.sleep(86400)  # Wait 24 hours
            

Mini summary: Use time and loops to schedule emails.


Lesson 9 ยท Using Email in Automation

Definition: Email automation is used in many real-world applications: sending reports, notifications, alerts, and more.

Why important: It saves time and ensures timely communication.

Simple explanation: Like having a robot that sends emails for you.

Real-life example: A system that sends a daily summary email.

School example: A system that sends grade reports.

Home example: A system that sends shopping reminders.

Nigerian example: A business that sends invoices automatically.

Illustration:

    # Read data from a CSV file and send emails
    import csv
    with open("students.csv", "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            send_email(row["Name"], row["Grade"])
            

Mini summary: Use email automation for many real-world tasks.


Lesson 10 ยท Notifications and Alerts

Definition: You can use Python to send notifications or alerts via email.

Why important: This allows you to get real-time updates.

Simple explanation: Like getting a text message alert.

Real-life example: An alert when the temperature drops below a certain level.

School example: An alert when a student submits homework.

Home example: An alert when a package is delivered.

Nigerian example: An alert about business sales.

Illustration:

    temp = get_temperature()
    if temp < 10:
        send_alert("Temperature is low: " + str(temp))
            

Mini summary: Use email for notifications and alerts.


Lesson 11 ยท Security and Privacy

Definition: When automating emails, you must protect your password and personal information.

Why important: Security prevents your account from being hacked.

Simple explanation: Like keeping your house keys safe.

Real-life example: Use environment variables to store passwords.

School example: Don't share your email password.

Home example: Keep your email account secure.

Nigerian example: Use secure practices for business emails.

Illustration:

    import os
    email_password = os.environ.get("EMAIL_PASSWORD")
            

Mini summary: Keep your email password safe.


Lesson 12 ยท You Are Ready!

Definition: You have learned how to send emails with Python.

Why important: You can now automate email tasks.

Simple explanation: You can make Python send emails for you.

Real-life example: You can send reports automatically.

School example: You can send grade reports.

Home example: You can send reminders.

Nigerian example: You can send business invoices.

Illustration:

    Python + Email = Automation Power! ๐ŸŽ‰
            

Mini summary: You are ready to automate emails!


๐Ÿ“Œ Key Vocabulary

  • SMTP: Simple Mail Transfer Protocol โ€” used to send emails.
  • Email Message: The content of an email (subject, body, etc.).
  • Server: A computer that handles email.
  • Port: A connection point (e.g., 587).
  • Login: To authenticate with a username and password.
  • Attachment: A file sent with an email.
  • Recipient: The person receiving the email.
  • Sender: The person sending the email.
  • Notification: An alert or message.
  • Security: Protecting information.

๐Ÿง  Important Concepts

  • SMTP sends emails: It's the protocol for sending.
  • EmailMessage: Creates the email content.
  • Login: You need to log in to your email account.
  • Personalisation: Makes emails more effective.
  • Attachments: Send files with emails.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Send a Simple Email in 6 Steps

  1. Import libraries: import smtplib; from email.message import EmailMessage
  2. Create the message: msg = EmailMessage()
  3. Set content: msg.set_content("Your message here.")
  4. Set subject, from, to: msg["Subject"] = "Subject"; msg["From"] = "sender@email.com"; msg["To"] = "recipient@email.com"
  5. Connect and login: with smtplib.SMTP("smtp.gmail.com", 587) as server: server.starttls(); server.login("your_email", "password")
  6. Send: server.send_message(msg)

Example:

    import smtplib
    from email.message import EmailMessage

    msg = EmailMessage()
    msg.set_content("Hello, this is a test.")
    msg["Subject"] = "Test"
    msg["From"] = "your_email@gmail.com"
    msg["To"] = "recipient@email.com"

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login("your_email@gmail.com", "password")
        server.send_message(msg)
            

๐ŸŒ Real-life Examples

  • Simple email: msg.set_content("Hello"); msg["Subject"] = "Greeting"
  • Multiple recipients: msg["To"] = "a@email.com, b@email.com"
  • Personalised: msg.set_content("Hello " + name)
  • Attachment: msg.add_attachment(file_data, filename="file.pdf")
  • Alert: send_alert("Temperature is too low.")

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Grade report: msg.set_content(f"Hello {name}, your grade is {grade}.")
  • Invoice: msg.set_content("Please find your invoice attached."); msg.add_attachment(pdf_data, filename="invoice.pdf")
  • Business alert: send_alert("Sales have reached 1,000,000 Naira.")
  • Reminder: msg.set_content("Don't forget the meeting at 3pm.")
  • Newsletter: for customer in customers: send_custom_email(customer)

๐ŸŽˆ Fun Examples children can relate to

  • msg.set_content("Happy Birthday!")
  • msg.set_content("Let's play games.")
  • msg.set_content("I love Python!")
  • msg.set_content("Do you want to be friends?")
  • msg.set_content("I made a new program!")

๐Ÿ  Everyday Examples

  • Reminder: msg.set_content("Don't forget to buy milk.")
  • Update: msg.set_content("I finished my homework.")
  • Invitation: msg.set_content("You are invited to my party.")
  • Thank you: msg.set_content("Thank you for your help.")
  • Photo: msg.add_attachment(photo_data, filename="photo.jpg")

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to send test emails to themselves.
  • Use local examples to make it relatable.
  • Discuss the importance of email security.
  • Have students create programs that send automated reports.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child set up a test email account.
  • Write programs together that send emails.
  • Encourage them to think of tasks they can automate.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • The first email was sent in 1971.
  • SMTP has been used since 1982.
  • Python can send thousands of emails quickly.
  • Email automation saves millions of hours.
  • Many businesses use Python for email automation.

๐Ÿ’ก Did You Know?

  • Did you know that you can send emails to many people at once?
  • Did you know that you can personalise emails with Python?
  • Did you know that you can send attachments with Python?
  • Did you know that you can schedule emails with Python?
  • Did you know that Python is used for email marketing?

๐Ÿงท Remember This

  • Use SMTP to send emails.
  • Create an EmailMessage object.
  • Set the subject, from, and to fields.
  • Login to your email account.
  • Send the message.
  • Keep your password secure.

โš ๏ธ Common Mistakes

  • Wrong server: Using the wrong SMTP server address.
  • Wrong port: Using the wrong port number.
  • Incorrect login: Using the wrong email or password.
  • Security settings: Some email providers require less secure apps.
  • Forgot starttls: Not enabling TLS for security.

โœ… Best Practices

  • Use environment variables for passwords.
  • Test with a test email account.
  • Use TLS for secure connections.
  • Handle errors gracefully.
  • Never share your password.

๐ŸŽจ Illustrations, Diagrams & Tables

Email Sending Flow

    +----------------------+
    | Create Email         |
    +----------------------+
              |
              V
    +----------------------+
    | Connect to SMTP      |
    +----------------------+
              |
              V
    +----------------------+
    | Login to Email       |
    +----------------------+
              |
              V
    +----------------------+
    | Send Email           |
    +----------------------+
            

Email Parts

PartDescriptionExample
SubjectTitle of the email"Test Email"
FromSender's email"your_email@gmail.com"
ToRecipient's email"recipient@email.com"
BodyContent of the email"Hello, this is a test."

SMTP Settings

ServiceServerPort
Gmailsmtp.gmail.com587
Yahoosmtp.mail.yahoo.com587
Outlooksmtp.office365.com587

๐Ÿ“ End-of-Module Summary

In this module, we learned how to send emails with Python. We discovered that SMTP is the protocol used to send emails. We learned how to create email messages, set the subject and body, and send them to recipients. We also learned how to personalise emails, add attachments, and schedule emails. With these skills, you can automate many tasks that involve sending emails. Great work!

โ“ Frequently Asked Questions (10)

  1. What is SMTP? The protocol used to send emails.
  2. How do you send an email with Python? Using smtplib and EmailMessage.
  3. What is the server for Gmail? smtp.gmail.com
  4. What is the port for Gmail? 587
  5. How do you personalise emails? Use variables in the content.
  6. How do you add an attachment? msg.add_attachment()
  7. How do you schedule emails? Use time and loops.
  8. How do you keep your password safe? Use environment variables.
  9. Can you send emails to multiple recipients? Yes, use commas.
  10. What is TLS? A security protocol for email.

๐Ÿ“‹ Review Questions (15)

  1. What is SMTP?
  2. What library do you use to send emails?
  3. How do you create an email message?
  4. How do you set the subject?
  5. How do you set the sender?
  6. How do you set the recipient?
  7. How do you send an email?
  8. How do you personalise emails?
  9. How do you add an attachment?
  10. How do you schedule emails?
  11. How do you keep your password safe?
  12. What is the server for Gmail?
  13. What is the port for Gmail?
  14. What is TLS?
  15. Can you send emails to multiple recipients?

โœ๏ธ Fill-in-the-Blank Exercises

  1. SMTP stands for ______________. (Simple Mail Transfer Protocol)
  2. Use the ______________ library to send emails. (smtplib)
  3. The ______________ class is used to create email messages. (EmailMessage)
  4. Use ______________ to add an attachment. (add_attachment)
  5. Use ______________ to enable TLS. (starttls)

โœ… True or False Exercises

  1. SMTP is used to receive emails. (False)
  2. You need to log in to your email account to send emails. (True)
  3. Attachments cannot be sent with Python. (False)
  4. You can personalise emails with Python. (True)
  5. TLS is used for security. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is SMTP?
    a) Simple Mail Transfer Protocol โœ…
    b) Simple Mail Transmission Protocol
    c) Simple Message Transfer Protocol
  2. What library sends emails?
    a) smtplib โœ…
    b) email
    c) mail
  3. What class creates email messages?
    a) EmailMessage โœ…
    b) Email
    c) Message
  4. How do you set the subject?
    a) msg["Subject"] โœ…
    b) msg.subject
    c) msg.set_subject()
  5. How do you set the sender?
    a) msg["From"] โœ…
    b) msg["Sender"]
    c) msg.set_from()
  6. How do you set the recipient?
    a) msg["To"] โœ…
    b) msg["Receiver"]
    c) msg.set_to()
  7. How do you send an email?
    a) server.send_message(msg) โœ…
    b) server.send(msg)
    c) server.send_email(msg)
  8. How do you personalise emails?
    a) Use variables โœ…
    b) Use the same content
    c) Use a template
  9. How do you add an attachment?
    a) add_attachment() โœ…
    b) attach_file()
    c) add_file()
  10. What is the server for Gmail?
    a) smtp.gmail.com โœ…
    b) smtp.gmail.net
    c) gmail.smtp.com
  11. What is the port for Gmail?
    a) 587 โœ…
    b) 465
    c) 25
  12. What is TLS?
    a) A security protocol โœ…
    b> A type of email
    c) A port
  13. Can you send emails to multiple recipients?
    a) Yes โœ…
    b) No
  14. Can you schedule emails?
    a) Yes โœ…
    b) No
  15. Is email automation useful?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. SMTPA) A security protocol
2. TLSB) Simple Mail Transfer Protocol
3. AttachmentC) The person receiving the email
4. RecipientD) A file sent with an email
5. SubjectE) The title of the email

(Answers: 1-B, 2-A, 3-D, 4-C, 5-E)

๐Ÿ“ Short Answer Questions

  1. What is SMTP and why is it used?
  2. Write a program that sends a "Hello, world!" email.
  3. How can you personalise emails with Python?

๐ŸŽญ Scenario-based Exercises

Scenario 1: You want to send a weekly report to your team. Write a program that sends an email with a report attached.

Scenario 2: You have a list of students and their grades. Write a program that sends each student their grade via email.

๐Ÿ‘ฅ Group Activity

In groups of 3, create a program that sends a group email to everyone in the class. Personalise each email with the person's name.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Write a program that sends an email to yourself with the current date and time. Schedule it to run every day.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • How can email automation save time in your daily life?
  • What are some security concerns with email automation?
  • What other tasks could you automate with email?

๐Ÿ› ๏ธ Mini Project

Create a program that reads a list of students from a CSV file and sends each student a personalised email with their grade.

๐Ÿ“ Practical Assignment

Write a program that sends a daily reminder email to yourself with a list of tasks from a text file.

๐Ÿ† Challenge Exercise

Write a program that reads a CSV file of customer data, generates a personalised invoice for each customer, and sends it as an attachment.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-Simple Mail Transfer Protocol, 2-smtplib, 3-EmailMessage, 4-add_attachment, 5-starttls

True/False: 1-F, 2-T, 3-F, 4-T, 5-T

Matching: 1-B, 2-A, 3-D, 4-C, 5-E

๐ŸŽ Key Takeaways

  • SMTP is used to send emails.
  • Use smtplib and EmailMessage.
  • Set the subject, from, and to.
  • Login to your email account.
  • Use attachments, personalisation, and scheduling.
  • Keep your password secure.

๐Ÿš€ Preparation for the next module

In Module Nine, we will learn about web scraping โ€” extracting data from websites. We will learn how to use Python to get information from web pages automatically. Before the next session, think of a website that has data you would like to collect.

See you in Module Nine! ๐ŸŽ‰


End of Module Eight ยท Automating Emails and Notifications

11

Module Nine

Module Nine ยท Python for Automation

๐ŸŒ Module Nine ยท Web Scraping with Python


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Eight, we learned how to send emails automatically. Now we will learn how to extract data from websites. This is called web scraping. Web scraping is like a robot that reads information from web pages and saves it for you.

In this module, we will learn how to use Python to get data from websites. We will use libraries like requests and BeautifulSoup to fetch and parse web pages. By the end of this module, you will be able to extract data from websites automatically.

๐ŸŽฏ Learning Objectives

  • Understand what web scraping is and why it is useful.
  • Learn how to fetch web pages with Python.
  • Parse HTML and extract data using BeautifulSoup.
  • Extract text, links, and other data from web pages.
  • Use web scraping for real-world automation.

๐Ÿ“š Warm-up Story ยท Emeka's Price Tracker

Emeka is a business owner in Enugu. He wanted to track prices of products on several websites. Every day, he would visit each website, write down prices, and compare them. It took him an hour every day.

His friend told him about web scraping with Python. Emeka wrote a program that visited the websites, extracted the prices, and saved them in a CSV file. Now he gets price updates automatically every day. Emeka saves time and makes better decisions.

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is Web Scraping?

Definition: Web scraping is the process of extracting data from websites automatically.

Why important: Web scraping allows you to collect large amounts of data from the web quickly.

Simple explanation: Like a robot that reads a website and copies the important information.

Real-life example: Extracting product prices from an e-commerce website.

School example: Extracting weather data from a weather website.

Home example: Extracting news headlines from a news website.

Nigerian example: Extracting exchange rates from a financial website.

Illustration:

    Website  โ†’  Python Program  โ†’  Data
    (HTML)        (scrapes)       (CSV, Excel)
            

Mini summary: Web scraping is automatically getting data from websites.


Lesson 2 ยท Installing Libraries

Definition: You need to install requests and beautifulsoup4 to do web scraping.

Why important: These libraries help you fetch web pages and parse HTML.

Simple explanation: Like installing tools before you start a project.

Real-life example: pip install requests beautifulsoup4

School example: Installing libraries to work on a web scraping project.

Home example: Installing libraries to extract data for fun.

Nigerian example: Installing libraries to scrape Nigerian websites.

Illustration:

    pip install requests
    pip install beautifulsoup4
            

Mini summary: Install requests and beautifulsoup4.


Lesson 3 ยท Fetching a Web Page

Definition: You use the requests library to get the content of a web page.

Why important: You need to fetch the page before you can scrape data.

Simple explanation: Like opening a book before you read it.

Real-life example: response = requests.get("https://example.com")

School example: Fetching a school website.

Home example: Fetching a news website.

Nigerian example: Fetching a Nigerian news website.

Illustration:

    import requests
    response = requests.get("https://example.com")
    print(response.text)  # Prints the HTML
            

Mini summary: Use requests.get() to fetch a web page.


Lesson 4 ยท Parsing HTML with BeautifulSoup

Definition: BeautifulSoup is a library that helps you parse (analyse) HTML code.

Why important: It makes it easy to find and extract data from HTML.

Simple explanation: Like using a magnifying glass to find specific words in a book.

Real-life example: soup = BeautifulSoup(response.text, "html.parser")

School example: Parsing a page to find all the headings.

Home example: Parsing a page to find all the links.

Nigerian example: Parsing a page to find all the news headlines.

Illustration:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(response.text, "html.parser")
            

Mini summary: Use BeautifulSoup to parse HTML.


Lesson 5 ยท Finding Data with BeautifulSoup

Definition: You can find data using methods like find(), find_all(), and CSS selectors.

Why important: This is how you extract specific data from a web page.

Simple explanation: Like searching for a word in a book.

Real-life example: soup.find_all("h1") finds all the headings.

School example: Finding all the links on a page.

Home example: Finding all the images on a page.

Nigerian example: Finding all the product prices on a page.

Illustration:

    headings = soup.find_all("h1")
    for heading in headings:
        print(heading.text)
            

Mini summary: Use find_all() to find data.


Lesson 6 ยท Extracting Text

Definition: You can extract text from HTML elements using .text.

Why important: This gives you the human-readable text from a web page.

Simple explanation: Like reading the words on a page.

Real-life example: heading.text gets the text of a heading.

School example: Extracting the title of a web page.

Home example: Extracting the name of a product.

Nigerian example: Extracting the name of a Nigerian news headline.

Illustration:

    title = soup.find("title").text
    print(title)  # Prints the title of the page
            

Mini summary: Use .text to extract text.


Lesson 7 ยท Extracting Links

Definition: You can extract links (URLs) from a tags using the href attribute.

Why important: Links are useful for navigating and collecting data.

Simple explanation: Like getting all the addresses in a list.

Real-life example: soup.find_all("a") finds all links.

School example: Extracting links from a school website.

Home example: Extracting links from a news website.

Nigerian example: Extracting links from a Nigerian blog.

Illustration:

    links = soup.find_all("a")
    for link in links:
        print(link.get("href"))
            

Mini summary: Use get("href") to extract links.


Lesson 8 ยท Extracting Data by Class

Definition: You can find elements by their CSS class.

Why important: Classes are often used to style and identify elements.

Simple explanation: Like finding items with the same label.

Real-life example: soup.find_all(class_="product-price")

School example: Finding all elements with a specific class.

Home example: Finding all elements with a specific class.

Nigerian example: Finding product prices on a Nigerian e-commerce site.

Illustration:

    prices = soup.find_all(class_="price")
    for price in prices:
        print(price.text)
            

Mini summary: Use class_ to find elements by class.


Lesson 9 ยท Using Web Scraping in Automation

Definition: Web scraping is used in many automation tasks: price tracking, news aggregation, data collection, and more.

Why important: It allows you to gather data from many sources automatically.

Simple explanation: Like having a robot that reads websites for you.

Real-life example: A program that tracks the price of a product and alerts you when it drops.

School example: A program that collects weather data for a project.

Home example: A program that collects news headlines for you.

Nigerian example: A program that tracks exchange rates.

Illustration:

    # Scrape product prices from a website
    url = "https://example.com/products"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    prices = soup.find_all(class_="price")
    for price in prices:
        print(price.text)
            

Mini summary: Use web scraping to automate data collection.


Lesson 10 ยท Respecting Websites

Definition: When scraping, you should respect the website's rules and not overload their servers.

Why important: Being respectful ensures you don't get blocked and don't harm the website.

Simple explanation: Like asking permission before borrowing something.

Real-life example: Check the website's robots.txt file.

School example: Only scrape when you have permission.

Home example: Only scrape for personal, non-commercial use.

Nigerian example: Respect the rules of Nigerian websites.

Illustration:

    # Check robots.txt
    # https://example.com/robots.txt
    # Don't scrape too fast
            

Mini summary: Respect websites when scraping.


Lesson 11 ยท Putting It All Together

Definition: You can combine web scraping with other skills to build powerful tools.

Why important: This is how you solve real-world problems.

Simple explanation: Like building a machine that collects and processes data.

Real-life example: A program that scrapes job listings and saves them to a CSV file.

School example: A program that scrapes data for a research project.

Home example: A program that scrapes recipes from a website.

Nigerian example: A program that scrapes Nigerian news and saves it.

Illustration:

    import requests
    from bs4 import BeautifulSoup
    import csv

    url = "https://example.com/news"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    headlines = soup.find_all(class_="headline")

    with open("news.csv", "w") as file:
        writer = csv.writer(file)
        writer.writerow(["Headline"])
        for headline in headlines:
            writer.writerow([headline.text])
            

Mini summary: Combine scraping with other tools to automate tasks.


Lesson 12 ยท You Are Ready!

Definition: You have learned the basics of web scraping with Python.

Why important: You can now collect data from websites automatically.

Simple explanation: You can make Python read websites for you.

Real-life example: You can build a price tracker.

School example: You can collect data for projects.

Home example: You can gather information from the web.

Nigerian example: You can scrape data from Nigerian websites.

Illustration:

    Python + Web Scraping = Data Power! ๐ŸŽ‰
            

Mini summary: You are ready to scrape the web!


๐Ÿ“Œ Key Vocabulary

  • Web scraping: Extracting data from websites.
  • HTML: The code used to create web pages.
  • Parser: A tool that analyses HTML.
  • requests: A library for fetching web pages.
  • BeautifulSoup: A library for parsing HTML.
  • Tag: An HTML element (e.g., h1, p, a).
  • Attribute: A property of a tag (e.g., href, class).
  • Selector: A way to find elements.
  • robots.txt: A file that tells scrapers what is allowed.
  • Data: Information you extract.

๐Ÿง  Important Concepts

  • Fetch first: Get the web page with requests.
  • Parse then extract: Use BeautifulSoup to find data.
  • Be respectful: Don't overload websites.
  • Use data wisely: Save and process the data.
  • Web scraping is powerful: It can collect huge amounts of data.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Scrape a Web Page in 5 Steps

  1. Import libraries: import requests; from bs4 import BeautifulSoup
  2. Fetch the page: response = requests.get("https://example.com")
  3. Parse the HTML: soup = BeautifulSoup(response.text, "html.parser")
  4. Find the data: data = soup.find_all("tag", class_="class")
  5. Extract and use: for item in data: print(item.text)

Example:

    import requests
    from bs4 import BeautifulSoup

    response = requests.get("https://example.com")
    soup = BeautifulSoup(response.text, "html.parser")
    headlines = soup.find_all("h1")
    for headline in headlines:
        print(headline.text)
            

๐ŸŒ Real-life Examples

  • Fetching: response = requests.get("https://example.com")
  • Parsing: soup = BeautifulSoup(response.text, "html.parser")
  • Extracting text: soup.find("h1").text
  • Extracting links: soup.find_all("a")
  • Extracting by class: soup.find_all(class_="price")

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • News headlines: soup.find_all(class_="headline") on a Nigerian news site.
  • Product prices: soup.find_all(class_="price") on a Nigerian e-commerce site.
  • Exchange rates: soup.find_all(class_="rate") on a financial site.
  • Job listings: soup.find_all(class_="job-title") on a job site.
  • Weather: soup.find(class_="temperature").text on a weather site.

๐ŸŽˆ Fun Examples children can relate to

  • soup.find_all("h1") to find all the big titles on a page.
  • soup.find_all("a") to find all the links.
  • soup.find_all("img") to find all the images.
  • soup.find_all("p") to find all the paragraphs.
  • soup.find_all(class_="fun") to find all the fun elements.

๐Ÿ  Everyday Examples

  • Weather: soup.find(class_="temp").text to get the temperature.
  • News: soup.find_all(class_="headline") to get headlines.
  • Movies: soup.find_all(class_="movie-title") to get movie titles.
  • Recipes: soup.find_all(class_="recipe-name") to get recipe names.
  • Sports: soup.find_all(class_="score") to get scores.

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to scrape simple websites.
  • Use local examples to make it relatable.
  • Discuss the importance of respecting websites.
  • Have students create programs that scrape and save data.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child scrape simple websites.
  • Write programs together that collect data.
  • Encourage them to think of data they can collect.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Web scraping is used by many businesses.
  • Python is one of the best languages for scraping.
  • BeautifulSoup is used by thousands of developers.
  • Scraping can collect data from millions of pages.
  • Many websites have APIs as an alternative to scraping.

๐Ÿ’ก Did You Know?

  • Did you know that Google uses web scraping for search results?
  • Did you know that you can scrape data from social media?
  • Did you know that you can scrape data from news websites?
  • Did you know that web scraping can save hours of work?
  • Did you know that you can save scraped data to CSV or Excel?

๐Ÿงท Remember This

  • Fetch web pages with requests.
  • Parse HTML with BeautifulSoup.
  • Use find_all() to find elements.
  • Use .text to get text.
  • Use get("href") to get links.
  • Respect websites and their rules.

โš ๏ธ Common Mistakes

  • Wrong URL: Using a broken or incorrect URL.
  • No permissions: Scraping against the rules.
  • Not checking status: Not checking if the page loaded.
  • Wrong class: Using the wrong class name.
  • No parsing: Forgetting to parse the HTML.

โœ… Best Practices

  • Check the website's robots.txt file.
  • Use a delay between requests to avoid overloading.
  • Handle errors gracefully.
  • Save data to a file for later use.
  • Use specific selectors to get the right data.

๐ŸŽจ Illustrations, Diagrams & Tables

Web Scraping Flow

    +----------------------+
    | Fetch Web Page       |
    | (requests.get())     |
    +----------------------+
              |
              V
    +----------------------+
    | Parse HTML           |
    | (BeautifulSoup)      |
    +----------------------+
              |
              V
    +----------------------+
    | Find Data            |
    | (find_all(), etc.)   |
    +----------------------+
              |
              V
    +----------------------+
    | Extract & Use Data   |
    | (save to file, etc.) |
    +----------------------+
            

Common BeautifulSoup Methods

MethodDescription
find()Finds the first matching element
find_all()Finds all matching elements
.textExtracts text from an element
get("href")Extracts a link from an a tag
class_Finds elements by class

Scraping Example

    import requests
    from bs4 import BeautifulSoup

    url = "https://example.com"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")

    # Find all headings
    headings = soup.find_all("h1")
    for heading in headings:
        print(heading.text)
            

๐Ÿ“ End-of-Module Summary

In this module, we learned about web scraping with Python. We discovered that web scraping is the process of extracting data from websites automatically. We learned how to fetch web pages using the requests library and how to parse HTML using BeautifulSoup. We also learned how to extract data using various methods. With web scraping, you can collect data from the web and use it for automation. Great work!

โ“ Frequently Asked Questions (10)

  1. What is web scraping? Extracting data from websites.
  2. What libraries do you need? requests and beautifulsoup4.
  3. How do you fetch a web page? requests.get(url)
  4. How do you parse HTML? BeautifulSoup(response.text, "html.parser")
  5. How do you find data? find_all(), find(), etc.
  6. How do you extract text? Use .text.
  7. How do you extract links? get("href")
  8. What is robots.txt? A file that tells scrapers what is allowed.
  9. Can you save scraped data? Yes, to CSV, Excel, etc.
  10. Is web scraping legal? It depends on the website's rules.

๐Ÿ“‹ Review Questions (15)

  1. What is web scraping?
  2. What library is used to fetch web pages?
  3. What library is used to parse HTML?
  4. How do you fetch a web page?
  5. How do you parse HTML?
  6. How do you find all elements of a certain tag?
  7. How do you extract text from an element?
  8. How do you extract a link from an a tag?
  9. How do you find elements by class?
  10. What is robots.txt?
  11. Why should you respect websites?
  12. How do you save scraped data?
  13. What is the purpose of web scraping?
  14. What is the difference between find() and find_all()?
  15. Can you scrape any website?

โœ๏ธ Fill-in-the-Blank Exercises

  1. Web scraping is extracting data from ______________. (websites)
  2. Use the ______________ library to fetch web pages. (requests)
  3. Use ______________ to parse HTML. (BeautifulSoup)
  4. Use ______________ to find all elements. (find_all)
  5. Use ______________ to extract text from an element. (.text)

โœ… True or False Exercises

  1. Web scraping is extracting data from websites. (True)
  2. You need to install requests and beautifulsoup4. (True)
  3. find_all() finds the first element. (False)
  4. .text extracts text from an element. (True)
  5. You should always respect websites when scraping. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is web scraping?
    a) Extracting data from websites โœ…
    b) Building websites
    c) Sending emails
  2. What library fetches web pages?
    a) requests โœ…
    b) BeautifulSoup
    c) csv
  3. What library parses HTML?
    a) requests
    b) BeautifulSoup โœ…
    c) smtplib
  4. How do you fetch a web page?
    a) requests.get(url) โœ…
    b) requests.fetch(url)
    c) requests.open(url)
  5. How do you parse HTML?
    a) BeautifulSoup(response.text, "html.parser") โœ…
    b) parse(response.text)
    c) html.parse(response.text)
  6. How do you find all elements?
    a) find_all() โœ…
    b) find()
    c) search()
  7. How do you extract text?
    a) .text โœ…
    b) .get()
    c) .content
  8. How do you extract a link?
    a) get("href") โœ…
    b) get("link")
    c) get("url")
  9. How do you find elements by class?
    a) class_ โœ…
    b) class
    c) className
  10. What is robots.txt?
    a) A file that tells scrapers what is allowed โœ…
    b) A file with robot names
    c) A file with website data
  11. Why should you respect websites?
    a) To avoid being blocked โœ…
    b) To get more data
    c) To make them happy
  12. Can you save scraped data?
    a) Yes โœ…
    b) No
  13. What is the purpose of web scraping?
    a) To collect data automatically โœ…
    b) To build websites
    c) To send emails
  14. What is the difference between find() and find_all()?
    a) find() finds one, find_all() finds all โœ…
    b) find() finds all, find_all() finds one
    c) They are the same
  15. Can you scrape any website?
    a) No, you must follow rules โœ…
    b) Yes, all websites
    c) Only some websites

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. Web scrapingA) A library for fetching web pages
2. requestsB) A library for parsing HTML
3. BeautifulSoupC) Extracting data from websites
4. find_all()D) Finds all matching elements
5. robots.txtE) A file that tells scrapers what is allowed

(Answers: 1-C, 2-A, 3-B, 4-D, 5-E)

๐Ÿ“ Short Answer Questions

  1. What is web scraping and why is it useful?
  2. Write a program that fetches a web page and prints its title.
  3. How can you find all the links on a web page?

๐ŸŽญ Scenario-based Exercises

Scenario 1: You want to collect headlines from a news website. Write a program that extracts the headlines and saves them to a file.

Scenario 2: You want to track the price of a product on an e-commerce website. Write a program that extracts the price and prints it.

๐Ÿ‘ฅ Group Activity

In groups of 3, choose a website to scrape. Write a program that extracts specific data from the website and saves it to a CSV file.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Write a program that scrapes the titles of the top 5 news articles from a news website and prints them.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • What are some ethical considerations of web scraping?
  • How can web scraping be used in business?
  • What other data would you like to scrape?

๐Ÿ› ๏ธ Mini Project

Create a program that scrapes the latest news headlines from a website and sends them to you via email.

๐Ÿ“ Practical Assignment

Write a program that scrapes product prices from a website and alerts you when the price drops below a certain value.

๐Ÿ† Challenge Exercise

Write a program that scrapes data from multiple pages of a website and saves all the data to a single CSV file.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-websites, 2-requests, 3-BeauitfulSoup, 4-find_all, 5-.text

True/False: 1-T, 2-T, 3-F, 4-T, 5-T

Matching: 1-C, 2-A, 3-B, 4-D, 5-E

๐ŸŽ Key Takeaways

  • Web scraping is extracting data from websites.
  • Use requests to fetch web pages.
  • Use BeautifulSoup to parse HTML.
  • Use find_all(), find(), etc. to find data.
  • Respect websites and their rules.

๐Ÿš€ Preparation for the next module

In Module Ten, we will learn about automating browser tasks with Selenium. We will learn how to control a web browser automatically. Before the next session, think of a task you do in a web browser that you would like to automate.

See you in Module Ten! ๐ŸŽ‰


End of Module Nine ยท Web Scraping with Python

12

Module Ten

Module Ten ยท Python for Automation

๐Ÿ–ฅ๏ธ Module Ten ยท Automating Browser Tasks with Selenium


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Nine, we learned how to extract data from websites using web scraping. But what if we need to interact with a website โ€” like clicking buttons, filling forms, or logging in? That's where Selenium comes in.

In this module, we will learn how to use Selenium to control a web browser automatically. Selenium can open websites, click links, type text, and even take screenshots. By the end of this module, you will be able to automate many tasks that you normally do in a web browser.

๐ŸŽฏ Learning Objectives

  • Understand what Selenium is and why it is useful.
  • Install Selenium and set up a web driver.
  • Open websites and interact with them.
  • Click buttons, fill forms, and login automatically.
  • Take screenshots and extract data using Selenium.

๐Ÿ“š Warm-up Story ยท Grace's Automated Login

Grace is a student in Lagos. Every morning, she had to log in to the school portal to check her grades. She typed her username and password every day. It was boring and took time.

Her friend told her about Selenium. Grace wrote a program that opened the browser, went to the portal, entered her username and password, and clicked the login button. Now she runs the program and it does everything for her. Grace saves time every day!

๐Ÿงฉ Main Lessons

Lesson 1 ยท What is Selenium?

Definition: Selenium is a tool that allows you to control a web browser automatically.

Why important: Selenium can automate tasks in any web application.

Simple explanation: Like a robot that uses a web browser for you.

Real-life example: Automating login to a website.

School example: Automating checking grades online.

Home example: Automating paying bills online.

Nigerian example: Automating checking bank account balance.

Illustration:

    Python  โ†’  Selenium  โ†’  Browser  โ†’  Website
    (code)      (driver)     (Chrome)   (action)
            

Mini summary: Selenium controls a web browser automatically.


Lesson 2 ยท Installing Selenium

Definition: You need to install Selenium and a web driver (like ChromeDriver).

Why important: This is how you set up Selenium on your computer.

Simple explanation: Like installing a tool before you start a project.

Real-life example: pip install selenium

School example: Installing Selenium for a project.

Home example: Installing Selenium to automate tasks.

Nigerian example: Installing Selenium for business automation.

Illustration:

    pip install selenium
    # Download ChromeDriver from https://chromedriver.chromium.org/
            

Mini summary: Install Selenium and a web driver.


Lesson 3 ยท Starting a Browser

Definition: You start a browser using the web driver.

Why important: This opens a browser window that Selenium can control.

Simple explanation: Like opening a browser and handing it to a robot.

Real-life example: from selenium import webdriver; driver = webdriver.Chrome()

School example: Starting a browser to automate a task.

Home example: Starting a browser to automate a task.

Nigerian example: Starting a browser to automate a task.

Illustration:

    from selenium import webdriver
    driver = webdriver.Chrome()
    driver.get("https://example.com")
            

Mini summary: Use webdriver.Chrome() to start a browser.


Lesson 4 ยท Opening a Website

Definition: You use driver.get(url) to open a website.

Why important: This is how you navigate to a web page.

Simple explanation: Like typing a URL in the address bar.

Real-life example: driver.get("https://example.com")

School example: Opening the school portal.

Home example: Opening a shopping website.

Nigerian example: Opening a bank website.

Illustration:

    driver.get("https://example.com")
            

Mini summary: Use driver.get() to open a website.


Lesson 5 ยท Finding Elements

Definition: You find elements on a web page using find_element() or find_elements().

Why important: You need to find elements to interact with them.

Simple explanation: Like finding a button on a page.

Real-life example: driver.find_element("id", "username")

School example: Finding the login form.

Home example: Finding the search box.

Nigerian example: Finding the login button.

Illustration:

    # Find by ID
    element = driver.find_element("id", "username")
    # Find by class
    element = driver.find_element("class name", "btn")
            

Mini summary: Use find_element() to find elements.


Lesson 6 ยท Interacting with Elements

Definition: You can interact with elements using methods like click(), send_keys(), and clear().

Why important: This is how you fill forms, click buttons, and more.

Simple explanation: Like typing and clicking on a web page.

Real-life example: element.send_keys("username")

School example: Entering a student ID.

Home example: Entering a search term.

Nigerian example: Entering a phone number.

Illustration:

    username = driver.find_element("id", "username")
    username.send_keys("my_username")
    password = driver.find_element("id", "password")
    password.send_keys("my_password")
    login_btn = driver.find_element("id", "login")
    login_btn.click()
            

Mini summary: Use send_keys(), click(), etc. to interact.


Lesson 7 ยท Automating Login

Definition: You can automate login by finding the form elements, entering data, and clicking the login button.

Why important: This is a very common automation task.

Simple explanation: Like having a robot log in for you.

Real-life example: Automating login to your email.

School example: Automating login to the school portal.

Home example: Automating login to a social media account.

Nigerian example: Automating login to a bank account.

Illustration:

    driver.get("https://example.com/login")
    username = driver.find_element("id", "username")
    username.send_keys("my_username")
    password = driver.find_element("id", "password")
    password.send_keys("my_password")
    login_btn = driver.find_element("id", "login")
    login_btn.click()
            

Mini summary: Automate login with Selenium.


Lesson 8 ยท Filling Forms

Definition: You can fill forms by finding input fields and sending text.

Why important: This allows you to automate data entry.

Simple explanation: Like filling an online form automatically.

Real-life example: Automating a job application.

School example: Automating a survey.

Home example: Automating a shopping order.

Nigerian example: Automating a registration form.

Illustration:

    name = driver.find_element("id", "name")
    name.send_keys("Aisha Bello")
    email = driver.find_element("id", "email")
    email.send_keys("aisha@email.com")
    submit = driver.find_element("id", "submit")
    submit.click()
            

Mini summary: Fill forms with send_keys().


Lesson 9 ยท Taking Screenshots

Definition: You can take screenshots of the current browser window using save_screenshot().

Why important: This allows you to capture visual proof of your automation.

Simple explanation: Like taking a picture of the screen.

Real-life example: driver.save_screenshot("screenshot.png")

School example: Saving a screenshot of your grades.

Home example: Saving a screenshot of a recipe.

Nigerian example: Saving a screenshot of a transaction.

Illustration:

    driver.save_screenshot("page.png")
            

Mini summary: Use save_screenshot() to take screenshots.


Lesson 10 ยท Waiting for Elements

Definition: Sometimes web pages take time to load. You can use WebDriverWait to wait for elements.

Why important: This prevents errors from trying to interact with elements that haven't loaded.

Simple explanation: Like waiting for a page to finish loading.

Real-life example: WebDriverWait(driver, 10).until(EC.presence_of_element_located(("id", "username")))

School example: Waiting for the login page to load.

Home example: Waiting for the search results to load.

Nigerian example: Waiting for the bank portal to load.

Illustration:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    wait = WebDriverWait(driver, 10)
    username = wait.until(EC.presence_of_element_located(("id", "username")))
            

Mini summary: Use WebDriverWait to wait for elements.


Lesson 11 ยท Closing the Browser

Definition: You can close the browser using driver.quit().

Why important: This ensures the browser is properly closed after automation.

Simple explanation: Like closing a browser window.

Real-life example: driver.quit()

School example: Closing the browser after checking grades.

Home example: Closing the browser after shopping.

Nigerian example: Closing the browser after a transaction.

Illustration:

    driver.quit()
            

Mini summary: Use driver.quit() to close the browser.


Lesson 12 ยท Using Selenium in Automation

Definition: Selenium can be used to automate many tasks: logging in, filling forms, extracting data, and more.

Why important: It allows you to automate tasks that require a web browser.

Simple explanation: Like having a robot that uses the internet for you.

Real-life example: Automating social media posting.

School example: Automating checking online grades.

Home example: Automating online shopping.

Nigerian example: Automating bank transactions.

Illustration:

    # Automate checking grades
    driver.get("https://schoolportal.com/login")
    # Login
    # Check grades
    # Save screenshot
    driver.quit()
            

Mini summary: Use Selenium for many automation tasks.


Lesson 13 ยท You Are Ready!

Definition: You have learned how to use Selenium to automate browser tasks.

Why important: You can now automate any web-based task.

Simple explanation: You can make Python use the web browser for you.

Real-life example: You can automate your daily web tasks.

School example: You can automate checking grades.

Home example: You can automate shopping.

Nigerian example: You can automate bank tasks.

Illustration:

    Python + Selenium = Web Automation Power! ๐ŸŽ‰
            

Mini summary: You are ready to automate web tasks!


๐Ÿ“Œ Key Vocabulary

  • Selenium: A tool for automating web browsers.
  • Web Driver: A program that controls the browser.
  • Element: A part of a web page (button, input, etc.).
  • Click: To press a button.
  • Send keys: To type text into an input.
  • Screenshot: An image of the browser window.
  • Wait: To pause until an element is ready.
  • Quit: To close the browser.
  • Automate: To make a task automatic.
  • Browser: A program like Chrome, Firefox, etc.

๐Ÿง  Important Concepts

  • Selenium controls browsers: It can open, click, type, and more.
  • Find elements first: Before interacting, find the element.
  • Wait for elements: Web pages take time to load.
  • Close the browser: Always close the browser after automation.
  • Web automation is powerful: It can save hours of work.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Automate Login with Selenium

  1. Import libraries: from selenium import webdriver
  2. Start the browser: driver = webdriver.Chrome()
  3. Open the login page: driver.get("https://example.com/login")
  4. Find username field: username = driver.find_element("id", "username")
  5. Enter username: username.send_keys("my_username")
  6. Find password field: password = driver.find_element("id", "password")
  7. Enter password: password.send_keys("my_password")
  8. Click login button: login_btn = driver.find_element("id", "login"); login_btn.click()
  9. Wait for page to load: import time; time.sleep(2)
  10. Close browser: driver.quit()

Example:

    from selenium import webdriver
    import time

    driver = webdriver.Chrome()
    driver.get("https://example.com/login")

    username = driver.find_element("id", "username")
    username.send_keys("my_username")

    password = driver.find_element("id", "password")
    password.send_keys("my_password")

    login_btn = driver.find_element("id", "login")
    login_btn.click()

    time.sleep(2)
    driver.quit()
            

๐ŸŒ Real-life Examples

  • Login: driver.get("https://example.com/login"); username.send_keys("user"); password.send_keys("pass"); login_btn.click()
  • Search: search = driver.find_element("name", "q"); search.send_keys("Python"); search.submit()
  • Form: name.send_keys("Aisha"); email.send_keys("aisha@email.com"); submit.click()
  • Screenshot: driver.save_screenshot("page.png")
  • Wait: WebDriverWait(driver, 10).until(EC.presence_of_element_located(("id", "username")))

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Bank login: driver.get("https://bank.com/login"); username.send_keys("1234567890"); password.send_keys("my_password"); login_btn.click()
  • School portal: driver.get("https://schoolportal.com"); username.send_keys("student_id"); password.send_keys("password"); login_btn.click()
  • E-commerce: search = driver.find_element("name", "search"); search.send_keys("rice"); search.submit()
  • Form: name.send_keys("Chidi"); email.send_keys("chidi@email.com"); submit.click()
  • Screenshot: driver.save_screenshot("transaction.png")

๐ŸŽˆ Fun Examples children can relate to

  • driver.get("https://google.com"); search.send_keys("funny cats"); search.submit()
  • driver.get("https://youtube.com"); search.send_keys("Python for kids"); search.submit()
  • driver.get("https://example.com"); driver.save_screenshot("page.png")
  • driver.get("https://example.com"); print(driver.title)
  • driver.get("https://example.com"); driver.quit()

๐Ÿ  Everyday Examples

  • Email: driver.get("https://gmail.com"); username.send_keys("my_email"); password.send_keys("my_password"); login_btn.click()
  • Shopping: driver.get("https://amazon.com"); search.send_keys("books"); search.submit()
  • News: driver.get("https://bbc.com"); headlines = driver.find_elements("class", "headline"); for headline in headlines: print(headline.text)
  • Weather: driver.get("https://weather.com"); temp = driver.find_element("class", "temp"); print(temp.text)
  • Social media: driver.get("https://twitter.com"); login_btn.click()

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to automate a simple login task.
  • Use local examples to make it relatable.
  • Discuss the power and responsibility of automation.
  • Have students create programs that automate browser tasks.
  • Celebrate every program they write.

๐Ÿ‘ช Parent Tips

  • Help your child set up Selenium and a web driver.
  • Write programs together that automate simple tasks.
  • Encourage them to think of tasks they can automate.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Selenium is used by many companies for testing.
  • Selenium supports multiple browsers.
  • Selenium can automate complex workflows.
  • Web automation saves millions of hours.
  • Selenium is one of the most popular automation tools.

๐Ÿ’ก Did You Know?

  • Did you know that Selenium can run headless (without a visible browser)?
  • Did you know that you can use Selenium with Firefox, Edge, and Safari?
  • Did you know that Selenium can take screenshots of specific elements?
  • Did you know that Selenium can execute JavaScript?
  • Did you know that Selenium is open-source?

๐Ÿงท Remember This

  • Selenium controls web browsers.
  • Find elements before interacting with them.
  • Use send_keys() to type text.
  • Use click() to click buttons.
  • Use WebDriverWait to wait for elements.
  • Always close the browser with driver.quit().

โš ๏ธ Common Mistakes

  • Wrong driver: Not having the correct web driver.
  • Element not found: Using the wrong selector.
  • Not waiting: Trying to interact with elements that haven't loaded.
  • Not closing: Forgetting to close the browser.
  • Wrong URL: Using an incorrect URL.

โœ… Best Practices

  • Use WebDriverWait for loading pages.
  • Use unique selectors (ID, name, etc.).
  • Always close the browser after automation.
  • Handle exceptions gracefully.
  • Test with small scripts first.

๐ŸŽจ Illustrations, Diagrams & Tables

Selenium Flow

    +----------------------+
    | Start Browser        |
    | webdriver.Chrome()   |
    +----------------------+
              |
              V
    +----------------------+
    | Open Website         |
    | driver.get(url)      |
    +----------------------+
              |
              V
    +----------------------+
    | Find Elements        |
    | find_element()       |
    +----------------------+
              |
              V
    +----------------------+
    | Interact             |
    | send_keys(), click() |
    +----------------------+
              |
              V
    +----------------------+
    | Close Browser        |
    | driver.quit()        |
    +----------------------+
            

Common Selenium Methods

MethodDescription
driver.get(url)Opens a URL
driver.find_element(by, value)Finds an element
element.send_keys(text)Types text
element.click()Clicks an element
driver.save_screenshot(file)Takes a screenshot

Comparison: Selenium vs BeautifulSoup

SeleniumBeautifulSoup
Controls browserParses HTML
Can interact with pagesOnly extracts data
SlowerFaster
Handles JavaScriptDoesn't handle JavaScript

๐Ÿ“ End-of-Module Summary

In this module, we learned how to use Selenium to automate browser tasks. We discovered that Selenium can control a web browser, allowing us to interact with websites automatically. We learned how to start a browser, open websites, find elements, and interact with them. We also learned how to wait for elements, take screenshots, and close the browser. With Selenium, you can automate many web-based tasks. Great work!

โ“ Frequently Asked Questions (10)

  1. What is Selenium? A tool for automating web browsers.
  2. How do you install Selenium? pip install selenium
  3. What is a web driver? A program that controls the browser.
  4. How do you start a browser? driver = webdriver.Chrome()
  5. How do you open a website? driver.get(url)
  6. How do you find an element? driver.find_element(by, value)
  7. How do you type text? element.send_keys(text)
  8. How do you click a button? element.click()
  9. How do you take a screenshot? driver.save_screenshot(file)
  10. How do you close the browser? driver.quit()

๐Ÿ“‹ Review Questions (15)

  1. What is Selenium?
  2. How do you install Selenium?
  3. What is a web driver?
  4. How do you start a browser?
  5. How do you open a website?
  6. How do you find an element?
  7. How do you type text into an input field?
  8. How do you click a button?
  9. How do you take a screenshot?
  10. How do you wait for an element?
  11. How do you close the browser?
  12. What is the difference between find_element() and find_elements()?
  13. What is WebDriverWait used for?
  14. Can Selenium handle JavaScript?
  15. What is one common use of Selenium?

โœ๏ธ Fill-in-the-Blank Exercises

  1. Selenium is a tool for automating ______________. (web browsers)
  2. Use ______________ to start a Chrome browser. (webdriver.Chrome())
  3. Use ______________ to open a website. (driver.get(url))
  4. Use ______________ to type text into an element. (send_keys)
  5. Use ______________ to click an element. (click)

โœ… True or False Exercises

  1. Selenium is used to automate web browsers. (True)
  2. You can use Selenium with Chrome only. (False)
  3. find_element() finds one element. (True)
  4. send_keys() is used to type text. (True)
  5. driver.quit() closes the browser. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is Selenium?
    a) A tool for automating web browsers โœ…
    b) A tool for web scraping
    c) A tool for sending emails
  2. How do you install Selenium?
    a) pip install selenium โœ…
    b) install selenium
    c) pip get selenium
  3. What is a web driver?
    a) A program that controls the browser โœ…
    b) A web page
    c) A type of website
  4. How do you start a browser?
    a) webdriver.Chrome() โœ…
    b) start.browser()
    c) open.browser()
  5. How do you open a website?
    a) driver.get(url) โœ…
    b) driver.open(url)
    c) driver.navigate(url)
  6. How do you find an element?
    a) driver.find_element(by, value) โœ…
    b) driver.find(by, value)
    c) driver.element(by, value)
  7. How do you type text?
    a) element.send_keys(text) โœ…
    b) element.type(text)
    c) element.enter(text)
  8. How do you click a button?
    a) element.click() โœ…
    b) element.press()
    c) element.select()
  9. How do you take a screenshot?
    a) driver.save_screenshot(file) โœ…
    b) driver.screenshot(file)
    c) driver.capture(file)
  10. How do you wait for an element?
    a) WebDriverWait โœ…
    b) time.sleep()
    c) wait_for_element()
  11. How do you close the browser?
    a) driver.quit() โœ…
    b) driver.close()
    c) driver.stop()
  12. Can Selenium handle JavaScript?
    a) Yes โœ…
    b) No
  13. What is find_elements()?
    a) Finds all matching elements โœ…
    b) Finds one element
    c) Finds no elements
  14. Is Selenium only for testing?
    a) No, it is also used for automation โœ…
    b) Yes, only for testing
  15. Can Selenium automate login?
    a) Yes โœ…
    b) No

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. SeleniumA) Opens a website
2. WebDriverB) Closes the browser
3. driver.get()C) A tool for automating browsers
4. send_keys()D) Types text into an element
5. driver.quit()E) A program that controls the browser

(Answers: 1-C, 2-E, 3-A, 4-D, 5-B)

๐Ÿ“ Short Answer Questions

  1. What is Selenium and what is it used for?
  2. Write a program that opens Google and searches for "Python".
  3. How do you find an element and click it?

๐ŸŽญ Scenario-based Exercises

Scenario 1: You want to automate logging into your email account. Write a program that opens the login page, enters your username and password, and clicks the login button.

Scenario 2: You want to take a screenshot of a weather website every day. Write a program that opens the website and saves a screenshot.

๐Ÿ‘ฅ Group Activity

In groups of 3, create a program that automates a common web task (like checking the weather, getting news, or checking grades).

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Write a program that automates logging into a website of your choice. Take a screenshot after login.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • How can Selenium be used in business?
  • What are some ethical considerations of web automation?
  • What other tasks would you like to automate?

๐Ÿ› ๏ธ Mini Project

Create a program that automates a complete workflow: login, extract data, take a screenshot, and save the data to a file.

๐Ÿ“ Practical Assignment

Write a program that automates filling a form on a website. Include at least 5 fields.

๐Ÿ† Challenge Exercise

Write a program that logs into a website, navigates to a specific page, extracts data, and saves it to a CSV file.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-web browsers, 2-webdriver.Chrome(), 3-driver.get(url), 4-send_keys, 5-click

True/False: 1-T, 2-F, 3-T, 4-T, 5-T

Matching: 1-C, 2-E, 3-A, 4-D, 5-B

๐ŸŽ Key Takeaways

  • Selenium controls web browsers automatically.
  • Use driver.get() to open websites.
  • Use find_element() to find elements.
  • Use send_keys() to type text.
  • Use click() to click buttons.
  • Use WebDriverWait to wait for elements.
  • Always close the browser with driver.quit().

๐Ÿš€ Preparation for the next module

In Module Eleven, we will learn about scheduling scripts to run automatically. We will learn how to use Task Scheduler and cron to run your Python scripts at specific times. Before the next session, think of a script you would like to schedule.

See you in Module Eleven! ๐ŸŽ‰


End of Module Ten ยท Automating Browser Tasks with Selenium

13

Module Eleven

Module Eleven ยท Python for Automation

โฐ Module Eleven ยท Scheduling and Running Scripts


๐Ÿ“– Module Introduction

Hello, future automation expert! In Module Ten, we learned how to automate browser tasks with Selenium. Now we will learn how to schedule our scripts to run automatically at specific times. This is very useful for tasks that need to happen regularly โ€” like daily reports, weekly backups, or monthly summaries.

In this module, we will learn how to use Task Scheduler (on Windows) and cron (on macOS and Linux) to run Python scripts automatically. By the end of this module, you will be able to set up scripts to run on a schedule!

๐ŸŽฏ Learning Objectives

  • Understand why scheduling scripts is useful.
  • Learn how to schedule scripts on Windows using Task Scheduler.
  • Learn how to schedule scripts on macOS and Linux using cron.
  • Schedule scripts to run at specific times (daily, weekly, etc.).
  • Automate regular tasks with scheduled scripts.

๐Ÿ“š Warm-up Story ยท Fatima's Daily Report

Fatima is a business owner in Kano. Every morning, she needed to run a Python script that generated a sales report. She used to run it manually every day. Sometimes she forgot, and then she didn't have the report for the meeting.

Her IT friend told her about scheduling. Fatima set up Task Scheduler to run her script every day at 8am. Now the report is ready when she arrives at work. Fatima never forgets and saves time every day!

๐Ÿงฉ Main Lessons

Lesson 1 ยท Why Schedule Scripts?

Definition: Scheduling means setting a script to run automatically at a specific time.

Why important: It saves time and ensures tasks are done regularly.

Simple explanation: Like setting an alarm to wake you up.

Real-life example: A script that sends a daily report email.

School example: A script that checks grades every day.

Home example: A script that backs up photos every week.

Nigerian example: A script that checks exchange rates daily.

Illustration:

    Without Schedule:  You run it manually
    With Schedule:     Computer runs it automatically
            

Mini summary: Scheduling automates regular tasks.


Lesson 2 ยท Task Scheduler (Windows)

Definition: Task Scheduler is a Windows tool that lets you schedule tasks to run automatically.

Why important: It's built into Windows and easy to use.

Simple explanation: Like a calendar for your computer tasks.

Real-life example: Scheduling a script to run every morning.

School example: Scheduling a script to run after school.

Home example: Scheduling a script to run on weekends.

Nigerian example: Scheduling a script to run at a specific time.

Illustration:

    Task Scheduler:
    +----------------------+
    | Task Name: Daily Report |
    | Trigger: Every day at 8am |
    | Action: Run Python script |
    +----------------------+
            

Mini summary: Task Scheduler schedules tasks on Windows.


Lesson 3 ยท Cron (macOS / Linux)

Definition: Cron is a tool on macOS and Linux that schedules tasks.

Why important: It's the standard tool for scheduling on these systems.

Simple explanation: Like Task Scheduler, but for macOS and Linux.

Real-life example: crontab -e to edit schedules.

School example: Scheduling a script to run at a specific time.

Home example: Scheduling a script to run on weekends.

Nigerian example: Scheduling a script to run daily.

Illustration:

    Cron Example:
    0 8 * * * python /path/to/script.py
    (Runs at 8am every day)
            

Mini summary: Cron schedules tasks on macOS and Linux.


Lesson 4 ยท Creating a Simple Script to Schedule

Definition: You need a Python script that does something useful โ€” like sending an email or saving data.

Why important: The script is what will run automatically.

Simple explanation: Like a recipe that you want to cook on a schedule.

Real-life example: A script that sends a daily greeting email.

School example: A script that saves the current time to a file.

Home example: A script that backs up files.

Nigerian example: A script that checks the weather in Lagos.

Illustration:

    # save_time.py
    import datetime
    with open("time.txt", "a") as file:
        file.write(str(datetime.datetime.now()) + "\n")
            

Mini summary: Create a script to run on a schedule.


Lesson 5 ยท Scheduling on Windows

Definition: You use Task Scheduler to schedule a script on Windows.

Why important: This is how you make your script run automatically.

Simple explanation: Like setting a reminder.

Real-life example: Task Scheduler runs python C:\script.py every day.

School example: Scheduling a script to run after school.

Home example: Scheduling a script to run every hour.

Nigerian example: Scheduling a script to run at 9am.

Illustration:

    Task Scheduler Steps:
    1. Open Task Scheduler
    2. Create Basic Task
    3. Set Trigger (when to run)
    4. Set Action (what to run)
    5. Finish
            

Mini summary: Use Task Scheduler to schedule scripts on Windows.


Lesson 6 ยท Scheduling on macOS / Linux

Definition: You use cron to schedule a script on macOS or Linux.

Why important: This is how you make your script run automatically.

Simple explanation: Like setting a reminder.

Real-life example: 0 8 * * * python /path/to/script.py

School example: Scheduling a script to run at a specific time.

Home example: Scheduling a script to run every hour.

Nigerian example: Scheduling a script to run daily.

Illustration:

    Cron Syntax:
    minute hour day month day_of_week command
    Example: 0 8 * * * python /home/user/script.py
            

Mini summary: Use cron to schedule scripts on macOS and Linux.


Lesson 7 ยท Common Scheduling Patterns

Definition: You can schedule scripts to run at many different intervals.

Why important: This gives you flexibility.

Simple explanation: Like choosing how often to repeat a task.

Real-life example: Daily, weekly, monthly, or hourly.

School example: Daily for homework checks.

Home example: Weekly for backups.

Nigerian example: Monthly for reports.

Illustration:

    Common Schedules:
    Every day:     0 0 * * *
    Every hour:    0 * * * *
    Every minute:  * * * * *
    Weekly:        0 0 * * 0  (Sunday)
            

Mini summary: Schedule scripts at different intervals.


Lesson 8 ยท Tips for Scheduling

Definition: There are some best practices for scheduling scripts.

Why important: This helps avoid errors and problems.

Simple explanation: Like making sure your script works before you schedule it.

Real-life example: Test your script before scheduling.

School example: Make sure the script runs without errors.

Home example: Use full paths in your scripts.

Nigerian example: Check the schedule time zone.

Illustration:

    Tips:
    1. Test your script manually first
    2. Use full paths (e.g., C:\Users\name\script.py)
    3. Log output to a file
    4. Use absolute paths for files
    5. Check the time zone
            

Mini summary: Follow tips to avoid scheduling problems.


Lesson 9 ยท Using Python's Schedule Library

Definition: There is a Python library called schedule that can run tasks in a loop.

Why important: It is an alternative to Task Scheduler and cron.

Simple explanation: Like a timer inside your Python program.

Real-life example: schedule.every().day.at("08:00").do(job)

School example: Running a task every hour.

Home example: Running a task every minute.

Nigerian example: Running a task at a specific time.

Illustration:

    import schedule
    import time

    def job():
        print("Task is running!")

    schedule.every().day.at("08:00").do(job)

    while True:
        schedule.run_pending()
        time.sleep(1)
            

Mini summary: Use the schedule library for simple scheduling.


Lesson 10 ยท Putting It All Together

Definition: You can combine scheduling with all your automation scripts to run them automatically.

Why important: This is how you build fully automated systems.

Simple explanation: Like a machine that runs itself.

Real-life example: A script that sends a daily report at 8am.

School example: A script that checks for updates every hour.

Home example: A script that backs up files every night.

Nigerian example: A script that monitors prices every hour.

Illustration:

    # scheduled_report.py
    import schedule
    import time

    def send_report():
        # Send an email report
        print("Report sent!")

    schedule.every().day.at("08:00").do(send_report)

    while True:
        schedule.run_pending()
        time.sleep(60)
            

Mini summary: Combine scheduling with automation.


Lesson 11 ยท You Are Ready!

Definition: You have learned how to schedule scripts to run automatically.

Why important: You can now fully automate tasks.

Simple explanation: Your computer can work for you even when you're not there.

Real-life example: You can schedule daily, weekly, and monthly tasks.

School example: You can schedule tasks for your projects.

Home example: You can schedule tasks for your family.

Nigerian example: You can schedule tasks for your business.

Illustration:

    Python + Scheduling = Full Automation! ๐ŸŽ‰
            

Mini summary: You are ready to fully automate tasks!


๐Ÿ“Œ Key Vocabulary

  • Schedule: To set a task to run at a specific time.
  • Task Scheduler: A Windows tool for scheduling tasks.
  • Cron: A tool for scheduling on macOS and Linux.
  • Trigger: The event that starts a task (e.g., time).
  • Action: The task to run (e.g., a Python script).
  • Crontab: The file that stores cron schedules.
  • Interval: How often a task runs.
  • Log: A record of what a script did.
  • Automation: Making tasks run automatically.
  • Schedule library: A Python library for scheduling.

๐Ÿง  Important Concepts

  • Scheduling saves time: You don't have to run scripts manually.
  • Task Scheduler for Windows: Built-in and easy to use.
  • Cron for macOS/Linux: Powerful and flexible.
  • Schedule library: A Python-only solution.
  • Test before scheduling: Make sure your script works first.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Schedule a Script on Windows

  1. Create your script: Save it as script.py.
  2. Open Task Scheduler: Search for "Task Scheduler" in the Start menu.
  3. Create Basic Task: Click "Create Basic Task".
  4. Name the task: Give it a name, e.g., "Daily Report".
  5. Set trigger: Choose when to run (e.g., Daily at 8:00 AM).
  6. Set action: Choose "Start a program". Browse to python.exe (e.g., C:\Python39\python.exe). Add the script path as an argument.
  7. Finish: Click Finish.

Example:

    Task Scheduler Steps:
    1. Create script: daily_report.py
    2. Open Task Scheduler
    3. Create Basic Task
    4. Name: "Daily Report"
    5. Trigger: Daily at 8:00 AM
    6. Action: Start a program โ†’ python.exe "C:\scripts\daily_report.py"
    7. Finish
            

๐ŸŒ Real-life Examples

  • Daily: 0 8 * * * python daily_report.py
  • Hourly: 0 * * * * python hourly_update.py
  • Weekly: 0 0 * * 0 python weekly_backup.py
  • Monthly: 0 0 1 * * python monthly_summary.py
  • Yearly: 0 0 1 1 * python yearly_report.py

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Daily report: 0 8 * * * python sales_report.py
  • Exchange rate: 0 9 * * * python exchange_rate.py
  • Weather: 0 7 * * * python weather.py
  • Backup: 0 2 * * * python backup.py
  • Email: 0 6 * * * python send_email.py

๐ŸŽˆ Fun Examples children can relate to

  • 0 12 * * * python lunch_reminder.py
  • 0 15 * * * python play_time.py
  • 0 20 * * * python story_time.py
  • 0 8 * * 1 python monday_greeting.py
  • 0 9 * * 6 python weekend_fun.py

๐Ÿ  Everyday Examples

  • Morning: 0 7 * * * python morning_reminder.py
  • Afternoon: 0 13 * * * python afternoon_task.py
  • Evening: 0 19 * * * python evening_report.py
  • Night: 0 22 * * * python night_backup.py
  • Weekend: 0 10 * * 6 python weekend_cleanup.py

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to schedule a simple script.
  • Use local examples to make it relatable.
  • Discuss the importance of testing scripts first.
  • Have students create a schedule for a task they do regularly.
  • Celebrate every successful schedule.

๐Ÿ‘ช Parent Tips

  • Help your child schedule a script on their computer.
  • Write programs together that run on a schedule.
  • Encourage them to think of tasks they can automate.
  • Make learning Python a fun activity.
  • Celebrate their progress.

๐Ÿง Interesting Facts

  • Cron has been used since the 1970s.
  • Task Scheduler was introduced in Windows 95.
  • Many businesses use scheduled scripts for daily operations.
  • Scheduling saves millions of hours every year.
  • Python's schedule library is easy to use.

๐Ÿ’ก Did You Know?

  • Did you know that you can schedule scripts to run on any day?
  • Did you know that you can schedule scripts to run on the first of every month?
  • Did you know that you can schedule scripts to run at specific times?
  • Did you know that you can run multiple scripts at the same time?
  • Did you know that you can log the output of scheduled scripts?

๐Ÿงท Remember This

  • Scheduling saves time.
  • Use Task Scheduler on Windows.
  • Use cron on macOS and Linux.
  • Test your script before scheduling.
  • Use full paths in your scripts.

โš ๏ธ Common Mistakes

  • Not testing: Scheduling a script without testing it first.
  • Using wrong paths: Not using full paths to files.
  • Wrong time: Using the wrong time or time zone.
  • Not logging: Not tracking what the script did.
  • Forgetting to save: Forgetting to save the schedule.

โœ… Best Practices

  • Test your script manually first.
  • Use full paths for files and programs.
  • Log output to a file.
  • Check the time zone.
  • Start with a simple schedule and then make it more complex.

๐ŸŽจ Illustrations, Diagrams & Tables

Cron Syntax

FieldValuesExample
Minute0-590
Hour0-238
Day1-31*
Month1-12*
Day of Week0-6 (0=Sunday)*

Common Schedules

ScheduleCron Expression
Every day at 8am0 8 * * *
Every hour0 * * * *
Every minute* * * * *
Every Sunday at 9am0 9 * * 0
First of every month0 0 1 * *

Schedule Flow

    +----------------------+
    | Create Script        |
    +----------------------+
              |
              V
    +----------------------+
    | Test Script Manually |
    +----------------------+
              |
              V
    +----------------------+
    | Set up Schedule      |
    +----------------------+
              |
              V
    +----------------------+
    | Monitor and Adjust   |
    +----------------------+
            

๐Ÿ“ End-of-Module Summary

In this module, we learned how to schedule Python scripts to run automatically. We discovered that scheduling saves time and ensures tasks are done regularly. We learned about Task Scheduler on Windows and cron on macOS and Linux. We also learned about the Python schedule library. With scheduling, you can fully automate your tasks. Great work!

โ“ Frequently Asked Questions (10)

  1. Why schedule scripts? To run them automatically.
  2. What is Task Scheduler? A Windows tool for scheduling.
  3. What is cron? A tool for scheduling on macOS and Linux.
  4. What is a cron expression? A way to specify the schedule.
  5. How do you test a script? Run it manually first.
  6. What is the schedule library? A Python library for scheduling.
  7. What are full paths? Complete file paths (e.g., C:\script.py).
  8. Why log output? To see what the script did.
  9. Can you run multiple scripts? Yes.
  10. Is scheduling hard? No, it's easy to set up.

๐Ÿ“‹ Review Questions (15)

  1. Why is scheduling useful?
  2. What is Task Scheduler?
  3. What is cron?
  4. What is a cron expression?
  5. How do you test a script before scheduling it?
  6. What is the schedule library?
  7. What are full paths?
  8. Why should you log output?
  9. How do you schedule a script on Windows?
  10. How do you schedule a script on macOS/Linux?
  11. What is a trigger in Task Scheduler?
  12. What is an action in Task Scheduler?
  13. Can you schedule scripts for specific days of the week?
  14. What is the difference between cron and Task Scheduler?
  15. What is one best practice for scheduling?

โœ๏ธ Fill-in-the-Blank Exercises

  1. Scheduling means setting a script to run ______________. (automatically)
  2. Task Scheduler is a tool on ______________. (Windows)
  3. Cron is a tool on ______________ and Linux. (macOS)
  4. A cron expression specifies the ______________. (schedule)
  5. Test your script ______________ before scheduling it. (manually)

โœ… True or False Exercises

  1. Scheduling saves time. (True)
  2. Task Scheduler is only for Windows. (True)
  3. Cron is only for Windows. (False)
  4. You should test a script before scheduling it. (True)
  5. You can schedule scripts to run at specific times. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. Why schedule scripts?
    a) To run them automatically โœ…
    b) To make them faster
    c) To delete them
  2. What is Task Scheduler?
    a) A Windows scheduling tool โœ…
    b) A macOS scheduling tool
    c) A Linux scheduling tool
  3. What is cron?
    a) A Windows scheduling tool
    b) A macOS/Linux scheduling tool โœ…
    c) A Python library
  4. What is a cron expression?
    a) The schedule format โœ…
    b) A type of script
    c) A type of loop
  5. How do you test a script?
    a) Run it manually โœ…
    b) Schedule it first
    c) Delete it
  6. What is the schedule library?
    a) A Python scheduling library โœ…
    b) A Windows tool
    c) A macOS tool
  7. What are full paths?
    a) Complete file paths โœ…
    b) Short file names
    c) Relative paths
  8. Why log output?
    a) To see what the script did โœ…
    b) To delete it
    c) To ignore it
  9. How do you schedule on Windows?
    a) Task Scheduler โœ…
    b) Cron
    c) Schedule library
  10. How do you schedule on macOS?
    a) Task Scheduler
    b) Cron โœ…
    c) Schedule library
  11. What is a trigger?
    a) An event that starts a task โœ…
    b> A type of script
    c) A type of loop
  12. What is an action?
    a) The task to run โœ…
    b) The trigger
    c) The schedule
  13. Can you schedule scripts for specific days?
    a) Yes โœ…
    b) No
  14. What is the difference between cron and Task Scheduler?
    a) Different operating systems โœ…
    b) The same thing
    c) Both are for Windows
  15. What is a best practice?
    a) Test your script first โœ…
    b) Never test
    c) Schedule first

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. ScheduleA) The event that starts a task
2. Task SchedulerB) A Windows scheduling tool
3. CronC) A macOS/Linux scheduling tool
4. TriggerD) To set a task to run automatically
5. ActionE) The task to run

(Answers: 1-D, 2-B, 3-C, 4-A, 5-E)

๐Ÿ“ Short Answer Questions

  1. Why is scheduling useful?
  2. What is the difference between Task Scheduler and cron?
  3. Write a cron expression to run a script every day at 9am.

๐ŸŽญ Scenario-based Exercises

Scenario 1: You have a script that sends a daily report. You want it to run every day at 8am. How would you schedule it?

Scenario 2: You have a script that backs up files every week. You want it to run every Sunday at 10pm. How would you schedule it?

๐Ÿ‘ฅ Group Activity

In groups of 3, create a schedule for a script that does a simple task (like printing the time). Set it to run every minute and observe the output.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Create a script that saves the current time to a file. Schedule it to run every hour. Check the file after a few hours.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • How can scheduling help you in your daily life?
  • What are some tasks you would like to schedule?
  • What are the benefits of automation?

๐Ÿ› ๏ธ Mini Project

Create a script that sends a daily "Good Morning" email to yourself. Schedule it to run every day at 7am.

๐Ÿ“ Practical Assignment

Write a script that checks the weather every morning and saves the data to a file. Schedule it to run daily.

๐Ÿ† Challenge Exercise

Write a script that scrapes a website, processes the data, and sends a report via email. Schedule it to run every day at 8am.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-automatically, 2-Windows, 3-macOS, 4-schedule, 5-manually

True/False: 1-T, 2-T, 3-F, 4-T, 5-T

Matching: 1-D, 2-B, 3-C, 4-A, 5-E

๐ŸŽ Key Takeaways

  • Scheduling runs scripts automatically.
  • Use Task Scheduler on Windows.
  • Use cron on macOS and Linux.
  • Test your scripts before scheduling them.
  • Scheduling saves time and automates tasks.

๐Ÿš€ Preparation for the next module

In Module Twelve, we will put everything together and build your final automation project. We will combine all the skills you have learned โ€” variables, lists, loops, conditions, functions, files, and scheduling โ€” to create a complete automation system. Before the next session, think of a project you would like to build.

See you in Module Twelve! ๐ŸŽ‰


End of Module Eleven ยท Scheduling and Running Scripts

14

Module Twelve

Module Twelve ยท Python for Automation

๐Ÿš€ Module Twelve ยท Final Project: Build Your Automation


๐Ÿ“– Module Introduction

Hello, future automation expert! You have made it to the final module! You have learned so much: variables, lists, loops, conditions, functions, files, CSV, Excel, email, web scraping, Selenium, and scheduling. Now it's time to put it all together and build your own automation project.

In this module, we will guide you through planning, building, and presenting a complete automation project. You will choose a problem to solve, plan your solution, write the code, and share it with others. By the end of this module, you will have a project to be proud of!

๐ŸŽฏ Learning Objectives

  • Plan a complete automation project.
  • Combine all the skills you have learned.
  • Build a working automation project.
  • Present and share your project.
  • Celebrate your achievements.

๐Ÿ“š Warm-up Story ยท Tunde's Automation Journey

Tunde started this course as a beginner. He didn't know anything about Python. But he learned step by step. He learned about variables, lists, loops, and functions. He learned how to work with files, send emails, and even scrape websites.

For his final project, Tunde built a system that scraped product prices from websites, saved them to a CSV file, and emailed him a summary every morning. He scheduled it to run at 7am. Tunde was so proud of his project. He saved hours of work and impressed his boss. Tunde is now an automation expert!

๐Ÿงฉ Main Lessons

Lesson 1 ยท Choosing Your Project

Definition: The first step is to choose a project that solves a real problem for you.

Why important: A good project is something you care about.

Simple explanation: Think about a task you do repeatedly and want to automate.

Real-life example: Automating a daily report.

School example: Automating grade checks.

Home example: Automating a shopping list.

Nigerian example: Automating exchange rate checks.

Illustration:

    Project Ideas:
    1. Daily weather report
    2. Price tracker
    3. Email reminder
    4. File organiser
    5. Web scraper
            

Mini summary: Choose a project that solves a real problem.


Lesson 2 ยท Planning Your Project

Definition: Planning means deciding what your project will do and how it will work.

Why important: A good plan makes building the project easier.

Simple explanation: Like making a recipe before you start cooking.

Real-life example: Write down the steps your project will take.

School example: Plan a project for a class assignment.

Home example: Plan a project for a family task.

Nigerian example: Plan a project for a business task.

Illustration:

    Project Plan:
    1. What problem does it solve?
    2. What will it do?
    3. What tools will it use?
    4. What are the steps?
    5. How will I test it?
            

Mini summary: Plan your project before you start coding.


Lesson 3 ยท Breaking Down the Problem

Definition: Break the project into smaller, manageable pieces.

Why important: It makes the project less overwhelming.

Simple explanation: Like eating a pizza one slice at a time.

Real-life example: Step 1: Get data. Step 2: Process data. Step 3: Save data.

School example: Break a large project into smaller tasks.

Home example: Break cleaning a room into smaller steps.

Nigerian example: Break a business project into smaller tasks.

Illustration:

    Project: Price Tracker
    1. Scrape prices from website
    2. Save prices to CSV
    3. Check if price is below target
    4. Send email alert
            

Mini summary: Break big projects into smaller pieces.


Lesson 4 ยท Choosing the Right Tools

Definition: Decide which tools and libraries you need for your project.

Why important: Using the right tools makes your project easier.

Simple explanation: Like choosing the right tool for a job.

Real-life example: Use requests for web scraping.

School example: Use csv for file handling.

Home example: Use schedule for scheduling.

Nigerian example: Use openpyxl for Excel files.

Illustration:

    Tools:
    - Web scraping: requests, BeautifulSoup
    - Excel: openpyxl
    - Email: smtplib
    - Scheduling: schedule, Task Scheduler, cron
    - Files: csv, os
            

Mini summary: Choose the right tools for your project.


Lesson 5 ยท Writing the Code

Definition: This is where you write the Python code for your project.

Why important: This is the main part of your project.

Simple explanation: Like writing the recipe for your dish.

Real-life example: Write a script that scrapes data and saves it.

School example: Write a script for your project.

Home example: Write a script for your family task.

Nigerian example: Write a script for your business.

Illustration:

    # Example: Price Tracker
    import requests
    from bs4 import BeautifulSoup

    url = "https://example.com/product"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    price = soup.find(class_="price").text
    print(price)
            

Mini summary: Write the code for your project.


Lesson 6 ยท Testing and Debugging

Definition: Testing means running your code and checking if it works. Debugging means fixing problems.

Why important: Testing ensures your project works correctly.

Simple explanation: Like tasting your food to see if it needs more salt.

Real-life example: Run your script and check the output.

School example: Test your project and fix any errors.

Home example: Test your script and fix any problems.

Nigerian example: Test your script before using it.

Illustration:

    Testing Steps:
    1. Run the script
    2. Check the output
    3. If there is an error, fix it
    4. Run again
    5. Repeat until it works
            

Mini summary: Test and debug your code to make it work.


Lesson 7 ยท Adding Error Handling

Definition: Error handling means making your code handle errors gracefully so it doesn't crash.

Why important: This makes your project more reliable.

Simple explanation: Like having a backup plan.

Real-life example: Use try-except to handle errors.

School example: Handle errors in your project.

Home example: Handle errors in your script.

Nigerian example: Make your script robust.

Illustration:

    try:
        # Code that might cause an error
        price = soup.find(class_="price").text
    except:
        # Code to run if there is an error
        price = "Price not found"
            

Mini summary: Add error handling to make your code reliable.


Lesson 8 ยท Making Your Code User-Friendly

Definition: User-friendly code is easy to use and understand.

Why important: This makes your project more useful.

Simple explanation: Like writing clear instructions.

Real-life example: Use clear variable names.

School example: Make your project easy to use.

Home example: Make your script easy to run.

Nigerian example: Make your code easy to understand.

Illustration:

    # Clear variable names
    product_url = "https://example.com/product"
    price_element = soup.find(class_="price")
            

Mini summary: Make your code user-friendly.


Lesson 9 ยท Documenting Your Project

Definition: Documentation is writing down what your project does and how to use it.

Why important: Documentation helps others (and your future self) understand your code.

Simple explanation: Like writing a manual for your project.

Real-life example: Write a README file.

School example: Write a report about your project.

Home example: Write instructions for your family.

Nigerian example: Write documentation for your business.

Illustration:

    README.md
    # Price Tracker
    This project tracks the price of a product and sends an alert when it drops.

    ## How to use
    1. Install requirements
    2. Run the script
    3. Check the output
            

Mini summary: Document your project so others can use it.


Lesson 10 ยท Presenting Your Project

Definition: Presenting means showing your project to others and explaining how it works.

Why important: This helps you share your work and get feedback.

Simple explanation: Like showing a school project to the class.

Real-life example: Present your project to your team.

School example: Present your project to your class.

Home example: Show your project to your family.

Nigerian example: Present your project to your colleagues.

Illustration:

    Presentation Tips:
    1. Explain the problem you solved
    2. Show how your project works
    3. Demonstrate the code
    4. Show the results
    5. Share what you learned
            

Mini summary: Present your project and share your work.


Lesson 11 ยท Celebrating Your Achievement

Definition: Celebrate your hard work and success!

Why important: This motivates you to keep learning.

Simple explanation: Like having a party after finishing a big project.

Real-life example: Share your project on LinkedIn.

School example: Be proud of your project.

Home example: Celebrate with your family.

Nigerian example: Share your project with your community.

Illustration:

    ๐ŸŽ‰ You did it! ๐ŸŽ‰
    You have completed the course!
    You are now an automation expert!
            

Mini summary: Celebrate your achievements!


๐Ÿ“Œ Key Vocabulary

  • Project: A task or problem you solve with code.
  • Plan: A way to organise your work.
  • Break down: To divide into smaller parts.
  • Tool: A library or software you use.
  • Test: To check if something works.
  • Debug: To fix errors.
  • Error handling: Making code handle errors gracefully.
  • User-friendly: Easy to use and understand.
  • Documentation: Writing about your project.
  • Present: To show your project to others.

๐Ÿง  Important Concepts

  • Plan before you code: A good plan makes building easier.
  • Break problems down: Small pieces are easier to handle.
  • Test as you go: Check your work step by step.
  • Document your work: Write down what you did.
  • Celebrate your success: You have accomplished something great.

๐Ÿ‘ฃ Step-by-Step Explanations

How to Build a Complete Automation Project

  1. Choose a project: Pick something you want to automate.
  2. Plan the project: Write down what it will do.
  3. Break it down: Divide into small steps.
  4. Choose tools: Decide which libraries to use.
  5. Write the code: Build each part step by step.
  6. Test and debug: Make sure it works.
  7. Add error handling: Make it reliable.
  8. Document: Write a README.
  9. Present: Show your project to others.
  10. Celebrate: Enjoy your success!

Example:

    Project: Price Tracker
    1. Plan: Scrape price, save to CSV, email alert
    2. Break down: scrape, save, email
    3. Tools: requests, csv, smtplib
    4. Code: write each part
    5. Test: run and check
    6. Error handling: try-except
    7. Document: write README
    8. Present: share with others
    9. Celebrate! ๐ŸŽ‰
            

๐ŸŒ Real-life Examples

  • Daily Report: Automate a daily sales report.
  • Price Tracker: Track prices and send alerts.
  • Email Reminder: Send automated reminders.
  • File Organiser: Organise files automatically.
  • Web Scraper: Collect data from websites.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Exchange Rate: Track Naira to Dollar rates.
  • Market Data: Scrape market prices.
  • School Portal: Automate checking grades.
  • Business Report: Automate daily business reports.
  • Customer Emails: Send automated emails to customers.

๐ŸŽˆ Fun Examples children can relate to

  • Game Tracker: Track scores in a game.
  • Movie Reminder: Remind when a movie releases.
  • Recipe Saver: Save recipes automatically.
  • Pet Tracker: Track pet activities.
  • Homework Helper: Remind to do homework.

๐Ÿ  Everyday Examples

  • Grocery List: Automate a shopping list.
  • Budget Tracker: Track your budget automatically.
  • Calendar: Add events to a calendar automatically.
  • Reminder: Send reminders for tasks.
  • Backup: Back up files automatically.

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Encourage students to choose a project they care about.
  • Provide guidance and support.
  • Celebrate every completed project.
  • Encourage sharing and presenting.
  • Remind students of how far they have come.

๐Ÿ‘ช Parent Tips

  • Celebrate your child's project with them.
  • Ask them to explain how it works.
  • Encourage them to keep learning.
  • Support their future projects.
  • Be proud of their accomplishment.

๐Ÿง Interesting Facts

  • Many people start with automation as their first coding project.
  • Automation saves millions of hours every day.
  • You can automate almost any task.
  • Python is one of the best languages for automation.
  • Automation is used in every industry.

๐Ÿ’ก Did You Know?

  • Did you know that you can automate your social media posts?
  • Did you know that you can automate your email responses?
  • Did you know that you can automate your data entry?
  • Did you know that you can automate your backups?
  • Did you know that you can automate almost anything?

๐Ÿงท Remember This

  • Plan your project before you start.
  • Break the problem into small pieces.
  • Test your code regularly.
  • Document your project.
  • Share your work with others.
  • Celebrate your success!

โš ๏ธ Common Mistakes

  • Not planning: Starting without a plan.
  • Not breaking down: Trying to do everything at once.
  • Not testing: Not checking if the code works.
  • Not documenting: Not writing down what you did.
  • Not sharing: Keeping your project to yourself.

โœ… Best Practices

  • Start with a simple project.
  • Plan your project carefully.
  • Break the problem into small steps.
  • Test each step before moving on.
  • Document your project.
  • Share your project with others.

๐ŸŽจ Illustrations, Diagrams & Tables

Project Planning Flowchart

    +----------------------+
    | Choose Project       |
    +----------------------+
              |
              V
    +----------------------+
    | Plan the Project     |
    +----------------------+
              |
              V
    +----------------------+
    | Break Down Problem   |
    +----------------------+
              |
              V
    +----------------------+
    | Choose Tools         |
    +----------------------+
              |
              V
    +----------------------+
    | Write Code           |
    +----------------------+
              |
              V
    +----------------------+
    | Test and Debug       |
    +----------------------+
              |
              V
    +----------------------+
    | Document and Share   |
    +----------------------+
            

Project Examples

Project IdeaToolsSkills Used
Price Trackerrequests, BeautifulSoup, csv, smtplibWeb scraping, files, email
Daily Reportcsv, smtplib, scheduleFiles, email, scheduling
File Organiseros, shutilFiles, automation
Email Remindersmtplib, scheduleEmail, scheduling
Web Scraperrequests, BeautifulSoupWeb scraping

Project Checklist

    โ˜ Project idea chosen
    โ˜ Project plan written
    โ˜ Problem broken down
    โ˜ Tools chosen
    โ˜ Code written
    โ˜ Code tested
    โ˜ Errors fixed
    โ˜ Code documented
    โ˜ Project presented
    โ˜ Success celebrated!
            

๐Ÿ“ End-of-Module Summary

Congratulations! You have completed the "Python for Automation" course. In this final module, you learned how to plan, build, and present your own automation project. You combined all the skills you learned โ€” variables, lists, loops, conditions, functions, files, CSV, Excel, email, web scraping, Selenium, and scheduling โ€” to create a complete automation solution.

You are now an automation expert! You can use these skills to solve problems, save time, and make your life easier. Keep learning, keep building, and keep automating!

โ“ Frequently Asked Questions (10)

  1. What if I don't have a project idea? Think about a task you do repeatedly.
  2. How do I start? Plan your project and break it down.
  3. What if my code doesn't work? Test and debug it.
  4. How do I make it reliable? Add error handling.
  5. Should I document my project? Yes, it helps others understand it.
  6. How do I share my project? Present it to others.
  7. What if I need help? Ask your teacher or community.
  8. Can I continue learning? Yes, there is always more to learn.
  9. What is the most important skill? The ability to solve problems.
  10. What should I do next? Build more projects!

๐Ÿ“‹ Review Questions (15)

  1. What is the first step in building a project?
  2. Why is planning important?
  3. Why should you break a problem down?
  4. What are tools in a project?
  5. Why is testing important?
  6. What is debugging?
  7. What is error handling?
  8. Why should you document your project?
  9. Why should you present your project?
  10. Why should you celebrate your success?
  11. What is one example of a project?
  12. What skills did you use in your project?
  13. What was the most challenging part?
  14. What was the most rewarding part?
  15. What will you do next?

โœ๏ธ Fill-in-the-Blank Exercises

  1. The first step is to ______________ a project. (choose)
  2. Plan your project before you start ______________. (coding)
  3. Break the problem into ______________ pieces. (smaller)
  4. Test your code to check if it ______________. (works)
  5. ______________ your project so others can understand it. (Document)

โœ… True or False Exercises

  1. Planning is not important. (False)
  2. You should break a problem down. (True)
  3. Testing is optional. (False)
  4. Documentation is useful. (True)
  5. You should celebrate your success. (True)

๐Ÿ”˜ Multiple Choice Questions (15)

  1. What is the first step in building a project?
    a) Choose a project โœ…
    b) Write code
    c) Test
  2. Why is planning important?
    a) It makes building easier โœ…
    b) It wastes time
    c) It is not important
  3. Why break a problem down?
    a) To make it easier โœ…
    b) To make it harder
    c) To waste time
  4. What are tools?
    a) Libraries you use โœ…
    b) The code you write
    c) The project you build
  5. Why test your code?
    a) To check if it works โœ…
    b) To waste time
    c) To make it harder
  6. What is debugging?
    a) Fixing errors โœ…
    b> Writing code
    c) Planning
  7. Why add error handling?
    a) To make it reliable โœ…
    b> To make it fail
    c) To waste time
  8. Why document your project?
    a) To help others understand โœ…
    b> To confuse people
    c) To waste time
  9. Why present your project?
    a) To share your work โœ…
    b> To hide it
    c) To waste time
  10. Why celebrate success?
    a) To motivate yourself โœ…
    b> To ignore it
    c) To waste time
  11. What is one example of a project?
    a) Price tracker โœ…
    b) A type of food
    c) A type of game
  12. What skills did you use?
    a) Variables, loops, functions โœ…
    b) Only variables
    c) Only loops
  13. What was the most challenging part?
    a) Depends on the project โœ…
    b) Nothing
    c) Everything
  14. What was the most rewarding part?
    a) Seeing it work โœ…
    b) Nothing
    c) Everything
  15. What will you do next?
    a) Build more projects โœ…
    b) Stop learning
    c) Forget everything

๐Ÿ”— Matching Exercises

Match the word with its meaning:

WordMeaning
1. ProjectA) To divide into smaller parts
2. PlanB) A task you solve with code
3. Break downC) To check if something works
4. TestD) To organise your work
5. DocumentE) To write about your project

(Answers: 1-B, 2-D, 3-A, 4-C, 5-E)

๐Ÿ“ Short Answer Questions

  1. What is the first step in building a project?
  2. Why is planning important?
  3. What is the most important thing you learned in this course?

๐ŸŽญ Scenario-based Exercises

Scenario 1: You want to build a project that tracks your daily steps and sends you a reminder to walk. How would you plan it?

Scenario 2: You have built a project that scrapes data from a website, but it sometimes fails. How would you make it more reliable?

๐Ÿ‘ฅ Group Activity

In groups of 3, share your projects with each other. Give feedback and suggestions. Celebrate each other's work.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Plan and build your own automation project. Use all the skills you have learned. Document your project and present it.

๐Ÿ—ฃ๏ธ Classroom Discussion Questions

  • What was the most challenging part of building your project?
  • What was the most rewarding part?
  • What will you build next?

๐Ÿ› ๏ธ Mini Project

Build a complete automation project of your choice. It should include at least 3 different skills (e.g., web scraping, email, scheduling).

๐Ÿ“ Practical Assignment

Write a full automation project that solves a real problem for you. Document it and share it with the class.

๐Ÿ† Challenge Exercise

Build a project that combines web scraping, data processing, and email automation. Schedule it to run daily.

๐Ÿ”‘ Quiz Answers

Fill-in-the-blank: 1-choose, 2-coding, 3-smaller, 4-works, 5-Document

True/False: 1-F, 2-T, 3-F, 4-T, 5-T

Matching: 1-B, 2-D, 3-A, 4-C, 5-E

๐ŸŽ Key Takeaways

  • Choose a project you care about.
  • Plan your project carefully.
  • Break the problem into small pieces.
  • Test your code regularly.
  • Document your project.
  • Share your work with others.
  • Celebrate your success!

๐Ÿš€ What's Next?

Congratulations! You have completed all 12 modules of the "Python for Automation" course. You now have the skills to automate tasks, solve problems, and build useful projects.

Here are some ideas for your next steps:

  • Build more automation projects.
  • Share your projects with the world.
  • Teach others what you have learned.
  • Explore advanced topics like web development, data science, or machine learning.

Thank you for being part of this course. You are now an automation expert! Keep learning, keep building, and keep automating.

๐ŸŽ‰ We are so proud of you! ๐ŸŽ‰


End of Module Twelve ยท Final Project: Build Your Automation

End of Course ยท Python for Automation

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, pass the exam, and unlock Practice Tools plus a verified certificate with your name on it โ€” โ‚ฆ4,000/month.

๐ŸŽ“ Sign Up & Unlock for โ‚ฆ4,000/month
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - try them free for 7 days, no card required.
โ†’