Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Python for security work

Lab · Easy · 3 hours

Python Coding Lab

Twenty beginner Python exercises, from variables and loops to classes, file I/O and small projects.

  • python
  • exercises
  • loops
  • functions
  • classes
On this page 4 sections
  1. ·Exercises 1–5: The Basics
  2. ·Exercises 6–10: Control Flow & Loops
  3. ·Exercises 11–15: Functions & Data Structures
  4. ·Exercises 16–20: Mini Projects

Before you start

Python is the lingua franca of security work, from quick recon scripts to full exploit toolchains. An engineer who cannot read or write Python cannot automate a task, patch a payload or adapt a public proof of concept. Work through twenty short exercises that cover variables, loops, functions, lists, dictionaries, classes and file I/O.

How to use this lab: Read the challenge, try to write the solution yourself first, then reveal the answer. Type each solution in your Python REPL or a .py file. The goal is productive struggle, not an immediate answer.

Exercises 1–5: The Basics

Exercise 1 — Print & Variables

Create variables for your name, age, and city. Print a sentence using all three. Example output: Hi, I'm Uzair, 25 years old, from Lahore.

# Your solution:
name = ___
age  = ___
city = ___
print(f"Hi, I'm {___}, {___} years old, from {___}.")
Show answer
name = "Uzair"
age  = 25
city = "Lahore"
print(f"Hi, I'm {name}, {age} years old, from {city}.")

Exercise 2 — User Input

Ask the user for two numbers and print their sum, difference, product, and quotient.

Show answer
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Sum:      {a + b}")
print(f"Diff:     {a - b}")
print(f"Product:  {a * b}")
if b != 0:
    print(f"Quotient: {a / b}")
else:
    print("Can't divide by zero!")

Exercise 3 — String Methods

Given the string " Hello, World! ", print it: (a) with whitespace stripped, (b) in uppercase, (c) with "World" replaced by "Python", (d) split into a list of words.

Show answer
s = "  Hello, World!  "
print(s.strip())
print(s.strip().upper())
print(s.strip().replace("World", "Python"))
print(s.strip().split())

Exercise 4 — Number Properties

Ask the user for a number. Print whether it is: even or odd, positive/negative/zero, and divisible by 5.

Show answer
n = int(input("Enter a number: "))
print("Even" if n % 2 == 0 else "Odd")
if n > 0:   print("Positive")
elif n < 0: print("Negative")
else:       print("Zero")
print("Divisible by 5" if n % 5 == 0 else "Not divisible by 5")

Exercise 5 — Temperature Converter

Ask for a temperature in Celsius. Convert it to Fahrenheit (F = C × 9/5 + 32) and Kelvin (K = C + 273.15). Print all three.

Show answer
c = float(input("Enter temperature in Celsius: "))
f = c * 9/5 + 32
k = c + 273.15
print(f"Celsius:    {c}°C")
print(f"Fahrenheit: {f:.2f}°F")
print(f"Kelvin:     {k:.2f}K")

Exercises 6–10: Control Flow & Loops

Exercise 6 — FizzBuzz

Print numbers 1 to 50. But: print "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both.

Show answer
for i in range(1, 51):
    if i % 15 == 0:   print("FizzBuzz")
    elif i % 3 == 0:  print("Fizz")
    elif i % 5 == 0:  print("Buzz")
    else:             print(i)

Exercise 7 — Multiplication Table

Ask for a number and print its full multiplication table (1–12).

Show answer
n = int(input("Enter a number: "))
for i in range(1, 13):
    print(f"{n} × {i} = {n * i}")

Exercise 8 — Factorial

Calculate the factorial of a number entered by the user (e.g., 5! = 120). Use a loop, not math.factorial().

Show answer
n = int(input("Enter a positive number: "))
result = 1
for i in range(1, n + 1):
    result *= i
print(f"{n}! = {result}")

Exercise 9 — Star Patterns

Ask for a number n. Print a right-angle triangle of n rows made of stars. For n=4: row 1 has 1 star, row 2 has 2, etc.

Show answer
n = int(input("Number of rows: "))
for i in range(1, n + 1):
    print("*" * i)

Exercise 10 — Prime Checker

Write a program that checks if a number is prime. A prime is only divisible by 1 and itself (e.g., 2, 3, 5, 7, 11).

Show answer
n = int(input("Check if this number is prime: "))
if n < 2:
    print("Not prime")
