if...else Programs
The previous page ended with a program that told the user nothing when two numbers were equal. else closes that gap: it carries no condition of its own, so it catches every case the if did not. Exactly one of the two blocks runs, every single time.
1Program 1 — even or odd
Ask the user for a whole number and say whether it is even or odd.
- one whole number,
num
- divide by 2 and look at the remainder:
num % 2
- “even” or “odd” — one of them, always
# even or odd — every whole number is one or the other
num = int(input('Enter a number: '))
if num % 2 == 0:
print(num, 'is even')
else:
print(num, 'is odd')Enter a number: 46 46 is even
Enter a number: 7 7 is odd
if num % 2 == 0:% is the remainder operator, not a percent sign. 46 % 2 is 0 and 7 % 2 is 1, so 'remainder of zero' is exactly what 'even' means.
else:No condition, and a colon of its own. Whatever the if did not take, this takes — so an odd number needs no test written for it.
= is not ==. if num % 2 = 0: does not run at all. Python reports SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? — it guesses right. One equals sign is an order (“put this in that box”); two is a question (“are these the same?”).2Program 2 — the larger of two numbers, properly
Ask for two numbers and report the larger. This time, say something sensible when they are equal.
# the larger of two numbers — with no gap for equal numbers
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
if a > b:
print(a, 'is larger')
else:
print(b, 'is larger or the two are equal')Enter the first number: 15 Enter the second number: 9 15 is larger
Enter the first number: 12 Enter the second number: 12 12 is larger or the two are equal
else beats two opposite ifs. Two separate tests can both be false, which is how the previous page lost the equal case. An else cannot: it has no condition to be false. And if you later change a > b to a >= b, there is no second test that has to be remembered and changed to match.3Program 3 — pass or fail
The pass mark is 33. Ask for a student's marks and print Pass or Fail.
# pass or fail, at the 33 mark boundary
marks = int(input('Enter the marks out of 100: '))
if marks >= 33:
print('Result: Pass')
else:
print('Result: Fail')Enter the marks out of 100: 33 Result: Pass
Enter the marks out of 100: 32 Result: Fail
The two runs shown are 33 and 32 on purpose. Anybody can get 90 and 10 right; the marks are won and lost at the boundary, and the boundary is where >= and > stop meaning the same thing. “33 is a pass” needs >= 33. With > 33, a student on exactly 33 fails.
4Program 4 — is it a leap year?
A year is a leap year if it divides by 4 — except a century year, which must divide by 400. So 2024 is one, 1900 is not, and 2000 is.
# a leap year is divisible by 4, but a century year must also be divisible by 400
year = int(input('Enter a year: '))
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print(year, 'is a leap year')
else:
print(year, 'is not a leap year')Enter a year: 2024 2024 is a leap year
Enter a year: 1900 1900 is not a leap year
Enter a year: 2000 2000 is a leap year
Read the condition in two halves, the way Python does. year % 4 == 0 must hold — no year that fails that is ever a leap year. Then the bracket: the year is either not a century (year % 100 != 0) or it is a century that divides by 400.
and binds tighter than or, so without them Python would read the condition as “(divides by 4 and is not a century) or divides by 400”. That is a different sentence — though here it is not a different answer: we tested every year from 1 to 10000 and the two agree on all of them, because a year that divides by 400 always divides by 4 as well. The brackets earn their place anyway. They give the line the same shape as the rule you were given, so a reader can check one against the other; and where and and or meet, that is usually not a luxury.5Program 5 — vowel or consonant
Ask for a single letter and say whether it is a vowel or a consonant. Accept capitals too.
# is the letter a vowel or a consonant?
letter = input('Enter one letter: ')
letter = letter.lower()
if letter in 'aeiou':
print(letter, 'is a vowel')
else:
print(letter, 'is a consonant')Enter one letter: E e is a vowel
Enter one letter: k k is a consonant
No int() here — a letter is text and must stay text. letter.lower() hands back a lower-case copy and letter = puts it back in the same box, so one test covers E and e together. That is why the output shows a small e for a typed capital.
letter is '' — and '' in 'aeiou' is True in Python, because an empty string is inside every string. We ran it. A program that must not be fooled by this needs a length check first, which is a job for the three-way ladder on the next page.6The mistake everybody makes: forgetting the third case
Here is a program that looks finished and is not. It has two outcomes, and the problem it was given has three:
# positive or negative — and the case this program gets wrong
num = int(input('Enter a number: '))
if num > 0:
print('Positive')
else:
print('Negative')Enter a number: 0 Negative
else did its job perfectly: it caught everything the if missed, and zero was one of those things. The fault is not in the else, it is in counting the outcomes — positive, negative, zero is three, and three outcomes need elif. That is the next page.7Recap
Never both, never neither. Count the blocks that ran on any run of an if…else and the answer is always 1.
else: on its own line with a colon. Writing else num < 0: is a SyntaxError — that shape is called elif.
>= 33 and > 33 differ on exactly one value. Always test the boundary itself, not just a number either side.
Count them before you write. Positive/negative looks like two and is three, because zero is neither.
- 1
Ask for two numbers and print the smaller one, handling the equal case.
Hint · The same shape as program 2 with
<in place of>. - 2
Ask for a number and say whether it divides exactly by 5.
Hint ·
num % 5 == 0. Both branches print something this time. - 3
Ask for the age and print
AdultorMinor, taking 18 as adult.Hint · Run it with 17, 18 and 19 before you believe it.
- 4
Ask for a word and say whether it is longer than 5 characters.
Hint ·
len(word) > 5— no casting, the word stays text. - 5
Ask for the units used and charge ₹5 per unit up to 100 units, or ₹7 per unit for the whole lot above that.
Hint · Work the amount out inside each branch, then print it once after the
if…else.
How many blocks run when an if...else statement is reached?
A pass/fail program uses if marks > 33. A student scores exactly 33. What is printed?
Why does if num > 0 ... else print 'Negative' get zero wrong?