Welcome back, young cyber hero! This is Module 2 of our exciting course.
In Module 1, we learned what scripts are and why they are important. Now, in Module 2, we are going to go deeper. We will learn how to write scripts that make decisions, repeat actions, and talk to files. We will also learn how to keep our scripts safe and test them. By the end of this module, you will be able to write a script that acts like a security guard for your computer. Let’s dive in!
After reading this module, you will be able to:
Chidi lives in Abuja, Nigeria. His family has a smart security camera at home. The camera can do three things:
But the camera needs instructions. Chidi’s dad wrote a script that says: “If you see a person, send a message and start recording. If you don’t see anyone, do nothing. Repeat this every 5 seconds.” This script uses conditions (if/else), loops (repeat), and functions (send message, record). Chidi thought, “I want to write scripts like this!” And that is exactly what we will learn in Module 2.
Definition: A variable is like a box where you store a value (number, text, or list).
Why important: Variables help us remember things in our script.
Simple explanation: Like a jar with a label. You put candies in it and can take them out later.
Real-life example: Let age = 10. Then you can use age later to check if someone is old enough.
School example: score = 100. Use it to reward a student.
Home example: door_locked = True. Use it to decide if the alarm should be on.
Nigerian example: balance = 5000 (in Naira). Use it to check if you can buy data.
# variables example name = "Chidi" age = 10 is_secure = True print(name, "is", age, "years old.")
Mini summary: Variables store data for later use.
Definition: Conditions are like questions that have True or False answers. They help scripts decide what to do.
Why important: They allow scripts to react differently in different situations.
Simple explanation: If it rains, take an umbrella. Else, wear sunglasses. The script checks the condition.
Real-life example: If a login password is wrong, deny access.
School example: If homework is done, you can play.
Home example: If the window is open, close it.
Nigerian example: If NEPA (electricity) is on, charge your phone; else, use a power bank.
password = "secure123"
if password == "secure123":
print("Access granted!")
else:
print("Access denied.")
Mini summary: Conditions let scripts choose between actions.
Definition: A loop repeats a block of instructions several times.
Why important: They save us from writing the same instruction over and over.
Simple explanation: Like singing “Happy Birthday” three times. A loop does that for you.
Real-life example: A script that checks 1000 files one by one – it uses a loop.
School example: Count from 1 to 10 using a loop.
Home example: Repeat “check the door” 5 times.
Nigerian example: A loop can check all 50 students’ scores and find the highest.
for i in range(5):
print("Checking door", i+1)
Mini summary: Loops repeat tasks automatically.
Definition: A function is a named group of instructions that you can call (run) whenever you want.
Why important: Functions keep your script neat and reusable.
Simple explanation: Like a “make_jollof” recipe – you can use it anytime you want to cook.
Real-life example: A function “scan_for_virus” that you can call many times.
School example: A function “calculate_average” for grades.
Home example: A function “lock_doors” that locks all doors.
Nigerian example: A function “send_alert” that sends a message to the security team.
def lock_doors():
print("Locking front door")
print("Locking back door")
# call the function
lock_doors()
Mini summary: Functions are reusable blocks of code.
Definition: Scripts can read data from files and write data to files.
Why important: This helps scripts keep logs (records) of what they did.
Simple explanation: Like keeping a diary. The script writes what it checked.
Real-life example: A script reads a list of bad IP addresses and blocks them.
School example: Read a list of student names and print each one.
Home example: Write a shopping list to a file.
Nigerian example: A script reads a list of bank account numbers to monitor for fraud.
# write to file
with open("log.txt", "w") as f:
f.write("All doors checked at 10pm")
Mini summary: Files help scripts store and retrieve data.
Definition: Modules are like toolboxes full of extra functions that other people made.
Why important: They save time – we don’t have to invent everything ourselves.
Simple explanation: Like using a calculator instead of doing long addition by hand.
Real-life example: The “os” module helps interact with the computer’s operating system.
School example: The “math” module gives you sin, cos, and more.
Home example: The “datetime” module helps get the current time.
Nigerian example: Use the “requests” module to check if a website is up.
import datetime
now = datetime.datetime.now()
print("Current time:", now)
Mini summary: Modules add superpowers to your scripts.
Definition: Error handling is a way to catch mistakes (errors) without crashing the script.
Why important: It makes scripts strong and reliable.
Simple explanation: Like wearing a helmet when riding a bike – if you fall, you are safe.
Real-life example: If a file is missing, the script tells you, instead of breaking.
School example: If a student’s name is not found, print “Not found”.
Home example: If the light bulb is broken, try another one.
Nigerian example: If the network is slow, the script waits and retries.
try:
file = open("missing.txt")
except:
print("File not found, but script continues.")
Mini summary: Error handling keeps scripts from crashing.
Definition: Logging means writing down what the script did, with timestamps.
Why important: Logs help us see what happened if something goes wrong.
Simple explanation: Like a diary for the script.
Real-life example: A script logs “2026-06-27 10:00: Door checked – OK”.
School example: Log when each student finishes a test.
Home example: Log when the alarm is turned on/off.
Nigerian example: A bank script logs every ATM withdrawal.
import logging
logging.basicConfig(filename='security.log', level=logging.INFO)
logging.info('Security check completed.')
Mini summary: Logging keeps a history of actions.
Definition: Automation means letting scripts do the repetitive work for us.
Why important: Humans get tired; scripts don’t.
Simple explanation: Like a robot vacuum that cleans the floor while you play.
Real-life example: A script that automatically updates antivirus definitions.
School example: A script that backs up all homework files every Friday.
Home example: A script that turns off lights at 11pm.
Nigerian example: A script that checks the weather every morning and sends a WhatsApp message.
# pseudo-code for automation
while True:
check_for_updates()
sleep(3600) # wait 1 hour
Mini summary: Automation makes life easier and safer.
Definition: We must protect our scripts so bad guys can’t change them. Use passwords and keep them hidden.
Why important: If an evil hacker changes your script, it may help them instead.
Simple explanation: Like keeping your diary in a locked drawer.
Real-life example: Never put passwords directly in a script; use secret files.
School example: The teacher keeps the answer key in a safe.
Home example: Keep your Wi-Fi password in a secret place.
Nigerian example: Bank scripts use special “API keys” that are never shown to anyone.
# NEVER do this: password = "mysecret123" # INSTEAD, read from a secure file or environment variable.
Mini summary: Keep your scripts and secrets safe.
Definition: Testing means running your script to make sure it works as expected.
Why important: You don’t want a broken script when you need it most.
Simple explanation: Like checking your shoes before a race – make sure they are tied.
Real-life example: Run the script with test data to see if it catches a fake virus.
School example: Test a grading script with sample scores.
Home example: Test the “lock doors” script during the day.
Nigerian example: A fintech startup tests their fraud script with dummy transactions.
# simple test
assert(2 + 2 == 4)
print("Test passed!")
Mini summary: Always test your scripts before using them for real.
Definition: Debugging is the process of finding and fixing errors in your script.
Why important: Every script has bugs (mistakes). Debugging makes them perfect.
Simple explanation: Like solving a puzzle – you look for the missing piece.
Real-life example: If your script says “Hello” but you typed “Helo”, you debug by correcting the spelling.
School example: If your maths answer is wrong, you check your steps.
Home example: If the TV remote doesn’t work, you check the batteries.
Nigerian example: If a bank script fails, the developer checks the logs to find the error.
# Debugging example
# The script should print "Access granted"
# but it prints nothing. We check the condition.
password = "secure123"
if password = "secure123": # Error: should be ==
print("Access granted!")
Mini summary: Debugging is finding and fixing mistakes in your code.
Definition: Comments are notes written in the script that the computer ignores. They are for humans to read.
Why important: Comments help you and others understand what the script does.
Simple explanation: Like writing notes in a textbook.
Real-life example: # This script checks if the door is open.
School example: # This function calculates the average score.
Home example: # Turn on the lights at 6pm.
Nigerian example: # This script sends a message to the security team.
# This is a comment
print("Hello") # This is also a comment
Mini summary: Comments explain your code to humans.
Definition: We can combine variables, conditions, loops, functions, and files to create a powerful security script.
Why important: Real-world scripts use all these concepts together.
Simple explanation: Like cooking a meal – you use many ingredients.
Real-life example: A script that logs login attempts and locks an account after 3 failed attempts.
School example: A script that tracks homework submissions.
Home example: A script that monitors the temperature and sends an alert if too hot.
Nigerian example: A script that monitors bank transactions and alerts if suspicious.
# Security script example
def check_login(username, password):
# Check if username and password are correct
if username == "admin" and password == "secure123":
return True
else:
return False
# Main program
attempts = 0
while attempts < 3:
user = input("Username: ")
pwd = input("Password: ")
if check_login(user, pwd):
print("Access granted!")
break
else:
attempts += 1
print("Wrong password. Attempts left:", 3 - attempts)
if attempts == 3:
print("Account locked.")
Mini summary: Combining concepts makes powerful scripts.
Definition: Ethical hacking is using scripts to find and fix security problems, not to cause harm.
Why important: It helps keep people safe.
Simple explanation: Like being a good detective who helps people.
Real-life example: A company hires ethical hackers to test their systems.
School example: You can write a script to test if your school’s website is secure.
Home example: You can test your home Wi-Fi for vulnerabilities.
Nigerian example: Nigerian banks hire ethical hackers to protect customer data.
# Ethical hacking script (simple)
# Check if a website is using HTTPS (secure)
import requests
url = "https://example.com"
response = requests.get(url)
if response.status_code == 200:
print("Website is up and secure.")
else:
print("Website may be down or insecure.")
Mini summary: Ethical hackers use scripts to protect, not harm.
Step 1: Define the problem Step 2: Write pseudo‑code Step 3: Write actual code Step 4: Run and debug Step 5: Deploy
Encourage students to think of scripts as “recipes”. Use pair programming for activities. Relate every concept to a daily routine. Use the Nigerian context to make it relatable. Emphasise that making mistakes is part of learning – debugging is a superpower! Use the warm-up story to spark interest.
Help your child by setting up a safe computer environment where they can practice. Ask them to explain their script to you. Celebrate small wins. Remind them that cyber security is about staying safe, not just about coding. Encourage them to think about how scripts can help in daily life.
Did you know that the first computer bug was actually a real moth? In 1947, a moth got stuck in a computer and caused an error. That’s why fixing errors is called “debugging”!
password_attempt).
Script Execution Flow
----------------------
Start
|
V
Read input → Process → Decision?
| |
| V
| (If true) → Action A
| (If false)→ Action B
|
V
Output result
|
V
End
Loop Illustration (for 5 times) +---+ +---+ +---+ +---+ +---+ | 1 | → | 2 | → | 3 | → | 4 | → | 5 | +---+ +---+ +---+ +---+ +---+
Function Call Flow +-------------------+ | Main Program | | | | call function | → function does work → return to main | | +-------------------+
| Feature | Python | Bash |
|---|---|---|
| Readability | Very easy | Moderate |
| Best for | General automation, security tools | File operations, system commands |
| Learning curve | Gentle | Steeper |
| Cross-platform | Yes | Linux/Unix mostly |
| Feature | if (condition) | for/while (loop) |
|---|---|---|
| Purpose | Make a decision | Repeat an action |
| Execution | Once | Multiple times |
| Example | If password is correct, grant access. | Check all files in a folder. |
Wow! You have learned so much in Module 2. You now know how to use variables, conditions, loops, functions, and modules. You can read and write files, handle errors, and keep logs. You also know how to keep your scripts safe and test them. You even learned about ethical hacking! Remember, every expert was once a beginner. Keep practicing and you will become a cyber hero!