What Are Conditions?
What Are Conditions?
Every day, you make countless decisions based on conditions. If it's raining, you take an umbrella. If you're hungry, you eat. If the traffic light is red, you stop. These simple if-then patterns form the foundation of how we navigate the world—and they're exactly how programs make decisions too.
In Python, conditions allow your code to be intelligent and responsive. Instead of executing the same instructions every single time, your programs can examine the current situation, evaluate what's true, and choose different paths accordingly. This is called conditional logic, and it's one of the most powerful concepts in programming.
Programs That Think
Imagine a simple login system. When someone enters their password, the program needs to decide: is this password correct or not? Based on that answer, it either grants access or denies it. The program isn't just blindly following a single set of instructions—it's evaluating a condition and responding appropriately.
password = "secret123"
user_input = input("Enter password: ")
if user_input == password:
print("Access granted!")
else:
print("Access denied!")
This tiny program demonstrates conditional thinking. The code looks at two values, compares them, and makes a decision. But to understand how this works, we need to explore what makes a condition "true" or "false."
{{VISUAL: diagram: flowchart showing a decision point where user input is compared to stored password, branching to either "Access granted" or "Access denied"}}
Boolean Values: The Language of True and False
At the heart of all conditions are Boolean values—named after mathematician George Boole. In Python, there are only two Boolean values: True and False (notice they're capitalized). These aren't strings or numbers; they're a special data type that represents the answer to yes/no questions.
When you write a condition, Python evaluates it and reduces it to one of these two values:
is_raining = True
is_sunny = False
print(is_raining) # Output: True
print(is_sunny) # Output: False
But most conditions aren't this straightforward. Usually, you're asking Python to compare things and determine whether the comparison is true or false.
Comparison Operators: Asking Questions About Data
Python provides six comparison operators that let you ask questions about values. Each operator compares two values and returns either True or False:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 7 > 4 | True |
< | Less than | 3 < 8 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 4 <= 3 | False |
Let's see these in action:
age = 18
temperature = 72
score = 95
print(age >= 18) # True (18 is equal to 18)
print(temperature > 100) # False (72 is not greater than 100)
print(score == 100) # False (95 does not equal 100)
print(score != 0) # True (95 is not equal to 0)
Notice something crucial: we use == (double equals) for comparison, not = (single equals). This is because = is the assignment operator—it stores a value in a variable. The == operator asks "are these equal?" without changing anything.
x = 10 # Assignment: store 10 in x
x == 10 # Comparison: is x equal to 10? (Returns True)
This distinction trips up many beginners, so keep it in mind!
{{VISUAL: diagram: side-by-side comparison showing "x = 10" labeled as "Assignment (stores value)" versus "x == 10" labeled as "Comparison (tests equality)"}}
Conditions with Different Data Types
Comparison operators work with various data types, not just numbers:
Strings can be compared alphabetically:
print("apple" < "banana") # True (a comes before b)
print("hello" == "Hello") # False (case-sensitive!)
print("Python" != "python") # True (different cases)
Numbers can be integers or floats:
print(3.14 > 3) # True
print(10.0 == 10) # True (Python treats these as equal)
Mixed comparisons between incompatible types will cause errors:
print(5 > "3") # TypeError: '>' not supported between int and str
Building Intuition: Conditions Are Questions
The best way to think about conditions is as questions your program asks. Every condition you write should translate into a clear yes/no question:
temperature > 75→ "Is the temperature greater than 75?"username == "admin"→ "Is the username equal to 'admin'?"balance >= 100→ "Is the balance at least 100?"
When Python evaluates these questions, it gets back True or False. Your program then uses that answer to decide what to do next. In the upcoming pages, you'll learn exactly how to use if, elif, and else statements to build these decision-making pathways into your code.
Practice Check
Before moving forward, try evaluating these conditions in your head:
x = 15
y = 20
x < y # ?
x == 15 # ?
y != 20 # ?
x >= 20 # ?
Understanding conditions is like learning to ask the right questions. Once you master that, you can teach your programs to think critically and respond intelligently to any situation they encounter.
Basic if Logic
Basic if Logic
At the heart of decision-making in Python lies the if statement. Think of it as a gatekeeper that checks whether something is true before allowing code to run. Just like you might check if it's raining before deciding to take an umbrella, your program can check conditions before executing certain code blocks.
The Anatomy of an if Statement
An if statement in Python follows a simple structure:
if condition:
# Code to execute if condition is True
print("The condition was met!")
Let's break down each component:
ifkeyword: Signals the start of a conditional check- condition: An expression that evaluates to either
TrueorFalse - colon (
:): Marks the end of the condition line (required!) - indented block: The code that runs only when the condition is
True
Critical Rule: Python uses indentation (typically 4 spaces) to define code blocks. Everything indented beneath the if statement belongs to that conditional block.
{{VISUAL: diagram: anatomy of an if statement showing the keyword, condition, colon, and indented code block with labels}}
Your First if Statement
Let's start with a simple example:
temperature = 30
if temperature > 25:
print("It's a hot day!")
print("Remember to stay hydrated.")
Output:
It's a hot day!
Remember to stay hydrated.
Here's what happens step-by-step:
- Python evaluates the condition:
temperature > 25 - Since 30 is greater than 25, the condition is
True - Python executes all indented lines below the
ifstatement - Both print statements run
Now, what if we change the temperature?
temperature = 20
if temperature > 25:
print("It's a hot day!")
print("Remember to stay hydrated.")
print("This line always runs!")
Output:
This line always runs!
Notice that the two indented print statements didn't run because the condition was False (20 is not greater than 25). However, the final print statement—which is not indented—runs regardless because it's not part of the if block.
Comparison Operators: The Building Blocks
To write meaningful conditions, you need comparison operators. These operators compare values and return either True or False:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 7 > 4 | True |
< | Less than | 3 < 8 | True |
>= | Greater than or equal | 5 >= 5 | True |
<= | Less than or equal | 4 <= 3 | False |
Important: Notice the double equals (==) for comparison versus single equals (=) for assignment. This is a common source of bugs!
# Assignment (storing a value)
age = 18
# Comparison (checking a value)
if age == 18:
print("You just became an adult!")
Practical Examples
Example 1: Access Control
user_age = 17
if user_age >= 18:
print("Access granted. Welcome!")
print("You may proceed to the content.")
Since user_age is 17, which is less than 18, nothing prints. The condition is False, so the code block is skipped entirely.
Example 2: Positive Number Checker
number = 42
if number > 0:
print(f"{number} is a positive number")
result = number * 2
print(f"Double that number is {result}")
Output:
42 is a positive number
Double that number is 84
{{VISUAL: diagram: flowchart showing if statement decision path with True branch executing code block and False branch skipping it}}
Example 3: String Comparison
Conditions work with strings too:
password = "python123"
if password == "python123":
print("Password correct!")
print("Login successful")
Output:
Password correct!
Login successful
Understanding Boolean Values
Every condition ultimately evaluates to a boolean value—either True or False. You can even check boolean values directly:
is_raining = True
if is_raining:
print("Take an umbrella")
When the condition itself is a boolean variable, you don't need comparison operators. Python simply checks if the value is True.
Common Beginner Mistakes
1. Forgetting the colon
# Wrong ❌
if temperature > 25
print("Hot!")
# Correct ✓
if temperature > 25:
print("Hot!")
2. Incorrect indentation
# Wrong ❌
if temperature > 25:
print("Hot!") # Not indented!
# Correct ✓
if temperature > 25:
print("Hot!") # Properly indented
3. Using = instead of ==
# Wrong ❌
if age = 18: # This is assignment, not comparison!
# Correct ✓
if age == 18:
print("Just turned 18!")
Building Your Intuition
Think of an if statement as a question your program asks itself: "Is this condition true?" If the answer is yes, the program takes action. If the answer is no, it simply moves on to the next line of code outside the indented block.
This simple mechanism is incredibly powerful. With just the basic if statement, you can already create programs that respond differently based on user input, sensor data, time of day, or any other condition you can imagine. In the next section, we'll expand on this foundation by learning how to handle multiple possible outcomes with elif and else.
if and else
if and else: Handling Both Paths
In real life, decisions rarely have just one outcome. When you check the weather before leaving home, you don't only plan for rain—you also decide what to do if it's not raining. Programming works the same way. The else statement pairs with if to handle the alternative path when your condition is false.
The Basic if-else Pattern
While a standalone if statement lets you execute code when a condition is true, adding else gives you complete control over both possibilities:
temperature = 15
if temperature > 20:
print("It's warm outside!")
else:
print("It's cool outside!")
Output: It's cool outside!
Here's what happens: Python evaluates the condition temperature > 20. Since 15 is not greater than 20, the condition is false. Python skips the first block entirely and executes the code inside the else block instead.
{{VISUAL: diagram: flowchart showing if-else decision split with condition diamond branching to two rectangular code blocks}}
Why else Matters
Without else, you'd need two separate if statements to cover both scenarios:
# Without else (redundant and error-prone)
age = 16
if age >= 18:
print("You can vote")
if age < 18:
print("You cannot vote yet")
This works, but it's inefficient. Python checks both conditions even though only one can be true. More importantly, if you later change the first condition, you must remember to update the second one too—a common source of bugs.
The if-else structure is cleaner and more logical:
# With else (clear and efficient)
age = 16
if age >= 18:
print("You can vote")
else:
print("You cannot vote yet")
Python evaluates the condition once. If true, run the first block. If false, run the second block. Simple, readable, and foolproof.
Indentation: The Rules Still Apply
Just like with if, everything inside an else block must be indented. Python uses this indentation to know which lines belong to the else:
score = 45
if score >= 50:
print("Pass!")
print("Well done!")
else:
print("Fail")
print("Keep studying!")
Both print statements under else will execute when the score is below 50. The indentation creates a clear visual boundary showing which code belongs to which branch.
Practical Examples
Example 1: Password Checker
password = input("Enter password: ")
if password == "secret123":
print("Access granted")
print("Welcome back!")
else:
print("Access denied")
print("Invalid password")
This simple security check grants or denies access based on password correctness.
Example 2: Even or Odd
