Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

If it rains, take an umbrella

You make small decisions all day: if it is raining, take an umbrella. If it isn't, leave it at home. Code can decide in just the same way.

An if checks a condition, which is a question with a true or false answer. When the answer is true, the lines inside the if run. When it is false, they are skipped. Python marks the inside lines by indenting them. The other languages wrap them in curly brackets.

An if: runs its lines only when the condition is true.
In code
if price >= 500:
    price = price - 50

Else: the other path

Often you want something to happen either way, but a different thing. An online shop gives free delivery above 500 rupees, and charges 40 below that.

Add an else after the if, and you get two paths. The computer checks the condition. If it is true it runs the first path, and if it is false it runs the second. Exactly one of them runs, never both and never neither.

Exactly one path: runs: the if part or the else part.
In code
if total >= 500:
    shipping = 0
else:
    shipping = 40
Free delivery above 500
total: 300
0
shipping: ?
1
line
total
300

The shop checks the condition: is the total at least 500? The total is 300, so the answer is false.

Move 1 of 4