Python Control flow

So far in this Python series you have learned what Python is, how to install it, and how to work with variables and data types. You can store information — but your programs still run straight from top to bottom without making any decisions. That changes now.

Python Control flow image


Control flow is what gives your programs intelligence. It is how Python decides what to do, what to skip, and what to repeat. Every real-world program — from a login system to a game to a hacking script — is built on control flow. This is one of the most important lessons in the entire series.

Table of Contents

  1. What Is Control Flow?
  2. Comparison Operators
  3. Logical Operators
  4. If Statements
  5. elif and else
  6. Nested If Statements
  7. For Loops
  8. While Loops
  9. break and continue
  10. The range() Function
  11. Practical Examples
  12. Frequently Asked Questions
  13. Conclusion

1. What Is Control Flow?

By default, Python reads your code from the first line to the last line, executing each statement in order. Control flow is anything that breaks that straight-line execution and makes Python take a different path depending on conditions or repeat certain actions multiple times.

There are two main tools for control flow in Python:

  • Conditionals — if, elif, else — make decisions based on whether something is true or false
  • Loops — for and while — repeat a block of code multiple times

Before you can use conditionals, you need to understand the operators that let Python compare things.


2. Comparison Operators

A comparison operator compares two values and returns either True or False. These are the building blocks of every condition you will ever write.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than10 > 7True
<Less than3 < 1False
>=Greater than or equal to5 >= 5True
<=Less than or equal to4 <= 6True

Important: Notice that equality uses == (double equals), not = (single equals). A single equals sign is for assigning a value to a variable. Double equals is for comparing two values. Mixing these up is one of the most common beginner mistakes in Python.

# Correct - assigning a value
age = 20

# Correct - comparing two values
print(age == 20)   # True
print(age == 25)   # False
print(age > 18)    # True
print(age != 20)   # False

3. Logical Operators

Logical operators let you combine multiple conditions together into one statement.

OperatorMeaningReturns True when
andBoth conditions must be truecondition1 AND condition2 are both True
orAt least one condition must be truecondition1 OR condition2 is True
notReverses the resultThe condition is False
age = 20
has_id = True

# and - both must be True
print(age >= 18 and has_id == True)   # True

# or - at least one must be True
print(age < 18 or has_id == True)     # True

# not - reverses the result
print(not has_id)                      # False

4. If Statements

An if statement tells Python: "only run this block of code if a certain condition is True." If the condition is False, Python skips the block entirely.

The syntax looks like this:

if condition:
    # code to run if condition is True

The colon after the condition is required. The code inside the if block must be indented — Python uses indentation (4 spaces or 1 tab) to know which lines belong inside the block. This is different from most other languages that use curly braces.

password = "secret123"

if password == "secret123":
    print("Access granted.")

print("Program continues here regardless.")

Output:

Access granted.
Program continues here regardless.

Now try changing the password to something wrong:

password = "wrongpassword"

if password == "secret123":
    print("Access granted.")

print("Program continues here regardless.")

Output:

Program continues here regardless.

The print inside the if block was skipped completely because the condition was False.


5. elif and else

Usually you need more than just "do this if true." You need alternatives. That is where elif and else come in.

  • elif means "else if" — check this condition only if the previous ones were False
  • else runs if none of the above conditions were True — it is the fallback
score = 72

if score >= 90:
    print("Grade: A")
elif score >= 75:
    print("Grade: B")
elif score >= 60:
    print("Grade: C")
elif score >= 50:
    print("Grade: D")
else:
    print("Grade: F - You need to retake this.")

Output:

Grade: C

Python checks each condition from top to bottom and stops as soon as one is True. The moment it finds a matching condition, it runs that block and skips all the remaining elif and else blocks.

Real world example — a simple login system:

username = "admin"
password = "verxio2026"

if username == "admin" and password == "verxio2026":
    print("Login successful. Welcome, admin.")
elif username == "admin" and password != "verxio2026":
    print("Wrong password. Try again.")
else:
    print("Username not found.")

6. Nested If Statements

You can put an if statement inside another if statement. This is called a nested if. Use it when a second condition only makes sense to check after the first one is already True.

is_logged_in = True
is_admin = False

if is_logged_in:
    print("Welcome back!")
    if is_admin:
        print("Admin panel is accessible.")
    else:
        print("You have standard user access.")
else:
    print("Please log in first.")

Output:

Welcome back!
You have standard user access.

Tip: Do not nest too deeply. If you find yourself writing if inside if inside if inside if, your logic probably needs to be restructured. Two or three levels is usually the maximum before code becomes hard to read.


7. For Loops

A for loop repeats a block of code for each item in a sequence. The sequence can be a list, a string, a range of numbers, or any other collection.

for variable in sequence:
    # code to repeat

A simple example — looping through a list:

tools = ["Nmap", "Wireshark", "Metasploit", "Burp Suite"]

