Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 8 of 25

Conditions: if, elif, else

An if statement runs a block of code only when a condition is True. The line ends with a colon, and the block below is indented by 4 spaces.

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

else runs when the condition is false. To check several conditions in turn, use elif (short for "else if"). Python checks from the top and runs only the first block whose condition is true.

if marks >= 90:
    print("A")
elif marks >= 60:
    print("B")
else:
    print("C")
  • Every if, elif and else line ends with :.
  • The indented lines belong to that branch.
  • Use == to compare, never =.
  • Combine conditions with and and or.

Key takeaways

  • Every if, elif and else line ends with a colon, and the indented lines below it belong to that branch.
  • Only the first branch whose condition is true runs.
  • Use == to compare and = to store.
  • Combine conditions with and and or. Python also allows chained comparisons such as 60 <= m < 80.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.