else:
    is_prime = True
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            is_prime = False
            break
    print("Prime!" if is_prime else f"Not prime (divisible by {i})")

Exercises 11–15: Functions & Data Structures

Exercise 11 — List Statistics

Create a list of 10 numbers. Write functions (without using built-ins) to find: minimum, maximum, sum, and average.

Show answer
def find_min(lst):
    m = lst[0]
    for x in lst:
        if x < m: m = x
    return m

def find_max(lst):
    m = lst[0]
    for x in lst:
        if x > m: m = x
    return m

def find_sum(lst):
    s = 0
    for x in lst: s += x
    return s

nums = [5, 2, 8, 1, 9, 3, 7, 4, 6, 10]
print(f"Min: {find_min(nums)}")
print(f"Max: {find_max(nums)}")
print(f"Sum: {find_sum(nums)}")
print(f"Avg: {find_sum(nums)/len(nums)}")

Exercise 12 — Word Counter

Ask the user for a sentence. Count how many times each word appears. Print the results sorted by count (most frequent first).

Show answer
sentence = input("Enter a sentence: ").lower()
words = sentence.split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
sorted_words = sorted(counts.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_words:
    print(f"{word}: {count}")

Exercise 13 — Palindrome Checker

Write a function that checks if a string is a palindrome (reads the same forwards and backwards). Ignore spaces and capitalisation. E.g., "A man a plan a canal Panama" is a palindrome.

Show answer
def is_palindrome(s):
    cleaned = s.lower().replace(" ", "")
    return cleaned == cleaned[::-1]

tests = ["racecar", "hello", "A man a plan a canal Panama", "level"]
for t in tests:
    print(f'"{t}" → {"Palindrome ✓" if is_palindrome(t) else "Not palindrome ✗"}')

Exercise 14 — Simple Contact Book

Build a contact book using a dictionary. Support commands: add, find, delete, list, quit.

Show answer
contacts = {}
while True:
    cmd = input("\nCommand (add/find/delete/list/quit): ").lower()
    if cmd == "add":
        name = input("Name: ")
        phone = input("Phone: ")
        contacts[name] = phone
        print(f"Added {name}")
    elif cmd == "find":
        name = input("Search name: ")
        print(contacts.get(name, "Not found"))
    elif cmd == "delete":
        name = input("Name to delete: ")
        if name in contacts:
            del contacts[name]
            print(f"Deleted {name}")
        else:
            print("Not found")
    elif cmd == "list":
        if contacts:
            for n, p in contacts.items(): print(f"{n}: {p}")
        else:
            print("No contacts")
    elif cmd == "quit":
        break

Exercise 15 — List Comprehension Practice

Using list comprehensions (one line each): (a) square numbers 1–10, (b) filter even numbers from 1–20, (c) convert a list of strings to uppercase, (d) get only words longer than 4 letters from a sentence.

Show answer
# a) Squares 1-10
squares = [x**2 for x in range(1, 11)]
print(squares)

# b) Even numbers 1-20
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)

# c) Uppercase
words = ["hello", "world", "python", "coding"]
upper = [w.upper() for w in words]
print(upper)

# d) Long words
sentence = "the quick brown fox jumps over the lazy dog"
long_words = [w for w in sentence.split() if len(w) > 4]
print(long_words)

Exercises 16–20: Mini Projects

Exercise 16 — Caesar Cipher

Implement the Caesar cipher: shift each letter by a number (e.g., shift 3: A→D, B→E). Write encrypt and decrypt functions. Leave non-letters unchanged.

Show answer
def caesar(text, shift, decrypt=False):
    if decrypt: shift = -shift
    result = ""
    for ch in text:
        if ch.isalpha():
            base = ord('A') if ch.isupper() else ord('a')
            result += chr((ord(ch) - base + shift) % 26 + base)
        else:
            result += ch
    return result

msg = "Hello, World!"
enc = caesar(msg, 3)
dec = caesar(enc, 3, decrypt=True)
print(f"Original:  {msg}")
print(f"Encrypted: {enc}")
print(f"Decrypted: {dec}")

Exercise 17 — Number System Converter

Write a program that converts a decimal number to binary, octal, and hexadecimal. Show the work step-by-step for binary (divide by 2 repeatedly).

Show answer
n = int(input("Enter a decimal number: "))
print(f"Decimal:     {n}")
print(f"Binary:      {bin(n)[2:]}")
print(f"Octal:       {oct(n)[2:]}")
print(f"Hexadecimal: {hex(n)[2:].upper()}")

