🐍 If else

conditions

Good to know

⭐️ All non-zero numbers, non-empty strings, lists, dicts, etc. evaluate as True.


Basic If Statement

Runs only if the condition is True.

age = 20
 
if age >= 18:
    print("Adult")

If / Else

Two possible branches.

age = 15
 
if age >= 18:
    print("Adult")
else:
    print("Minor")

If / Elif / Else

Check multiple exclusive conditions.

temp = 25
 
if temp > 30:
    print("Hot")
elif temp > 20:
    print("Warm")
elif temp > 10:
    print("Cool")
else:
    print("Cold")

Nested If Statements

Useful but can become messy — prefer combining conditions when possible.

user = "Admin"
logged_in = True
 
if logged_in:
    if user == "Admin":
        print("Welcome Admin!")

Combining Conditions (and / or / not)

Use logical operators to make cleaner conditions.

age = 22
has_ticket = True
 
if age >= 18 and has_ticket: # Also possible: or / not
    print("Entry allowed")

If in

List

if "cat" in ["dog", "cat", "mouse"]:
    print("Found the cat!")

Strings

if "he" in "hello":
    print("Substring found!")

Dict keys

person = {"name": "Alain", "age": 30}
 
if "name" in person:
    print("Key exists")

Dict values

Unless you ask explicitly:

if "Alain" in person.values():
    print("Value exists")

Opposite: not in

if "banana" not in ["apple", "cherry"]:
    print("Banana missing")

Truthy and Falsy Values

Python evaluates these as False:

# 0  
# "" (empty string)
# [], {}, () (empty containers)
# None
 
name = ""
 
if not name:
    print("Name is missing")

Ternary Expression (Short If-Else)

Good for small inline choices.

age = 17
status = "Adult" if age >= 18 else "Minor"
print(status)