Python Conditions and if Statements
Python allows you to make decisions in your program by comparing values using conditional operators. These operators come from basic mathematics and logic.
Common Comparison Operators
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal to |
| < | Less than |
| <= | Less than or equal to |
| > | Greater than |
| >= | Greater than or equal to |
These operators are mainly used with if statements, loops, and logical expressions to control program flow.
The if Statement in Python
An if statement executes a block of code only when a specified condition evaluates to True.
Basic Syntax
if condition:
# code runs if condition is True
Example: Comparing Two Values
In this example, the condition x > y is true, so Python prints the message.
How if Statements Work
Python evaluates the condition inside the if statement.
The condition must result in either True or False.
If the result is True, the indented code block runs.
If the result is False, Python skips that block.
Example: Checking Even or Odd
Importance of Indentation in Python
Python uses indentation to define blocks of code. Unlike many languages, Python does not use {} braces.
Incorrect Indentation (Error)
Correct Indentation
Multiple Statements Inside an if Block
You can place more than one statement inside an if condition. All statements must have the same indentation level.
Example
Using Variables Directly in Conditions
Boolean variables (True or False) can be used directly in if statements without comparisons.