Python If/Else for Beginners
Imagine your code is a spacecraft. At every fork in the mission plan your program must decide: burn engines, hold orbit, or abort. In Python those steering decisions are made with if, elif, and else. This article guides beginners through these conditional statements with simple analogies, clear examples, and tiny exercises so you can steer your own Python missions.
What is an if statement?
An if statement lets a program take action only when a condition is true.
fuel_percent = 75
if fuel_percent > 50:
print("Proceed to orbit insertion burn.")
If fuel_percent > 50 is True, the indented block runs. If it's False, Python skips the block entirely.
else — the fallback plan
Use else to run code when the if condition is false.
fuel_percent = 30
if fuel_percent > 50:
print("Proceed to orbit insertion burn.")
else:
print("Abort burn — return to safe orbit.")
Think of it this way: if is mission go; else is the contingency plan.
elif — multiple checkpoints
elif (short for "else if") handles more than two options.
fuel_percent = 50
if fuel_percent > 50:
print("Full burn permitted.")
elif fuel_percent == 50:
print("Proceed with caution — marginal fuel.")
else:
print("Abort burn — not enough fuel.")
Python checks conditions top to bottom and executes the first true branch. Once a branch runs, the rest are ignored.
Common condition types
Here's what you'll use most often when writing conditions:
- Comparisons:
==,!=,<,>,<=,>= - Logical operators:
and,or,not - Membership:
in,not in - Truthiness: values like
0,"",[],None,Falseare treated asFalsein conditions
Example combining checks:
temperature_c = -120
communications_online = True
if temperature_c > -100 and communications_online:
print("Proceed to surface operations.")
else:
print("Delay operations until conditions improve.")
Truthiness quick guide
You don't always need a comparison. Python evaluates the value directly:
payloads_ready = [] # empty list is falsy
if payloads_ready:
print("Start deployment.")
else:
print("No payloads — skip deployment.")
Empty lists, empty strings, zero, and None all evaluate to False. Pretty much everything else is True.
Nesting: decisions within decisions
You can nest if blocks, but keep them readable.
fuel_percent = 65
system_check_passed = False
if fuel_percent > 50:
if system_check_passed:
print("Launch!")
else:
print("Hold: system checks failed.")
else:
print("Abort: insufficient fuel.")
If nesting gets deep, consider combining conditions or extracting logic into functions.
Chained comparisons
Python supports expressions like a < b < c, which are evaluated sensibly:
altitude = 1200
if 1000 < altitude < 2000:
print("Within safe corridor.")
This reads naturally and saves you from writing altitude > 1000 and altitude < 2000.
Common beginner mistakes (and how to avoid them)
Wrong indentation: Python needs consistent indentation (4 spaces recommended). If your code isn't running as expected, check your spacing first.
Using = instead of ==: Single = assigns a value, double == compares. This one bites everyone at least once.
Overly complex conditions: Break them into named boolean variables for clarity.
safe_fuel = fuel >= 60
good_weather = wind_speed < 20
if safe_fuel and good_weather:
launch = True
Relying on floating-point equality: Avoid == with floats; use ranges or abs(a - b) < epsilon instead.
Debugging tip: print conditions
If a branch isn't executing, print the values you're testing:
print("fuel:", fuel_percent, "system:", system_check_passed)
Or use assertions in development:
assert isinstance(fuel_percent, (int, float)), "fuel must be numeric"
Short, practical example — simple mission planner
def launch_decision(fuel, weather, comms):
if fuel < 40:
return "Abort: low fuel"
elif not comms:
return "Abort: communications offline"
elif weather == "storm":
return "Delay: bad weather"
else:
return "Go for launch"
print(launch_decision(80, "clear", True)) # -> Go for launch
Exercises (try these)
1. Fuel check: Write an if/else that prints "Go" if fuel >= 75, otherwise "Refuel".
2. Docking checklist: Given dock_ready (bool) and crew_onboard (int), print "Dock" only if both dock_ready is True and crew_onboard >= 3.
3. Temperature gauge: Print "Too cold", "Optimal", or "Too hot" based on temperature ranges: < -100, -100..50, > 50.
Summary
Conditional statements are how your programs make decisions. Start with simple if/else blocks, add elif when you need more branches, and keep your conditions readable. Once you're comfortable with these basics, you'll be ready to handle more complex mission logic in your Python projects.