Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Fundamentals Of Cyber Security Scripting · Lesson 3 of 9

Module Two

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
3
📘 Module 2: Fundamentals of Cyber Security Scripting

🛡️ Module 2: Fundamentals of Cyber Security Scripting

Welcome back, young cyber hero! This is Module 2 of our exciting course.

📖 Module Introduction

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!

🎯 Learning Objectives

After reading this module, you will be able to:

  • Use variables to store important information.
  • Write conditions to make decisions in your scripts.
  • Create loops to repeat actions automatically.
  • Define functions to organise your code.
  • Read from and write to files.
  • Use modules to add extra powers to your scripts.
  • Handle errors so your script doesn’t crash.
  • Keep your scripts secure.

📖 Warm‑up Story: The Smart Security Camera

Chidi lives in Abuja, Nigeria. His family has a smart security camera at home. The camera can do three things:

  • It can check if someone is at the door.
  • It can send a message to Chidi’s phone.
  • It can record video.

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.

📘 Lesson 1: Variables – Storing Information

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.


📘 Lesson 2: Conditions – Making Decisions

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.


📘 Lesson 3: Loops – Repeating 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.


📘 Lesson 4: Functions – Grouping Instructions

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.


📘 Lesson 5: Reading and Writing Files

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.


📘 Lesson 6: Modules – Using Ready-made Tools

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.


📘 Lesson 7: Error Handling – Being Safe

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.


📘 Lesson 8: Simple Logging – Keeping Records

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.


📘 Lesson 9: Automating Security Checks

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.


📘 Lesson 10: Keeping Scripts Secret – Passwords and Keys

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.


📘 Lesson 11: Testing Your Scripts

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.


📘 Lesson 12: Debugging – Finding and Fixing Mistakes

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.


📘 Lesson 13: Comments – Explaining Your Script

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.


📘 Lesson 14: Combining Concepts – A Security Script

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.


📘 Lesson 15: Ethical Hacking and 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.


📚 Key Vocabulary

  • Variable: A container for storing data.
  • Condition: A true/false test that decides what to do.
  • Loop: Repeats a set of instructions.
  • Function: A named block of reusable code.
  • Module: A toolbox of pre‑written code.
  • Log: A record of events.
  • Automation: Letting scripts do tasks automatically.
  • Error handling: Catching mistakes without crashing.
  • Testing: Checking if a script works correctly.
  • Debugging: Finding and fixing errors.
  • Comment: A note in the script for humans.
  • Ethical hacking: Using scripts to protect systems.

🧠 Important Concepts

  • Variables store information.
  • Conditions let scripts make decisions.
  • Loops repeat actions.
  • Functions organise code.
  • Modules add extra powers.
  • Logging keeps a history.
  • Automation saves time.
  • Always test and keep secrets safe.
  • Debugging fixes mistakes.
  • Ethical hacking protects people.

🧩 Step‑by‑Step: Writing a Security Script

  1. Think – What do you want the script to do? (e.g., check if a password is strong)
  2. Plan – Write down the steps on paper.
  3. Code – Type the instructions in a .py file.
  4. Test – Run the script and see if it works.
  5. Fix – If it doesn’t work, find and correct mistakes.
  6. Use – Run it for real to protect something.
  Step 1: Define the problem
  Step 2: Write pseudo‑code
  Step 3: Write actual code
  Step 4: Run and debug
  Step 5: Deploy

🌍 Real‑life Examples

  • Google uses scripts to block billions of spam emails daily.
  • Banks use scripts to detect fraud.
  • Hospitals use scripts to keep patient data safe.
  • Social media platforms use scripts to remove harmful content.

🇳🇬 Nigerian Examples

  • Nigerian fintech companies use scripts to monitor transactions.
  • Schools in Lagos use scripts to manage student records.
  • MTN Nigeria uses scripts to secure their networks.
  • Nigerian banks use scripts to detect fraudulent activities.

🎉 Fun Examples Children Relate To

  • A script that counts how many candies you have.
  • A script that decides if you can watch TV based on homework done.
  • A script that gives you a compliment every day.
  • A script that plays a sound when you open your favourite app.

🏠 Everyday Examples

  • Your phone alarm is a script.
  • Automatic lights in the street.
  • Email filters that sort spam.
  • Smart thermostats that adjust temperature.

🧑‍🏫 Teacher Notes

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.

👨‍👩‍👦 Parent Tips

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.

💡 Interesting Facts

  • The first computer virus was created in 1983.
  • Python was named after the comedy group Monty Python.
  • More than 70% of companies use Python for security tasks.
  • The first script was written in 1941 for the Z3 computer.
  • Bash was created in 1989 and is still used today.

