Python Docs

If - Else

What Is an if Statement?

An if statement allows your program to make decisions.

It checks a condition and runs code only if the condition is true.

Basic Structure :

if condition


#code to run if condition is true

Example

age = 18
if age >= 18:
    print("You are an adult.")

Output:

You are an adult.

if…else Statement
Use else when you want code to run if the condition is false.

Example

age = 15
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Output:

You are a minor.

elif (Else If)
Use elif when you nedd to check multiple conditions.

Example

temperature = 25
if temperature > 30:
    print("It's hot!")
elif temperature > 20:
    print("Nice weather.")
else:
    print("It's cold.")

Output:

Nice weather.