# Manual binary conversion:
temp, bits = n, []
while temp > 0:
    bits.append(temp % 2)
    temp //= 2
print("\nBinary step-by-step:")
print(" → ".join(str(b) for b in reversed(bits)))

Exercise 18 — Simple Bank Account Class

Create a BankAccount class with: deposit, withdraw (check for sufficient funds), get_balance, and transaction history. Test with multiple operations.

Show answer
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner   = owner
        self.balance = balance
        self.history = []

    def deposit(self, amount):
        self.balance += amount
        self.history.append(f"+£{amount:.2f}")
        print(f"Deposited £{amount:.2f}. Balance: £{self.balance:.2f}")

    def withdraw(self, amount):
        if amount > self.balance:
            print(f"Insufficient funds! Balance: £{self.balance:.2f}")
            return False
        self.balance -= amount
        self.history.append(f"-£{amount:.2f}")
        print(f"Withdrew £{amount:.2f}. Balance: £{self.balance:.2f}")
        return True

    def statement(self):
        print(f"\n=== {self.owner}'s Account ===")
        for t in self.history: print(t)
        print(f"Balance: £{self.balance:.2f}")

acc = BankAccount("Uzair", 1000)
acc.deposit(500)
acc.withdraw(200)
acc.withdraw(2000)
acc.statement()

Exercise 19 — File-based Scoreboard

Build a high score tracker that saves scores to a file. Allow: adding a score (name + score), viewing top 5, clearing the board. Scores persist between program runs.

Show answer
import json, os

SCORES_FILE = "scores.json"

def load_scores():
    if os.path.exists(SCORES_FILE):
        with open(SCORES_FILE) as f:
            return json.load(f)
    return []

def save_scores(scores):
    with open(SCORES_FILE, "w") as f:
        json.dump(scores, f)

scores = load_scores()
while True:
    cmd = input("\nadd/top/clear/quit: ").lower()
    if cmd == "add":
        name  = input("Name: ")
        score = int(input("Score: "))
        scores.append({"name": name, "score": score})
        save_scores(scores)
        print("Saved!")
    elif cmd == "top":
        top5 = sorted(scores, key=lambda x: x["score"], reverse=True)[:5]
        print("\n=== TOP 5 ===")
        for i, s in enumerate(top5, 1):
            print(f"{i}. {s['name']}: {s['score']}")
    elif cmd == "clear":
        scores = []
        save_scores(scores)
        print("Cleared!")
    elif cmd == "quit":
        break

Exercise 20 — Text Adventure Game

Build a simple text adventure: 3 rooms (Start, Forest, Cave), items to pick up, a monster to defeat, and a win condition. Use a dictionary for the game world.

Show answer
world = {
    "start": {
        "desc": "You are in a dimly lit room. There is a SWORD on the floor.",
        "items": ["sword"],
        "exits": {"north": "forest"}
    },
    "forest": {
        "desc": "A dark forest. You hear growling to the EAST.",
        "items": ["torch"],
        "exits": {"south": "start", "east": "cave"}
    },
    "cave": {
        "desc": "A cave with a DRAGON! You need a sword to win!",
        "items": [],
        "exits": {"west": "forest"}
    }
}

location = "start"
inventory = []
print("=== DRAGON QUEST ===\n")

while True:
    room = world[location]
    print(f"\n{room['desc']}")
    if room["items"]: print(f"Items here: {', '.join(room['items'])}")
    print(f"Exits: {', '.join(room['exits'].keys())}")

    cmd = input("\n> ").lower().strip()
    if cmd in room["exits"]:
        location = room["exits"][cmd]
        if location == "cave":
            if "sword" in inventory:
                print("\nYou slay the dragon with your sword! YOU WIN! 🏆")
                break
    elif cmd.startswith("take "):
        item = cmd[5:]
        if item in room["items"]:
            inventory.append(item)
            room["items"].remove(item)
            print(f"Picked up {item}.")
        else:
            print(f"No {item} here.")
    elif cmd == "inventory":
        print(f"Inventory: {inventory or 'empty'}")
    elif cmd == "quit":
        break
    else:
        print("Try: north/south/east/west, take [item], inventory, quit")

Lab complete. Completing all 20 exercises builds solid Python fundamentals. Continue practising by building small projects of your own.

Sign in to track progress and send feedback.

This lab is extra practice for the course Python for security work. Do the lessons first.Open the course