Skip to main content
Variables, Control Flow & Functions
Lesson 7 of 10

Variables, Control Flow & Functions

Learn how variables store typed values, how conditionals and loops control program execution, and how to trace Python functions safely before running code.

Beginner 22 min IT foundations

Learning objectives

  • Identify common data types and distinguish assignment from equality comparison in Python
  • Trace how if/elif/else branches and for/while loops evaluate step by step
  • Explain the difference between returning a value from a function and printing output
  • Spot common logic and type bugs by reading short scripts before executing them

Recommended first: Binary, Hexadecimal & Text EncodingCommand Line & Shell Workflow

#Why this matters

Security engineers rarely rely on manual point-and-click work alone. You might write a 15-line Python script to scan lab logs for failed logins, automate an encoding check, or read an unfamiliar script left behind on a system.

Before you ever run a script you found, you must be able to read it and predict what it does. Every imperative program rests on three building blocks: variables to hold data, control flow to make decisions and repeat work, and functions to organise logic cleanly.

#Variables, types and expressions

A variable gives a readable name to a value in memory. In Python, = assigns a value to a name, while == tests whether two values are equal.

Type Example Purpose
int 443 Whole numbers for ports, counts and sizes
str "https" Text enclosed in quotes
bool True or False Logical states used in decisions
list [22, 80, 443] Ordered collection of items

Types matter because operators behave differently depending on the type. Adding two integers (80 + 1) gives 81, whereas adding two strings ("80" + "1") joins them into "801". Mixing int and str with + raises a TypeError.

python
port = 443
service = "https"
is_encrypted = True
allowed_ports = [22, 80, 443]

#Control flow: branching and loops

Programs normally run top to bottom, one line after another. Conditionals (if, elif, else) pick a branch based on a boolean expression using comparisons (==, !=, <, >=) and logical operators (and, or, not). Python groups the code inside each branch by indentation (typically four spaces).

  1. Read failed_countCheck if >= 5
  2. True -> return "lock"False -> check >= 3
  3. True -> return "warn"False -> return "allow"

Loops repeat a block of code without copying and pasting it:

  • A for loop steps through every element in a sequence, such as a list of ports or log lines.
  • A while loop repeats as long as its condition remains True. You must update the variable checked by while inside the loop, or the loop runs forever.

Inside either loop, continue skips to the next iteration and break exits the loop early.

python
ports = [22, 80, 8080, 443]
for port in ports:
    if port < 1024:
        print(port, "privileged")
    else:
        print(port, "unprivileged")

This loop checks four ports in order and classifies each one without repeating the if/else block four times.

#Functions, parameters and return values

A function wraps a task under a name using def. Inputs listed in parentheses are parameters, and the return keyword sends a result back to the caller and ends the function immediately.

python
def classify_attempts(failed_count):
    if failed_count >= 5:
        return "lock"
    elif failed_count >= 3:
        return "warn"
    return "allow"

for count in [1, 3, 6]:
    action = classify_attempts(count)
    print(count, "->", action)

Notice the difference between return and print():

  • print(action) displays text in the terminal for a human, then discards it.
  • return "warn" hands the string back to the caller so the rest of the program can store it in action, compare it or pass it to another function. If a function reaches its end without return, Python returns None.

Variables created inside a function belong to local scope and exist only while that function runs, keeping helper functions from accidentally overwriting variables elsewhere in your script.

#Common mistakes

  • Using = instead of ==: = assigns a value, while == compares values. Writing if x = 5: causes a SyntaxError in Python (and silently overwrites variables in languages like C).
  • Printing instead of returning: Writing print("lock") inside a helper function leaves callers receiving None, which breaks later comparisons like if action == "lock":.
  • Off-by-one thresholds: Confusing > with >=, or forgetting that range(5) produces 0, 1, 2, 3, 4 rather than 1 to 5, causes missed boundary checks.
  • Unchecked input types: Input read from a file or user prompt arrives as a str. Comparing "443" < 1024 raises a TypeError unless you convert it with int() first.
  • Running untrusted scripts to see what they do: Always trace control flow and function calls first in an isolated lab rather than executing unknown code on your host.

#Summary

  • Variables bind names to typed values (int, str, bool, list), and mismatched types change or break operations.
  • Conditionals (if/elif/else) choose a path, while for and while loops repeat actions cleanly.
  • Functions package reusable logic with parameters and pass results back to callers via return rather than print().
  • Tracing code line by line lets you catch boundary bugs and understand unfamiliar scripts before running them.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge