How to Use If Else in Python: Simple Guide with Examples
In Python, use
if to check a condition and run code only if it's true. Use else to run code when the condition is false. This helps your program make decisions and choose different actions.Syntax
The if else statement lets your program choose between two paths based on a condition.
- if: checks a condition; if true, runs the indented code below.
- else: runs if the
ifcondition is false.
python
if condition: # code runs if condition is True else: # code runs if condition is False
Example
This example checks if a number is positive or not and prints a message accordingly.
python
number = 5 if number > 0: print("The number is positive.") else: print("The number is zero or negative.")
Output
The number is positive.
Common Pitfalls
Common mistakes include forgetting the colon : after if or else, or not indenting the code inside the blocks properly. Also, using else without an if above causes errors.
python
wrong: if number > 0 print("Positive") else print("Not positive") correct: if number > 0: print("Positive") else: print("Not positive")
Quick Reference
Remember these tips when using if else in Python:
- Always end
ifandelselines with a colon:. - Indent the code inside
ifandelseblocks by 4 spaces. elseruns only if theifcondition is false.- Use
eliffor multiple conditions (not covered here).
Key Takeaways
Use
if to run code when a condition is true and else when it is false.Always put a colon
: after if and else lines.Indent the code inside
if and else blocks consistently.For multiple choices, use
elif (else if) statements.Avoid syntax errors by checking colons and indentation carefully.