๐ 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.
| Aspect | Details |
|---|---|
| Target audience | Complete beginners, office workers, IT professionals, and anyone who wants to automate daily tasks |
| Prerequisites | Basic computer skills (file management, using a browser) โ no coding experience needed |
| Delivery mode | Self-paced with hands-on projects and exercises |
| Total duration | ~15โ20 hours (over 4โ6 weeks) |
| Certification | Certificate of Completion with a project portfolio |
| Main tools | Python 3, VS Code (or any text editor), command line / terminal |
By the end of this course, you will be able to:
| Module | Title & focus | Key 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. |
| Component | Description |
|---|---|
| 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. |
| Week | Modules to cover | Estimated time |
|---|---|---|
| Week 1 | Modules 1, 2, 3 | 3โ4 hours |
| Week 2 | Modules 4, 5, 6 | 4โ5 hours |
| Week 3 | Modules 7, 8, 9 | 4โ5 hours |
| Week 4 | Modules 10, 11, 12 | 4โ6 hours |
| Question | Answer |
|---|---|
| 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. |
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!
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!
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
print() to see results.print("Hello, world!")hello.py.python hello.py and press Enter.Hello, world!.
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!
print("Good morning, class!")print("Welcome to Python!")name = "Aisha" then print(name)age = 25 then print(age)print("Hello,", name)print("แบธ kรกร bแปฬ!")city = "Lagos" then print(city)name = "Chidi" then print(name)print("Welcome to Nigeria!")print("Hello,", name, "from", city)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!")print("Good morning, family!")print("Don't forget to take out the trash.")print("Have a great day at school!")print("Dinner is ready!")print("Let's play a game!")print() shows text on the screen.print(Hello) โ should be print("Hello").print "Hello" โ should be print("Hello").print("Hello') โ be consistent.prin("Hello") โ should be print("Hello")..py extension.
+------------------+
| 1. Go to python.org |
+------------------+
|
V
+------------------+
| 2. Click Download |
+------------------+
|
V
+------------------+
| 3. Run Installer |
+------------------+
|
V
+------------------+
| 4. Click Install |
+------------------+
|
V
+------------------+
| 5. Done! โ
|
+------------------+
| Code | Output |
|---|---|
print("Hello") | Hello |
print("Python") | Python |
print("1") | 1 |
print(2 + 3) | 5 |
| Data Type | Example | With Quotes? |
|---|---|---|
| String (text) | "Hello" | Yes |
| Integer (number) | 5 | No |
| String (text) | "5" | Yes |
| Integer (number) | 10 | No |
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!
print()? A command to show text.print() used for?print("Hello") do?print() shows ______________ on the screen. (text)print() is used to hide text. (False)print() do?python filename.py โ
print("Hello") show?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Python | A) Shows text on the screen |
| 2. print | B) A programming language |
| 3. Variable | C) A note in code |
| 4. String | D) A container for information |
| 5. Comment | E) Text in quotes |
(Answers: 1-B, 2-A, 3-D, 4-E, 5-C)
print("Hello") do?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?
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.
Write a Python program that prints your name, your favourite food, and your favourite colour. Save it and run it.
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.
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.
Write a program that prints a pattern using print() statements. For example:
*
**
***
****
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
print() shows text on the screen.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!
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.
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
name = input("Enter your name: ")age = int(input("Enter your age: "))print("Hello, " + name + "! You are " + str(age) + " years old.")greeting.py and run.
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!
name = input("What is your name? ") then print("Hello, " + name).num1 = 10, num2 = 5, print(num1 + num2).first = "John", last = "Doe", print(first + " " + last).age = 25, print("I am " + str(age)).math = 80, english = 85, average = (math + english) / 2.name = input("What is your name? ") then print("Hello, " + name + "! Welcome to Nigeria.").city = "Lagos", print("I live in " + city).naira = 500, print("You have " + str(naira) + " Naira").states = 36, print("Nigeria has " + str(states) + " states.").food = "Jollof rice", print("My favourite food is " + food).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!").name = input("What is your name? ") then print("Good morning, " + name).chore = input("What chore do you need to do? ") then print("Don't forget to " + chore).meal = input("What is for dinner? ") then print("I can't wait to eat " + meal).subject = input("What subject is your homework? ") then print("Good luck with " + subject).sibling = input("What is your sibling's name? ") then print("Hello, " + sibling).input() always gives you a string?+ to add numbers and join strings.str() to convert numbers to strings.int() to convert strings to integers.name = Aisha โ should be name = "Aisha".print("Age is " + age) โ use str(age).my-name โ use my_name.age = input("Enter age: ") gives a string โ use int() for math.print "Hello" โ should be print("Hello").student_name instead of a.str() to print numbers with text.| Data Type | Description | Example |
|---|---|---|
| String | Text in quotes | "Hello", 'Aisha' |
| Integer | Whole number | 25, 100 |
| Float | Number with decimal | 3.14, 10.5 |
| Operation | Symbol | Example |
|---|---|---|
| Addition | + | 5 + 3 = 8 |
| Subtraction | - | 10 - 4 = 6 |
| Multiplication | * | 3 * 4 = 12 |
| Division | / | 10 / 2 = 5 |
| Power | ** | 2 ** 3 = 8 |
โ
Allowed: student_name, score2, first_name
โ Not Allowed: 2nd_score, my-name, class (reserved word)
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!
name = "Aisha".total = 5 + 3.full = first + " " + last.name = input("Enter name: ").str(number).print(5 + 3)?print("Hello" + " " + "World")?________ to get user input. (input)input() gets information from the user. (True)name = "Aisha" โ
name = Aishaname = 'Aisha5 + 3 โ
5 - 35 * 3input() โ
print()str()str() โ
int()float()print(5 + 3)?print("Hello" + " " + "World")?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Variable | A) A whole number |
| 2. String | B) A container for information |
| 3. Integer | C) Text in quotes |
| 4. Float | D) Gets information from the user |
| 5. input() | E) A decimal number |
(Answers: 1-B, 2-C, 3-A, 4-E, 5-D)
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.
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.
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).
Create a program that acts as a simple calculator. Ask the user for two numbers and then print the sum, difference, product, and quotient.
Write a program that asks for your favourite food, your favourite colour, and your favourite animal. Then print a message that includes all three.
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.
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
input() to get information from the user.str() and int() to convert data types.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
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.
for loops to repeat actions.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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
shopping_list = ["rice", "beans", "oil", "salt"]for item in shopping_list:print(item)shopping.py and run.
Step 1: shopping_list = ["rice", "beans", "oil", "salt"]
Step 2: for item in shopping_list:
Step 3: print(item)
Step 4: Run the program!
shopping_list = ["rice", "beans", "oil"] then for item in shopping_list: print(item).students = ["Aisha", "Chidi", "Bola"] then for name in students: print("Hello, " + name).scores = [85, 90, 78] then total = sum(scores).for i in range(5): print("Clean the room").for i in range(5, 0, -1): print(i) prints 5,4,3,2,1.states = ["Lagos", "Abuja", "Kano", "Kaduna"] then for state in states: print(state + " is a state in Nigeria").foods = ["Jollof rice", "Egusi soup", "Pounded yam"] then for food in foods: print("I love " + food).cities = ["Lagos", "Ibadan", "Enugu"] then for city in cities: print(city + " is a city in Nigeria").languages = ["Yoruba", "Hausa", "Igbo"] then for lang in languages: print(lang + " is spoken in Nigeria").rivers = ["Niger", "Benue", "Cross River"] then for river in rivers: print(river + " is a river in Nigeria").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).chores = ["sweep", "wash", "cook"] then for chore in chores: print("I need to " + chore).family = ["Mum", "Dad", "Sister"] then for member in family: print("Hello, " + member).teachers = ["Mr. A", "Ms. B"] then for teacher in teachers: print("Good morning, " + teacher).meals = ["breakfast", "lunch", "dinner"] then for meal in meals: print("Time for " + meal).days = ["Monday", "Tuesday", "Wednesday"] then for day in days: print("Today is " + day).range() can start at any number and step by any amount?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.for item in list: needs a colon.while loop that never stops.remove() on an item not in the list.student_names instead of list1.append() to add items.len() to get list length.| Operation | Example | Result |
|---|---|---|
| Create | fruits = ["apple", "banana"] | ["apple", "banana"] |
| Access | fruits[0] | "apple" |
| Change | fruits[1] = "mango" | ["apple", "mango"] |
| Add | fruits.append("orange") | ["apple", "mango", "orange"] |
| Remove | fruits.remove("mango") | ["apple", "orange"] |
| Length | len(fruits) | 2 |
+----------------------+
| for item in list: |
+----------------------+
|
V
+----------------------+
| Execute block of code |
+----------------------+
|
V
+----------------------+
| Any items left? ----> Yes ---> Loop again
+----------------------+
|
No
V
+----------------------+
| Exit loop |
+----------------------+
| For Loop | While Loop |
|---|---|
| Use when you know the number of iterations | Use when you don't know |
| Iterates over a sequence | Iterates while a condition is true |
for i in range(5): | while i < 5: |
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!
list[index].list.append(item).list.remove(item).range(5) do?break do?continue do?for i in range(3): print(i)?for i in range(2, 5): print(i)?________ to add an item to the end of a list. (append)for loop repeats for each item in a ______________. (list)range(5) generates numbers from 0 to ______________. (4)append() adds an item to the beginning. (False)for loops repeat for each item. (True)while loops repeat while a condition is true. (True)append() โ
add()push()remove() โ
delete()pop()len() โ
size()count()range(5) generate?list[1] โ
list[2]list[0]for i in range(3): print(i)?for i in range(2, 5): print(i)?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. List | A) Repeats while true |
| 2. Index | B) A container for multiple items |
| 3. append | C) Position of an item |
| 4. for loop | D) Adds an item to the end |
| 5. while loop | E) Repeats for each item |
(Answers: 1-B, 2-C, 3-D, 4-E, 5-A)
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.
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".
Create a list of your favourite foods. Write a program that prints each food and says "I love [food]!"
Create a program that holds a list of your favourite movies. Use a loop to print each movie with a number (1, 2, 3, ...).
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]!".
Write a program that creates a list of numbers from 1 to 10. Then use a loop to print only the even numbers.
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
append() to add items.remove() to delete items.for loops repeat for each item.while loops repeat while true.break stops a loop.continue skips an iteration.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
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.
if, elif, and else statements.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.
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.
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.
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.
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.
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.
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 !=.
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.
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.
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.
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.
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.
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.
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!
num = int(input("Enter a number: "))if num % 2 == 0:print("Even")else: print("Odd")even_odd.py and run.
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!
if score >= 50: print("Pass") else: print("Fail")if age >= 18: print("Can vote") else: print("Too young")if temp > 30: print("Hot") else: print("Cool")if username == "admin" and password == "1234": print("Welcome")if item in shopping_list: print("Buy it")if city == "Lagos": print("Lagos is in South-West") elif city == "Kano": print("Kano is in North-West")if food == "Jollof rice": print("I love Jollof") elif food == "Egusi": print("I love Egusi")if state == "Lagos": print("State in Nigeria") else: print("Not a Nigerian state")if language == "Yoruba": print("South-West") elif language == "Hausa": print("North")if amount > 1000: print("Expensive") else: print("Affordable")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!")if time < 12: print("Good morning") else: print("Good afternoon")if chore == "done": print("Great work") else: print("Do it now")if weather == "rainy": print("Take umbrella") else: print("Enjoy the sun")if meal == "breakfast": print("It's breakfast time")if homework_done == True: print("Good job") else: print("Finish your homework")and and or can combine many conditions?elif statements?in to check if an item is in a list?if runs code when true.elif checks more conditions.else runs when all are false.==, !=, >, <, >=, <= to compare.and, or, not to combine.if age = 18 is wrong. Use ==.if age > 18 needs a colon: if age > 18:.if must be indented.elif: Using many if statements when elif is better.and and or: Make sure you use the right one.elif for multiple conditions.and and or carefully.in to check membership in lists.
+----------------------+
| Condition |
+----------------------+
|
V
+----------------------+
| Is it True? |
+----------------------+
|
Yes ---+--- No
| |
V V
+--------+ +--------+
| Do A | | Do B |
+--------+ +--------+
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 is True |
!= | Not equal to | 5 != 3 is True |
> | Greater than | 5 > 3 is True |
< | Less than | 3 < 5 is True |
>= | Greater than or equal to | 5 >= 5 is True |
<= | Less than or equal to | 3 <= 5 is True |
if condition1:
# code block 1
elif condition2:
# code block 2
elif condition3:
# code block 3
else:
# code block 4
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!
if do? Runs code when true.else do? Runs code when false.elif do? Checks more conditions.==? Checks if two values are equal.!=? Checks if two values are not equal.and do? Combines conditions (both must be true).or do? Combines conditions (one must be true).in do? Checks if an item is in a list or string.if do?else do?elif do?== and =?!= mean?> do?< do?and do?or do?not do?in do?if statement?if-else statement?if-elif-else statement?if statement runs code when the condition is ______________. (true)else statement runs code when the condition is ______________. (false)== checks if two values are ______________. (equal)and combines conditions and requires ______________ to be true. (both)if runs code when false. (False)else runs code when true. (False)== checks if values are equal. (True)and requires both conditions to be true. (True)if do?else do?elif do?== do?!= do?and do?or do?in do?if 5 > 3: print("True")?if 5 < 3: print("True") else: print("False")?if 5 == 5: print("Equal")?if 5 != 3: print("Not Equal")?in with strings?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. if | A) Runs code when false |
| 2. else | B) Runs code when true |
| 3. elif | C) Checks equality |
| 4. == | D) Checks more conditions |
| 5. and | E) Combines conditions (both true) |
(Answers: 1-B, 2-A, 3-D, 4-C, 5-E)
if and else?== and =?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.
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).
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.
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."
Write a program that takes a list of numbers and prints only the numbers that are greater than 10.
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.
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
if, elif, and else control the flow of your program.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
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.
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.
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.
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.
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 ().
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
def.def greet(name):print("Hello, " + name)greet("Aisha")
Step 1: def greet(name):
Step 2: print("Hello, " + name)
Step 3: greet("Aisha") # Output: Hello, Aisha
def greet(name): print("Hello, " + name)def add(a, b): return a + bdef average(numbers): return sum(numbers) / len(numbers)def calculate_tax(amount): return amount * 0.1def celsius_to_fahrenheit(c): return c * 9/5 + 32def greet_yoruba(name): print("แบธ kรกร bแปฬ, " + name)def naira_to_dollar(naira): return naira / 1600def region(state): if state == "Lagos": return "South-West" else: return "Other"def make_jollof(rice, chicken): print("Making Jollof rice with " + chicken)def is_lagos(city): return city == "Lagos"def say_hello(): print("Hello, world!")def square(number): return number * numberdef favourite_food(food): print("I love " + food)def is_even(number): return number % 2 == 0def birthday(name): print("Happy Birthday, " + name)def clean_room(room): print("Cleaning " + room)def make_tea(type="green"): print("Making " + type + " tea")def check_homework(done): if done: print("Great job") else: print("Do it now")def do_chore(chore): print("Doing " + chore)def remind(task): print("Reminder: " + task)print() and len().def to define a function.().def greet() needs a colon: def greet():return when needed.
+----------------------+
| def function_name(parameters): |
| # code block |
| return result |
+----------------------+
| Function | Input | Output |
|---|---|---|
add(a, b) | 5, 3 | 8 |
greet(name) | "Aisha" | "Hello, Aisha" |
square(n) | 4 | 16 |
| Without Functions | With Functions |
|---|---|
| Repeated code | One function used many times |
| Hard to read | Easy to read |
| Hard to change | Easy to change |
| Long programs | Short programs |
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!
def function_name():function_name()return do? Sends a value back.return do?________ keyword to define a function. (def)________ to send a value back. (return)func. (False)return sends a value back. (True)def function_name(): โ
function function_name():func function_name():function_name() โ
call function_name()run function_name()return do?def โ
funcfunctiondef add(a, b): return a + b with add(5, 3)?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Function | A) Sends a value back |
| 2. Parameter | B) A reusable block of code |
| 3. Return | C) A variable passed to a function |
| 4. Define | D) A description of a function |
| 5. Docstring | E) To create a function |
(Answers: 1-B, 2-C, 3-A, 4-E, 5-D)
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.
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.
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.
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.
Write a function that calculates the tax on an amount. Tax is 10% of the amount. Test it with different amounts.
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.
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
def to define a function.return to send a value back.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
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!
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
with open("data.txt", "r") as file:content = file.read()print(content)
Step 1: with open("data.txt", "r") as file:
Step 2: content = file.read()
Step 3: print(content)
Step 4: Run the program!
with open("data.txt", "r") as file: print(file.read())with open("output.txt", "w") as file: file.write("Hello")with open("log.txt", "a") as file: file.write("New entry\n")with open("names.txt", "r") as file: for line in file: print(line.strip())import os; if os.path.exists("data.txt"): print("Exists")with open("students.txt", "r") as file: for name in file: print("Student: " + name.strip())with open("grades.txt", "w") as file: file.write("Aisha: 85\nChidi: 90\n")with open("sales.txt", "a") as file: file.write("1000 Naira\n")with open("cities.txt", "r") as file: for city in file: print(city.strip())import os; if os.path.exists("states.txt"): print("File found")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")with open("todo.txt", "r") as file: for task in file: print("- " + task.strip())with open("groceries.txt", "a") as file: file.write("Milk\n")with open("journal.txt", "a") as file: file.write("Today was a good day.\n")with open("reminders.txt", "r") as file: print(file.read())with open("recipe.txt", "r") as file: for line in file: print(line.strip())with for safe file handling."r" for reading, "w" for writing, "a" for appending.with: Forgetting the with statement.with for all file operations.strip() when reading lines.| Mode | Description |
|---|---|
"r" | Read (default) |
"w" | Write (overwrites) |
"a" | Append (adds to end) |
"r+" | Read and write |
| Operation | Code |
|---|---|
| Read entire file | file.read() |
| Read one line | file.readline() |
| Read all lines | file.readlines() |
| Write | file.write(text) |
| Append | file.write(text) |
+----------------------+
| Open file |
+----------------------+
|
V
+----------------------+
| Read or Write data |
+----------------------+
|
V
+----------------------+
| Close file |
+----------------------+
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!
open("filename.txt", "mode")with statement? Automatically closes files."r" mode? Read mode."w" mode? Write mode."a" mode? Append mode.file.read()file.write(text)file.close()os.path.exists()with statement?open()?"w" mode do?"a" mode do?with?open() to ______________ a file. (open)"r" mode is for ______________. (reading)"w" mode is for ______________. (writing)with statement automatically ______________ files. (closes)"w" mode appends to a file. (False)with statement automatically closes files. (True)open("file.txt", "r") โ
open("file.txt")file.open("file.txt")"r" mode?"w" mode?"a" mode?with statement do?file.read() โ
file.write()file.close()file.read()file.write() โ
file.close()file.close() โ
file.stop()file.end()os.path.exists() โ
file.exists()exists.file()open()?"r" โ
"w""a""w" mode do to an existing file?"a" mode do?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Read | A) Write to a file |
| 2. Write | B) Get data from a file |
| 3. Append | C) Automatically closes files |
| 4. with | D) Add to the end |
| 5. close | E) Release a file |
(Answers: 1-B, 2-A, 3-D, 4-C, 5-E)
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.
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.
Create a program that reads a file of numbers, calculates their sum, and writes the sum to another file.
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.
Write a program that reads a file of student grades, calculates the average, and writes the average to another file.
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.
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
open() to open a file."r" for reading, "w" for writing, "a" for appending.with for safe file handling.with.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
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!
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
csv and openpyxl.import csvwith open("data.csv", "r") as file:reader = csv.reader(file)for row in reader: print(row)
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)
import csv; with open("data.csv", "r") as file: reader = csv.reader(file); for row in reader: print(row)import csv; with open("output.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Name", "Score"])from openpyxl import load_workbook; wb = load_workbook("data.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Hello"; wb.save("output.xlsx")with open("data.csv", "r") as file: reader = csv.DictReader(file); for row in reader: print(row["Name"])import csv; with open("students.csv", "r") as file: reader = csv.DictReader(file); for row in reader: print(row["Name"] + " from " + row["City"])import csv; with open("grades.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Name", "Grade"]); writer.writerow(["Aisha", 85])from openpyxl import load_workbook; wb = load_workbook("sales.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Product"; sheet["B1"] = "Sales"; wb.save("sales.xlsx")with open("customers.csv", "r") as file: reader = csv.DictReader(file); for row in reader: print("Hello, " + row["Name"])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"])import csv; with open("shopping.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Item", "Quantity"]); writer.writerow(["Milk", 2])from openpyxl import Workbook; wb = Workbook(); sheet = wb.active; sheet["A1"] = "Expense"; sheet["B1"] = "Amount"; wb.save("budget.xlsx")from openpyxl import load_workbook; wb = load_workbook("budget.xlsx"); sheet = wb.active; for row in sheet.iter_rows(values_only=True): print(row)import csv; with open("tasks.csv", "w") as file: writer = csv.writer(file); writer.writerow(["Task", "Done"]); writer.writerow(["Clean room", "No"])import csv; with open("tasks.csv", "r") as file: reader = csv.reader(file); for row in reader: print(row)openpyxl can read and write Excel files?csv.reader to read CSV files.csv.writer to write CSV files.openpyxl for Excel files.import csv or from openpyxl import load_workbookwith to manage files.with when opening files.DictReader and DictWriter for easier data access.| CSV | Excel |
|---|---|
| Plain text | Binary format |
| Small file size | Larger file size |
| Simple | Feature-rich |
Read with csv | Read with openpyxl |
| Method | Description |
|---|---|
csv.reader() | Reads CSV rows as lists |
csv.DictReader() | Reads CSV rows as dictionaries |
| Method | Description |
|---|---|
load_workbook() | Loads an Excel file |
sheet.iter_rows() | Iterates over rows |
sheet["A1"] | Accesses a cell |
+----------------------+
| Read Data from CSV or Excel |
+----------------------+
|
V
+----------------------+
| Process Data |
| (calculate, filter, etc.) |
+----------------------+
|
V
+----------------------+
| Write Results to CSV or Excel |
+----------------------+
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!
csv.reader.csv.writer.DictReader? Reads CSV as dictionaries.DictWriter? Writes dictionaries to CSV.openpyxl.load_workbook.openpyxl.Workbook.openpyxl? A library for Excel files.DictReader?DictWriter?openpyxl?openpyxl?csv.______________ to read CSV files. (reader)csv.______________ to write CSV files. (writer)______________ is a library for Excel files. (openpyxl)openpyxl.______________ to load an Excel file. (load_workbook)DictReader reads CSV rows as dictionaries. (True)openpyxl is used for CSV files. (False)csv.reader โ
csv.writercsv.readcsv.readercsv.writer โ
csv.writeDictReader?DictWriter?openpyxl?pip install openpyxl โ
install openpyxlpip get openpyxlopenpyxl.load_workbook โ
openpyxl.read_excelopenpyxl.openopenpyxl.Workbook โ
openpyxl.write_excelopenpyxl.createopenpyxl?sheet["A1"] โ
sheet.cell("A1")sheet.get("A1")Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. CSV | A) A spreadsheet file format |
| 2. Excel | B) Comma-Separated Values |
| 3. DictReader | C) Reads CSV as dictionaries |
| 4. openpyxl | D) A library for Excel files |
| 5. Row | E) Horizontal line of data |
(Answers: 1-B, 2-A, 3-C, 4-D, 5-E)
openpyxl and how do you use it?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.
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.).
Create a program that reads a CSV file of products (Name, Price, Quantity) and calculates the total value of each product (Price * Quantity).
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.
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.
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.
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
csv module for CSV files.openpyxl for Excel files.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
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!
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
import smtplib; from email.message import EmailMessagemsg = EmailMessage()msg.set_content("Your message here.")msg["Subject"] = "Subject"; msg["From"] = "sender@email.com"; msg["To"] = "recipient@email.com"with smtplib.SMTP("smtp.gmail.com", 587) as server: server.starttls(); server.login("your_email", "password")server.send_message(msg)
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)
msg.set_content("Hello"); msg["Subject"] = "Greeting"msg["To"] = "a@email.com, b@email.com"msg.set_content("Hello " + name)msg.add_attachment(file_data, filename="file.pdf")send_alert("Temperature is too low.")msg.set_content(f"Hello {name}, your grade is {grade}.")msg.set_content("Please find your invoice attached."); msg.add_attachment(pdf_data, filename="invoice.pdf")send_alert("Sales have reached 1,000,000 Naira.")msg.set_content("Don't forget the meeting at 3pm.")for customer in customers: send_custom_email(customer)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!")msg.set_content("Don't forget to buy milk.")msg.set_content("I finished my homework.")msg.set_content("You are invited to my party.")msg.set_content("Thank you for your help.")msg.add_attachment(photo_data, filename="photo.jpg")
+----------------------+
| Create Email |
+----------------------+
|
V
+----------------------+
| Connect to SMTP |
+----------------------+
|
V
+----------------------+
| Login to Email |
+----------------------+
|
V
+----------------------+
| Send Email |
+----------------------+
| Part | Description | Example |
|---|---|---|
| Subject | Title of the email | "Test Email" |
| From | Sender's email | "your_email@gmail.com" |
| To | Recipient's email | "recipient@email.com" |
| Body | Content of the email | "Hello, this is a test." |
| Service | Server | Port |
|---|---|---|
| Gmail | smtp.gmail.com | 587 |
| Yahoo | smtp.mail.yahoo.com | 587 |
| Outlook | smtp.office365.com | 587 |
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!
smtplib and EmailMessage.smtp.gmail.commsg.add_attachment()______________ class is used to create email messages. (EmailMessage)______________ to add an attachment. (add_attachment)______________ to enable TLS. (starttls)smtplib โ
emailmailEmailMessage โ
EmailMessagemsg["Subject"] โ
msg.subjectmsg.set_subject()msg["From"] โ
msg["Sender"]msg.set_from()msg["To"] โ
msg["Receiver"]msg.set_to()server.send_message(msg) โ
server.send(msg)server.send_email(msg)add_attachment() โ
attach_file()add_file()smtp.gmail.com โ
smtp.gmail.netgmail.smtp.comMatch the word with its meaning:
| Word | Meaning |
|---|---|
| 1. SMTP | A) A security protocol |
| 2. TLS | B) Simple Mail Transfer Protocol |
| 3. Attachment | C) The person receiving the email |
| 4. Recipient | D) A file sent with an email |
| 5. Subject | E) The title of the email |
(Answers: 1-B, 2-A, 3-D, 4-C, 5-E)
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.
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.
Write a program that sends an email to yourself with the current date and time. Schedule it to run every day.
Create a program that reads a list of students from a CSV file and sends each student a personalised email with their grade.
Write a program that sends a daily reminder email to yourself with a list of tasks from a text file.
Write a program that reads a CSV file of customer data, generates a personalised invoice for each customer, and sends it as an attachment.
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
smtplib and EmailMessage.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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
h1, p, a).href, class).requests.import requests; from bs4 import BeautifulSoupresponse = requests.get("https://example.com")soup = BeautifulSoup(response.text, "html.parser")data = soup.find_all("tag", class_="class")for item in data: print(item.text)
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)
response = requests.get("https://example.com")soup = BeautifulSoup(response.text, "html.parser")soup.find("h1").textsoup.find_all("a")soup.find_all(class_="price")soup.find_all(class_="headline") on a Nigerian news site.soup.find_all(class_="price") on a Nigerian e-commerce site.soup.find_all(class_="rate") on a financial site.soup.find_all(class_="job-title") on a job site.soup.find(class_="temperature").text on a weather site.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.soup.find(class_="temp").text to get the temperature.soup.find_all(class_="headline") to get headlines.soup.find_all(class_="movie-title") to get movie titles.soup.find_all(class_="recipe-name") to get recipe names.soup.find_all(class_="score") to get scores.requests.BeautifulSoup.find_all() to find elements..text to get text.get("href") to get links.robots.txt file.
+----------------------+
| Fetch Web Page |
| (requests.get()) |
+----------------------+
|
V
+----------------------+
| Parse HTML |
| (BeautifulSoup) |
+----------------------+
|
V
+----------------------+
| Find Data |
| (find_all(), etc.) |
+----------------------+
|
V
+----------------------+
| Extract & Use Data |
| (save to file, etc.) |
+----------------------+
| Method | Description |
|---|---|
find() | Finds the first matching element |
find_all() | Finds all matching elements |
.text | Extracts text from an element |
get("href") | Extracts a link from an a tag |
class_ | Finds elements by class |
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)
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!
requests and beautifulsoup4.requests.get(url)BeautifulSoup(response.text, "html.parser")find_all(), find(), etc..text.get("href")robots.txt? A file that tells scrapers what is allowed.a tag?robots.txt?find() and find_all()?______________ library to fetch web pages. (requests)______________ to parse HTML. (BeautifulSoup)______________ to find all elements. (find_all)______________ to extract text from an element. (.text)requests and beautifulsoup4. (True)find_all() finds the first element. (False).text extracts text from an element. (True)requests โ
BeautifulSoupcsvrequestsBeautifulSoup โ
smtplibrequests.get(url) โ
requests.fetch(url)requests.open(url)BeautifulSoup(response.text, "html.parser") โ
parse(response.text)html.parse(response.text)find_all() โ
find()search().text โ
.get().contentget("href") โ
get("link")get("url")class_ โ
classclassNamerobots.txt?find() and find_all()?find() finds one, find_all() finds all โ
find() finds all, find_all() finds oneMatch the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Web scraping | A) A library for fetching web pages |
| 2. requests | B) A library for parsing HTML |
| 3. BeautifulSoup | C) Extracting data from websites |
| 4. find_all() | D) Finds all matching elements |
| 5. robots.txt | E) A file that tells scrapers what is allowed |
(Answers: 1-C, 2-A, 3-B, 4-D, 5-E)
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.
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.
Write a program that scrapes the titles of the top 5 news articles from a news website and prints them.
Create a program that scrapes the latest news headlines from a website and sends them to you via email.
Write a program that scrapes product prices from a website and alerts you when the price drops below a certain value.
Write a program that scrapes data from multiple pages of a website and saves all the data to a single CSV file.
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
requests to fetch web pages.BeautifulSoup to parse HTML.find_all(), find(), etc. to find data.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
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.
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!
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.
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.
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.
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.
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.
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.
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.
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().
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.
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.
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.
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.
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!
from selenium import webdriverdriver = 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()import time; time.sleep(2)driver.quit()
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()
driver.get("https://example.com/login"); username.send_keys("user"); password.send_keys("pass"); login_btn.click()search = driver.find_element("name", "q"); search.send_keys("Python"); search.submit()name.send_keys("Aisha"); email.send_keys("aisha@email.com"); submit.click()driver.save_screenshot("page.png")WebDriverWait(driver, 10).until(EC.presence_of_element_located(("id", "username")))driver.get("https://bank.com/login"); username.send_keys("1234567890"); password.send_keys("my_password"); login_btn.click()driver.get("https://schoolportal.com"); username.send_keys("student_id"); password.send_keys("password"); login_btn.click()search = driver.find_element("name", "search"); search.send_keys("rice"); search.submit()name.send_keys("Chidi"); email.send_keys("chidi@email.com"); submit.click()driver.save_screenshot("transaction.png")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()driver.get("https://gmail.com"); username.send_keys("my_email"); password.send_keys("my_password"); login_btn.click()driver.get("https://amazon.com"); search.send_keys("books"); search.submit()driver.get("https://bbc.com"); headlines = driver.find_elements("class", "headline"); for headline in headlines: print(headline.text)driver.get("https://weather.com"); temp = driver.find_element("class", "temp"); print(temp.text)driver.get("https://twitter.com"); login_btn.click()send_keys() to type text.click() to click buttons.WebDriverWait to wait for elements.driver.quit().WebDriverWait for loading pages.
+----------------------+
| 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() |
+----------------------+
| Method | Description |
|---|---|
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 |
| Selenium | BeautifulSoup |
|---|---|
| Controls browser | Parses HTML |
| Can interact with pages | Only extracts data |
| Slower | Faster |
| Handles JavaScript | Doesn't handle JavaScript |
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!
pip install seleniumdriver = webdriver.Chrome()driver.get(url)driver.find_element(by, value)element.send_keys(text)element.click()driver.save_screenshot(file)driver.quit()find_element() and find_elements()?WebDriverWait used for?______________ to start a Chrome browser. (webdriver.Chrome())______________ to open a website. (driver.get(url))______________ to type text into an element. (send_keys)______________ to click an element. (click)find_element() finds one element. (True)send_keys() is used to type text. (True)driver.quit() closes the browser. (True)pip install selenium โ
install seleniumpip get seleniumwebdriver.Chrome() โ
start.browser()open.browser()driver.get(url) โ
driver.open(url)driver.navigate(url)driver.find_element(by, value) โ
driver.find(by, value)driver.element(by, value)element.send_keys(text) โ
element.type(text)element.enter(text)element.click() โ
element.press()element.select()driver.save_screenshot(file) โ
driver.screenshot(file)driver.capture(file)WebDriverWait โ
time.sleep()wait_for_element()driver.quit() โ
driver.close()driver.stop()find_elements()?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Selenium | A) Opens a website |
| 2. WebDriver | B) 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)
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.
In groups of 3, create a program that automates a common web task (like checking the weather, getting news, or checking grades).
Write a program that automates logging into a website of your choice. Take a screenshot after login.
Create a program that automates a complete workflow: login, extract data, take a screenshot, and save the data to a file.
Write a program that automates filling a form on a website. Include at least 5 fields.
Write a program that logs into a website, navigates to a specific page, extracts data, and saves it to a CSV file.
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
driver.get() to open websites.find_element() to find elements.send_keys() to type text.click() to click buttons.WebDriverWait to wait for elements.driver.quit().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
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!
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
script.py.python.exe (e.g., C:\Python39\python.exe). Add the script path as an argument.
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
0 8 * * * python daily_report.py0 * * * * python hourly_update.py0 0 * * 0 python weekly_backup.py0 0 1 * * python monthly_summary.py0 0 1 1 * python yearly_report.py0 8 * * * python sales_report.py0 9 * * * python exchange_rate.py0 7 * * * python weather.py0 2 * * * python backup.py0 6 * * * python send_email.py0 12 * * * python lunch_reminder.py0 15 * * * python play_time.py0 20 * * * python story_time.py0 8 * * 1 python monday_greeting.py0 9 * * 6 python weekend_fun.py0 7 * * * python morning_reminder.py0 13 * * * python afternoon_task.py0 19 * * * python evening_report.py0 22 * * * python night_backup.py0 10 * * 6 python weekend_cleanup.py| Field | Values | Example |
|---|---|---|
| Minute | 0-59 | 0 |
| Hour | 0-23 | 8 |
| Day | 1-31 | * |
| Month | 1-12 | * |
| Day of Week | 0-6 (0=Sunday) | * |
| Schedule | Cron Expression |
|---|---|
| Every day at 8am | 0 8 * * * |
| Every hour | 0 * * * * |
| Every minute | * * * * * |
| Every Sunday at 9am | 0 9 * * 0 |
| First of every month | 0 0 1 * * |
+----------------------+
| Create Script |
+----------------------+
|
V
+----------------------+
| Test Script Manually |
+----------------------+
|
V
+----------------------+
| Set up Schedule |
+----------------------+
|
V
+----------------------+
| Monitor and Adjust |
+----------------------+
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!
Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Schedule | A) The event that starts a task |
| 2. Task Scheduler | B) A Windows scheduling tool |
| 3. Cron | C) A macOS/Linux scheduling tool |
| 4. Trigger | D) To set a task to run automatically |
| 5. Action | E) The task to run |
(Answers: 1-D, 2-B, 3-C, 4-A, 5-E)
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?
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.
Create a script that saves the current time to a file. Schedule it to run every hour. Check the file after a few hours.
Create a script that sends a daily "Good Morning" email to yourself. Schedule it to run every day at 7am.
Write a script that checks the weather every morning and saves the data to a file. Schedule it to run daily.
Write a script that scrapes a website, processes the data, and sends a report via email. Schedule it to run every day at 8am.
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
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
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!
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
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! ๐
+----------------------+
| 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 Idea | Tools | Skills Used |
|---|---|---|
| Price Tracker | requests, BeautifulSoup, csv, smtplib | Web scraping, files, email |
| Daily Report | csv, smtplib, schedule | Files, email, scheduling |
| File Organiser | os, shutil | Files, automation |
| Email Reminder | smtplib, schedule | Email, scheduling |
| Web Scraper | requests, BeautifulSoup | Web scraping |
โ Project idea chosen
โ Project plan written
โ Problem broken down
โ Tools chosen
โ Code written
โ Code tested
โ Errors fixed
โ Code documented
โ Project presented
โ Success celebrated!
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!
Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Project | A) To divide into smaller parts |
| 2. Plan | B) A task you solve with code |
| 3. Break down | C) To check if something works |
| 4. Test | D) To organise your work |
| 5. Document | E) To write about your project |
(Answers: 1-B, 2-D, 3-A, 4-C, 5-E)
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?
In groups of 3, share your projects with each other. Give feedback and suggestions. Celebrate each other's work.
Plan and build your own automation project. Use all the skills you have learned. Document your project and present it.
Build a complete automation project of your choice. It should include at least 3 different skills (e.g., web scraping, email, scheduling).
Write a full automation project that solves a real problem for you. Document it and share it with the class.
Build a project that combines web scraping, data processing, and email automation. Schedule it to run daily.
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
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:
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