for tool in tools:
    print(tool)

Output:

Nmap
Wireshark
Metasploit
Burp Suite

Looping through a string — Python treats each character as an item:

for letter in "Python":
    print(letter)

Output:

P
y
t
h
o
n

Looping through a list of numbers and doing math:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num * num)

Output:

1
4
9
16
25

8. While Loops

A while loop keeps repeating a block of code as long as a condition is True. Unlike a for loop which iterates over a known sequence, a while loop runs indefinitely until its condition becomes False.

while condition:
    # code to repeat

A simple countdown:

count = 5

while count > 0:
    print(count)
    count = count - 1

print("Blast off!")

Output:

5
4
3
2
1
Blast off!

A real-world example — keep asking for a password until the user gets it right:

correct_password = "python2026"

entered = ""

while entered != correct_password:
    entered = input("Enter the password: ")
    if entered != correct_password:
        print("Incorrect. Try again.")

print("Access granted!")

Warning — infinite loops: If the condition of a while loop never becomes False, the loop runs forever and your program freezes. Always make sure something inside the loop will eventually make the condition False. You can stop a running program with Ctrl + C in the terminal.

# This will loop forever - DO NOT run without a break condition
# while True:
#     print("This never stops")

9. break and continue

Two keywords give you extra control over loops:

  • break — immediately exits the entire loop, no matter what
  • continue — skips the rest of the current iteration and jumps to the next one

break Example

# Stop searching the moment you find what you need
targets = ["192.168.1.1", "192.168.1.2", "192.168.1.5", "192.168.1.10"]

for ip in targets:
    print(f"Scanning {ip}...")
    if ip == "192.168.1.5":
        print("Target found! Stopping scan.")
        break

Output:

Scanning 192.168.1.1...
Scanning 192.168.1.2...
Scanning 192.168.1.5...
Target found! Stopping scan.

continue Example

# Skip even numbers, only print odd ones
for num in range(1, 11):
    if num % 2 == 0:
        continue
    print(num)

Output:

1
3
5
7
9

10. The range() Function

The range() function generates a sequence of numbers, which is extremely useful in for loops when you want to repeat something a specific number of times.

# range(stop) - starts at 0, stops before the given number
for i in range(5):
    print(i)
# Output: 0 1 2 3 4

# range(start, stop) - starts at start, stops before stop
for i in range(1, 6):
    print(i)
# Output: 1 2 3 4 5

# range(start, stop, step) - counts in steps
for i in range(0, 20, 5):
    print(i)
# Output: 0 5 10 15

# Counting backwards
for i in range(10, 0, -1):
    print(i)
# Output: 10 9 8 7 6 5 4 3 2 1

11. Practical Examples

Number Guessing Game

secret = 42
attempts = 0

while True:
    guess = int(input("Guess the number (1-100): "))
    attempts += 1

    if guess < secret:
        print("Too low. Try higher.")
    elif guess > secret:
        print("Too high. Try lower.")
    else:
        print(f"Correct! You got it in {attempts} attempts.")
        break

FizzBuzz (Classic Programming Test)

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

Simple Port Scanner Logic

open_ports = [22, 80, 443]
ports_to_check = range(20, 90)

for port in ports_to_check:
    if port in open_ports:
        print(f"Port {port}: OPEN")
    else:
        print(f"Port {port}: closed")

12. Frequently Asked Questions

What is the difference between a for loop and a while loop?

Use a for loop when you know in advance how many times you want to repeat something, or when you are iterating over a collection. Use a while loop when you want to keep repeating until a certain condition changes — especially when you do not know in advance how many repetitions will be needed.

Can I use break inside a while loop?

Yes. break works in both for loops and while loops. It immediately exits whichever loop it is placed in.

What does pass do?

pass is a placeholder statement that does nothing. It is used when Python requires a statement syntactically but you do not want any code to run yet. For example: if condition: pass. It is useful when you are still planning your code structure.

Why does range(5) give me 0 to 4 and not 1 to 5?

Python is zero-indexed — counting starts at 0. range(5) gives you 0, 1, 2, 3, 4 which is five numbers total. Use range(1, 6) if you want 1 through 5.

What happens if I forget to indent?

Python will throw an IndentationError and refuse to run your code. Indentation is not optional in Python — it defines the structure of your code. Use 4 spaces consistently for every level of indentation.


Conclusion

Control flow is where programming starts to feel powerful. You can now write programs that make decisions with if, elif, and else, repeat actions with for and while loops, and fine-tune that repetition with break and continue.

Every project you will ever build — a password checker, a port scanner, a web scraper, a game — uses everything covered in this post. Make sure you practice each example by typing it out yourself, not just reading it.

In the next part of the Python series, we cover Functions — how to write reusable blocks of code that you can call from anywhere in your program. Functions are what transform a collection of scripts into a real, organized piece of software.

Popular Posts