Why Program Flow Matters
Most useful programs do not run the exact same steps every time. They make decisions: they react to user choices, they validate data, they handle special cases, and they choose between different actions. In Python, you control these decisions with conditions (expressions that are either true or false) and comparisons (ways to compare values). Together, they let your program follow different paths depending on what is happening.
When you write conditional logic, you are essentially answering questions like: “Is this number bigger than 10?”, “Did the user enter the correct password?”, “Is the list empty?”, or “Is this value inside an allowed range?” Python evaluates these questions to True or False, and then executes the appropriate block of code.
Boolean Values and Truthiness
Python has a built-in boolean type with two values: True and False. A condition is any expression that Python can interpret as a boolean.
Some values are considered “truthy” or “falsy” even if they are not literally True or False. This is useful, but as a beginner you should use it carefully so your code stays readable.
Common falsy values
False0(and0.0)''(empty string)[],{},()(empty collections)None
Everything else is truthy. For example, a non-empty string is truthy, and a non-zero number is truthy.
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
items = []
if items:
print("You have items")
else:
print("No items yet")
count = 3
if count:
print("Count is not zero")In the first if, an empty list behaves like False. In the second, 3 behaves like True.
Comparison Operators
Comparison operators compare two values and produce a boolean result.
==equal to!=not equal to<less than<=less than or equal to>greater than>=greater than or equal to
age = 20
print(age >= 18) # True
print(age == 21) # False
print(age != 0) # TrueComparing numbers
Numeric comparisons are straightforward. They are commonly used for ranges and thresholds.
temperature = 31
if temperature > 30:
print("Hot")
else:
print("Not hot")Comparing strings
Strings can be compared with == and != for exact matches. Comparisons like < and > also work, but they compare alphabetically (lexicographically), which is not what you want in many beginner programs.
command = "start"
if command == "start":
print("Starting...")
if command != "stop":
print("Not stopping")Exact matching is case-sensitive. "Start" is not equal to "start". If you want case-insensitive matching, normalize the text first.
command = "Start"
if command.lower() == "start":
print("Starting...")Comparing different types
In Python, comparing different types can be tricky. For example, "10" (a string) is not equal to 10 (an integer). If you need numeric comparisons, make sure you are working with numbers.
value = "10"
print(value == 10) # False
number = int(value)
print(number == 10) # True
print(number > 5) # TrueThe if Statement
The simplest way to control flow is an if statement. If the condition is true, the indented block runs. If it is false, Python skips that block.
balance = 50
withdraw = 20
if withdraw <= balance:
balance = balance - withdraw
print("Withdrawal approved")
print("New balance:", balance)Notice the indentation. In Python, indentation is not optional: it defines which lines belong to the if block.
Step-by-step: reading the logic
- Python evaluates
withdraw <= balance. - If it is
True, it runs the indented lines. - If it is
False, it skips them and continues after the block.
if / else: Two Paths
Use else when you want a fallback path for when the condition is false.
balance = 50
withdraw = 70
if withdraw <= balance:
balance = balance - withdraw
print("Approved")
else:
print("Declined: not enough funds")This pattern is common for validation: either accept and continue, or reject and handle the problem.
if / elif / else: Multiple Choices
When there are more than two possibilities, use elif (short for “else if”). Python checks conditions from top to bottom and executes the first matching block. After one block runs, the rest are skipped.
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Grade:", grade)Step-by-step: why order matters
Order is important because Python stops at the first true condition. If you accidentally put score >= 60 first, then a score of 82 would match that earlier condition and never reach the score >= 80 check.
Nesting Conditions (and When to Avoid It)
You can put an if inside another if. This is called nesting. It is sometimes necessary, but it can make code harder to read if overused.
is_member = True
cart_total = 120
if cart_total >= 100:
if is_member:
discount = 0.15
else:
discount = 0.05
else:
discount = 0.0
print("Discount:", discount)This works, but you can often make it clearer by combining conditions (covered next) or by using early returns in functions (when you learn functions).
Combining Conditions with and, or, and not
Python provides logical operators to combine multiple comparisons into one condition.
and: true only if both sides are trueor: true if at least one side is truenot: flips true to false and false to true
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
else:
print("Entry denied")day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("Weekend")is_closed = False
if not is_closed:
print("We are open")Short-circuit behavior
and and or use “short-circuiting.” That means Python may not evaluate the right side if the left side already decides the result.
- With
and, if the left side is false, the whole condition is false, so Python skips the right side. - With
or, if the left side is true, the whole condition is true, so Python skips the right side.
This can prevent errors when the right side would be unsafe.
text = ""
# Safe: if text is empty (falsy), Python will not evaluate text[0]
if text and text[0] == "A":
print("Starts with A")
else:
print("Does not start with A (or is empty)")Membership Tests: in and not in
Use in to check whether a value exists inside a collection (like a list, tuple, set) or inside a string.
allowed = ["read", "write", "admin"]
role = "write"
if role in allowed:
print("Role accepted")
else:
print("Unknown role")email = "person@example.com"
if "@" in email:
print("Looks like an email address")not in is the opposite.
banned = ["spammer1", "spammer2"]
username = "new_user"
if username not in banned:
print("Welcome")Identity vs Equality: is vs ==
== checks whether two values are equal. is checks whether two variables refer to the exact same object in memory (identity). Beginners often confuse these.
In most beginner scripts, you should use == for comparisons. Use is mainly when comparing to None.
value = None
if value is None:
print("No value provided")
# Avoid this style:
# if value == None:Writing Clear Conditions
Readable conditions make your program easier to maintain. Here are a few practical guidelines.
Prefer direct boolean checks
is_logged_in = True
# Clear
if is_logged_in:
print("Show dashboard")
# Less clear
if is_logged_in == True:
print("Show dashboard")Use parentheses when it helps readability
Python has operator precedence rules, but you do not need to memorize them all at once. If a condition is complex, add parentheses to show your intent.
age = 17
has_permission = True
is_member = False
if (age >= 18 and is_member) or has_permission:
print("Allowed")Avoid double negatives
is_disabled = False
# Clear
if not is_disabled:
print("Enabled")Practical Step-by-Step Script: Shipping Cost Rules
This example shows how conditions and comparisons can implement real rules. Imagine a small shipping calculator with these rules:
- If the order total is 50 or more, shipping is free.
- Otherwise, shipping is 5.
- But if the destination is international, add 10 extra.
Step 1: Start with the values you want to decide from.
order_total = 42
is_international = TrueStep 2: Decide the base shipping using an if/else.
if order_total >= 50:
shipping = 0
else:
shipping = 5Step 3: Adjust shipping with another condition.
if is_international:
shipping = shipping + 10Step 4: Show the result.
print("Shipping cost:", shipping)Full script:
order_total = 42
is_international = True
if order_total >= 50:
shipping = 0
else:
shipping = 5
if is_international:
shipping = shipping + 10
print("Shipping cost:", shipping)Try changing order_total and is_international to see different paths run.
Practical Step-by-Step Script: Input Validation with Ranges
A very common use of conditions is validating that a number is within an allowed range. For example, suppose a program expects a rating from 1 to 5.
Step 1: Convert the rating to an integer (assuming you already know how to read input and convert types).
rating = int("4")Step 2: Check the range using a combined condition.
if rating >= 1 and rating <= 5:
print("Thanks for rating!")
else:
print("Rating must be between 1 and 5")Python also supports chained comparisons, which can be more readable for ranges.
if 1 <= rating <= 5:
print("Thanks for rating!")Both versions work. Chained comparisons are a nice Python feature for expressing “between” checks.
Common Mistakes and How to Fix Them
Using = instead of ==
= assigns a value. == compares values. Python will raise a syntax error if you try to use = inside an if condition.
# Wrong (will cause an error)
# if x = 3:
# print("x is 3")
# Correct
x = 3
if x == 3:
print("x is 3")Forgetting indentation
Indentation defines the block. If indentation is inconsistent, Python raises an error or your logic will not do what you expect.
x = 10
if x > 5:
print("Greater than 5")
print("Still inside the if")
print("Outside the if")Conditions that are always true
A classic bug is writing if name == "Alice" or "Bob":. This does not do what it looks like. The string "Bob" is truthy, so the condition becomes always true.
name = "Charlie"
# Wrong
# if name == "Alice" or "Bob":
# print("Hello")
# Correct
if name == "Alice" or name == "Bob":
print("Hello")
# Also correct and often cleaner
if name in ["Alice", "Bob"]:
print("Hello")Comparing floats directly
Floating-point numbers can have tiny rounding differences. Direct equality checks can fail unexpectedly.
x = 0.1 + 0.2
print(x) # 0.30000000000000004
print(x == 0.3) # FalseWhen you need to compare floats, compare within a small tolerance.
x = 0.1 + 0.2
if abs(x - 0.3) < 1e-9:
print("Close enough")Choosing Between Many Options
Sometimes you have a lot of possible values and want to handle each one differently. You can use elif chains, but keep them readable.
status = "processing"
if status == "new":
action = "Create record"
elif status == "processing":
action = "Continue work"
elif status == "done":
action = "Archive"
else:
action = "Unknown status"
print(action)For many fixed options, a dictionary can also be a clean approach, but it changes the style from “flow control” to “data-driven mapping.” If you use a dictionary, you still often need an if to handle missing keys safely.
status = "done"
actions = {
"new": "Create record",
"processing": "Continue work",
"done": "Archive"
}
if status in actions:
print(actions[status])
else:
print("Unknown status")Mini Practice Tasks (Write and Test)
Task 1: Password length check
Create a variable password. If its length is less than 8, print “Too short”. Otherwise print “OK”.
password = "abc123"
if len(password) < 8:
print("Too short")
else:
print("OK")Task 2: Detect a valid menu choice
Create a variable choice that should be one of "a", "b", or "q". Print “Valid” if it matches, otherwise print “Invalid”.
choice = "b"
if choice in ["a", "b", "q"]:
print("Valid")
else:
print("Invalid")Task 3: Number classification
Create a variable n. Print “negative” if it is less than 0, “zero” if it is 0, and “positive” if it is greater than 0.
n = -2
if n < 0:
print("negative")
elif n == 0:
print("zero")
else:
print("positive")