Lesson 6 / 1155%

Lesson 6

Conditions

18 min

if, elif, else and indentation to make your program take decisions.

Definition

A condition is a statement that lets a programchoose what it runs depending on an expression that is eitherTrueorFalse. In Python, it is written with the keywordsif,elifandelse, and the code involved is grouped in an indented block.

Making decisions with if

A condition lets you run a block of code only if an expression is true. In Python, you use theifkeyword, followed by a condition, a colon, then anindented block of code (shifted by 4 spaces).

if.py
age = 20

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

print("End of the program")

Only the indented line depends on the condition. The last line, which is not indented, runs in every case. Ifagewere 15, Python would simply skip theifblock and display only “End of the program”.

Diagram: if the condition is true, the block runs; otherwise it is skipped.

Indentation: the golden rule

In many languages, a block is delimited with curly braces. In Python, it’sindentation that plays this role. All the lines of the same block must be shifted by the same number of spaces, and the line that introduces the block must end with a colon.

indentation.py
temperature = 30

if temperature > 25:
    print("It's hot.")           # inside the block
    print("Remember to hydrate.")  # still inside the block
print("Have a nice day!")        # outside the block, runs in every case

else: the alternative

elsedefines what happens when the condition is false. It has no condition of its own: it simply covers “all the other cases”.

if_else.py
age = int(input("How old are you? "))

if age >= 18:
    print("Access granted.")
else:
    print("Access denied.")

elif: several cases

To test several conditions in a row, you useelif(short for “else if”). Python stops as soon as one condition is true, so the order of the tests matters. You can chain as manyelifas you like.

elif.py
grade = float(input("Your grade out of 20: "))

if grade >= 16:
    print("Very good")
elif grade >= 14:
    print("Good")
elif grade >= 10:
    print("Pass")
else:
    print("Insufficient")

Combining conditions

You can useand,orandnotto build richer conditions, as well as theinkeyword to check whether an element is present.

combinations.py
day = "Saturday"
hour = 10

if day in ("Saturday", "Sunday") and hour >= 9:
    print("The store is open.")
else:
    print("The store is closed.")

Nested conditions

A block can itself contain another condition: these are callednested conditions. Each level adds 4 spaces of indentation. Use this technique in moderation: if your code drifts too far to the right, it can often be simplified withandorelif.

nesting.py
age = 20
has_ticket = True

if age >= 18:
    if has_ticket:
        print("Welcome to the concert!")
    else:
        print("You need a ticket.")
else:
    print("Adults only.")

“Truthy” and “falsy” values

In Python, some values are considered false in a condition:0, the empty string"", the empty list,NoneandFalse. Everything else is considered true.

truthy.py
name = input("Your name: ")

if name:
    print(f"Hello {name}")
else:
    print("You didn't type anything.")

The condensed form

When you simply want to choose between two values, Python offers a one-line syntax called a conditional expression. It reads almost like a sentence: “value if the condition is true, otherwise another value”.

condensed.py
age = 20
status = "adult" if age >= 18 else "minor"
print(status)   # adult

Common errors

  • Forgetting the colon: the line of theif, of theelifand of theelsemust end with:.
  • Writing = instead of ==:if age = 18:causes an error; you need to writeif age == 18:.
  • Bad indentation: a block with no indentation, or with irregular indentation, triggers anIndentationError.
  • Wrong order of elif: if you testgrade >= 10beforegrade >= 16, the second case will never be reached.

Good to know

Indentation is not decorative in Python: it defines the blocks of code. Mixing tabs and spaces causes anIndentationError. VS Code uses 4 spaces by default, so don’t change that.

📸 Capture d'écran à ajouter ici
Screenshot: VS Code showing code with an IndentationError underlined in red.

Exercise

Write a program that asks for the user’s age and displays “Child” (under 13), “Teenager” (13 to 17) or “Adult” (18 and over). Add one more case: if the age is negative, display an error message.

Going further

Ask for a number and display whether it is positive, negative or zero, then whether it is even or odd (use the%operator). Then try rewriting the even-or-odd test as a one-line conditional expression.