Python for Beginners: Learn to Code from Zero · Lesson 4 of 10

Lesson 4: Making Decisions with if, elif and else

Let your program choose what to do. Learn if, elif and else, and why indentation matters in Python.

Lesson 4: Making Decisions with if, elif and else

So far every line has run, one after another. Real programs make choices. The if statement runs some code only when a condition is true.

marks = 55
if marks >= 40:
    print("You passed")

Output:

You passed

Indentation is part of the language

The lines inside the if are pushed in by four spaces (indented). That is how Python knows which lines belong to the decision. The line with if ends with a colon :.

else and elif

marks = 35
if marks >= 40:
    print("Pass")
else:
    print("Fail")

Output:

Fail

For more than two outcomes use elif (short for "else if"). Python checks from the top and stops at the first true condition.

marks = 83
if marks >= 80:
    grade = "Distinction"
elif marks >= 60:
    grade = "First division"
elif marks >= 40:
    grade = "Pass"
else:
    grade = "Fail"
print(grade)

Output:

Distinction

Combining conditions in an if

age = 17
has_citizenship = True
if age >= 18 and has_citizenship:
    print("You can vote")
else:
    print("Not yet")

Output:

Not yet

Common mistakes

  • Forgetting the colon : at the end of the if line.
  • Using = instead of == to compare.
  • Mixing tabs and spaces. Use four spaces everywhere.

Try it yourself

  1. Write a program that prints "even" or "odd" for a number.
  2. Add a grade to the marks program for 90 and above.
  3. Ask for a person's age and print whether they are a child (under 13), a teenager (13 to 19) or an adult.

Next lesson: repeating work with loops.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 4: Making Decisions with if, elif and else | MeroSir