🤔 Did You Know?

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”!

🧾 Remember This

  • Scripts are instructions for computers.
  • Always test your scripts.
  • Keep your scripts and secrets safe.
  • Cyber scripts protect us every day.
  • Debugging is a superpower.
  • Ethical hackers are the good guys.

❌ Common Mistakes

  • Forgetting to close a parenthesis ( ) or quote “ “.
  • Using a variable without defining it first.
  • Putting sensitive information like passwords directly in code.
  • Not testing before using.
  • Using = instead of == in conditions.
  • Not using indentation (spaces) properly in Python.

✅ Best Practices

  • Use meaningful variable names (e.g., password_attempt).
  • Add comments to explain what your script does.
  • Keep scripts short and focused.
  • Store secrets in environment variables, not in code.
  • Test with different inputs.
  • Use functions to organise your code.
  • Handle errors gracefully.

📟 ASCII Diagrams

  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
  |                   |
  +-------------------+

📊 Comparison: Python vs Bash

FeaturePythonBash
ReadabilityVery easyModerate
Best forGeneral automation, security toolsFile operations, system commands
Learning curveGentleSteeper
Cross-platformYesLinux/Unix mostly

📊 Comparison: if vs loop

Featureif (condition)for/while (loop)
PurposeMake a decisionRepeat an action
ExecutionOnceMultiple times
ExampleIf password is correct, grant access.Check all files in a folder.

📝 End‑of‑Module Summary

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!

❓ Frequently Asked Questions

  1. What is the difference between a variable and a function? A variable stores data; a function is a set of instructions.
  2. Why do we use loops? Loops repeat actions so we don't have to write the same code many times.
  3. What is a module? A module is a toolbox of pre-written code.
  4. How do I handle errors? Use try/except blocks to catch errors.
  5. What is debugging? Debugging is finding and fixing mistakes in your code.
  6. Why are comments important? Comments help you and others understand your code.
  7. What is ethical hacking? Using scripts to find and fix security problems, not to cause harm.
  8. How do I test my script? Run it with different inputs and check if it works correctly.
  9. Why should I keep my script secret? So bad people can't change it to do bad things.
  10. What is automation? Letting scripts do tasks automatically, without human help.

📋 Review Questions

  1. What is a variable?
  2. What does a condition do?
  3. What is a loop?
  4. Why are functions useful?
  5. What is a module?
  6. What is error handling?
  7. Why is logging important?
  8. What does automation mean?
  9. How can you keep your script safe?
  10. Why do we test scripts?
  11. What is debugging?
  12. Why are comments important?
  13. What is ethical hacking?
  14. Give one Nigerian example of a security script.
  15. What is the first script you wrote in this module?

✏️ Fill‑in‑the‑Blank

  1. A __________ is a container for storing data. (variable)
  2. A __________ is a true/false test that decides what to do. (condition)
  3. A __________ repeats a block of code. (loop)
  4. A __________ is a named block of reusable code. (function)
  5. A __________ is a toolbox of pre‑written code. (module)
  6. __________ means letting scripts do tasks automatically. (Automation)
  7. __________ is finding and fixing errors. (Debugging)
  8. __________ are notes in the script for humans. (Comments)

✔️ True or False

  1. Variables store data. (True)
  2. Conditions can only check numbers. (False)
  3. Loops repeat actions. (True)
  4. Functions cannot be reused. (False)
  5. Modules are built-in tools. (True)
  6. Error handling makes scripts crash. (False)
  7. Logging is not important. (False)
  8. Automation saves time. (True)
  9. You should always put passwords in your script. (False)
  10. Testing is not important. (False)
  11. Debugging is finding errors. (True)
  12. Comments are ignored by the computer. (True)
  13. Ethical hacking is illegal. (False)

🔘 Multiple Choice Questions

  1. Which of these is a variable?
    A) 5 B) age = 10 C) print() D) if
    Answer: B
  2. What does a condition check?
    A) True/False B) Colour C) Size D) Speed
    Answer: A
  3. Which statement repeats code?
    A) if B) for C) def D) import
    Answer: B
  4. What is a function?
    A) A variable B) A reusable block C) A loop D) A module
    Answer: B
  5. Which module helps with dates?
    A) os B) datetime C) sys D) math
    Answer: B
  6. What is the extension for Python files?
    A) .txt B) .py C) .java D) .c
    Answer: B
  7. Which of these is good practice?
    A) Storing passwords in code B) Testing scripts C) Ignoring errors D) Writing long unreadable code
    Answer

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→