Flow of Control
Making decisions with if
Use if and else to choose what a program does.
The order in which a program's statements run is its flow of control. So far, statements have run in sequence: line 1, then line 2, then line 3. Python also offers selection (choosing between paths) and repetition (doing things again).
Selection uses if. The line starts with if, then a condition, and ends with a colon (:). The statements after it form a block, which runs only when the condition is true. A short block can sit on the same line, after the colon; a longer block goes on the following lines, indented. For example, if marks >= 33: print("Pass") prints Pass only when marks is 33 or more.
if..else gives two paths: the if block runs when the condition is true, and the else block runs when it is false. For example, to check whether a number is even or odd:
- num = int(input("Enter a number: "))
- if num % 2 == 0: print("Even")
- else: print("Odd")
Enter 24, and it prints Even; enter 11, and it prints Odd.
Another example always prints the positive difference between two numbers, whichever is bigger: if num1 > num2, the difference is num1 - num2; otherwise it is num2 - num1.
A block can have any number of statements. Its indentation (the spaces at the start of each line) shows which statements belong to it.
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.