Lesson 5 of 6 · Python

Making decisions with conditions

A program often needs to choose what happens next. Conditional statements let Python run different blocks depending on whether a condition evaluates to True or False.

The if statement

An if statement runs its indented block only when its condition is true. The condition is usually a comparison, such as marks >= 40. A colon ends the condition line and the following block must be indented.

Indentation is part of Python syntax. Use four spaces consistently. If a line belongs inside the conditional block, it must have the same indentation level as the other statements in that block.

Add alternatives with else and elif

Use else when every case not covered by the if condition should follow one alternative path. Use elif to test another condition before reaching the final else.

Python checks these conditions from top to bottom and runs the first matching block. Put more specific or higher-priority cases first so a broad condition does not hide a case that should be handled separately.

Combine multiple checks

Use and when all conditions must be true and or when any one of them is enough. For example, an account may be active only when the user has verified an email and has not been blocked.

Keep conditions readable. Store a complicated condition in a clearly named Boolean variable when that makes the decision easier to understand.

main.py
marks = int(input("Enter your marks: "))

if marks >= 80:
    print("Grade: A")
elif marks >= 60:
    print("Grade: B")
elif marks >= 40:
    print("Grade: C")
else:
    print("Result: Try again")
access.py
age = int(input("Age: "))
has_id = input("Do you have an ID? yes/no: ")

if age >= 18 and has_id == "yes":
    print("Entry allowed")
else:
    print("Entry not allowed")

Try it yourself

The code examples above are for reference. Copy the relevant example into the editor, press Run, then change it and run it again.

Code Campus
Your turn

Ask for a number and report whether it is positive, negative or zero. Use if, elif and else.

Show a hint
number = int(input("Number: "))
if number > 0:
    print("Positive")
elif number < 0:
    print("Negative")
else:
    print("Zero")

#CodeCampus

Code Campus