If Statements
Making Decisions with If Statements
If statements allow your program to make decisions based on conditions. They enable your code to execute different blocks of code depending on whether certain conditions are true or false.
Python's if statements are straightforward and readable. The basic structure uses if, optionally followed by elif (else if) for additional conditions, and else for a default case.
Basic If Statement
The simplest form checks a single condition and executes code only if that condition is true:
If-Elif-Else Structure
You can chain multiple conditions using elif (short for "else if"). Python evaluates conditions from top to bottom and executes only the first block where the condition is true:
Nested If Statements
You can nest if statements inside other if statements to create more complex decision trees:
Comparison Operators
Comparison operators allow you to compare values and return boolean results (True or False):
==Equal to - checks if two values are the same!=Not equal to - checks if two values are different>Greater than - checks if left value is larger<Less than - checks if left value is smaller>=Greater than or equal to<=Less than or equal to
Truthiness in Python
Python has a concept of "truthiness" - values that evaluate to True or False in a boolean context. Understanding this helps you write cleaner conditionals:
💡 Truthy Values
Values that evaluate to True: non-zero numbers, non-empty strings/lists/dicts, True
💡 Falsy Values
Values that evaluate to False: 0, 0.0, "", [], {}, None, False
Common Patterns
Here are some practical patterns you'll use frequently: