Conditional Statements

45 min read Flow of Control

This is a free course. Log in to run the code exercises and track your progress.

Conditional Statements

Statements normally run in sequence. A conditional statement chooses which block runs. Python has if, if-else and if-elif-else; a block is marked by its indentation.

n = int(input())
if n < 0:
    n = -n          # absolute value without abs()
print(n)

A classic program sorts three numbers using only comparisons. Each swap puts a smaller value in front:

a, b, c = 30, 10, 20
if a > b:
    a, b = b, a
if b > c:
    b, c = c, b
if a > b:
    a, b = b, a
print(a, b, c)   # 10 20 30

After the first two comparisons the largest value has moved to c; the third comparison puts the remaining two in order. Draw the flowchart: each if is one diamond.

Python exercise

Read three integers from one line and print them in ascending order, using only if statements (no sort(), sorted(), min() or max()).

a, b, c = map(int, input().split())
if a > b:
    a, b = b, a
# two more comparisons are needed
print(a, b, c)

Log in to edit and run this code.