LearnWave
Learn it. Master it.

Brief Overview of Python

if..else

Choose between paths with if, elif and else.

Normally statements run one after another. Conditional statements let a program choose different paths depending on a condition. Python has three forms:

  • if: runs its block only when the condition is True. For example: if age >= 18: followed by an indented print("Eligible to vote"). The colon (:) marks the end of the condition.
  • if..else: runs one block when the condition is True and the else block when it is False. The book's example subtracts the smaller of two numbers from the larger: if num1 > num2, diff = num1 - num2, else diff = num2 - num1.
  • if..elif..else: checks several conditions in order. If the first is False, the next is checked, and so on; the first True one runs its block and the whole statement ends. If none is True, the else block runs. The number of elif parts depends on how many conditions you need.
  • elif means 'else if', but it must be written as elif: Python has no 'elseif' keyword, despite what one line of the book suggests.

Indentation. Leading whitespace (spaces or tabs) at the start of a line is indentation. Python uses it to mark blocks and nested blocks: statements at the same indentation form one block. The interpreter checks it strictly, and wrong indentation is a syntax error. The book suggests one tab per level; most Python style guides use four spaces, but whichever you choose, be consistent.

Example (new): a program for a cinema could check if age < 12: print('Child ticket'), elif age >= 60: print('Senior ticket'), else: print('Adult ticket'). For age 65 the first test is False, the elif is True, so it prints Senior ticket and skips the else.

Indentation is part of the grammar.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.