if Statement Programs
Six programs, each built round a single if. Read the problem, plan it, write it — and only then look at the program printed here. Every output on this page is a real run, so if yours differs, yours is telling you something.
if is for. One outcome. The block runs when the condition is True, and when it is False nothing happens — no error, no message, no stopping. The program simply carries on with the next line at the margin. Half the marks lost on this shape are lost to that half.1Program 1 — is the number positive?
Ask the user for a number. If it is positive, say so. The program should end politely either way.
- one number,
num
- test whether
num > 0
- a message, but only when the test is true
- a closing line, always
# print a message only when the number is positive
num = int(input('Enter a number: '))
if num > 0:
print('That number is positive')
print('Checked')Enter a number: 7 That number is positive Checked
Now the run that matters more — the one where the condition is false:
Enter a number: -4 Checked
num = int(input('Enter a number: '))input() always hands back text, so int() turns '7' into the number 7. Without it, num > 0 would be comparing text with a number and Python would refuse.
if num > 0:The condition. Python works out num > 0 first — with 7 in num that is True, with -4 it is False — and the colon says the indented block below belongs to this line.
print('That number is positive')Indented by four spaces, so it is the if's block. It runs only when the condition was True.
print('Checked')Back at the margin, so it belongs to nobody. It runs on both runs — which is how you can tell the program did not stop when the condition was false.
Checked still printed. If your program seems to do nothing, print something after the if and you will see it is alive.2Program 2 — a discount on bills over ₹500
A shop gives 10% off, but only on bills above ₹500. Ask for the bill amount and print what the customer has to pay.
- the bill amount,
bill
- if
bill > 500, work out 10% and take it off
- the discount, when there was one
- the amount to pay, always
# a 10% discount, but only on bills above 500
bill = float(input('Enter the bill amount: '))
if bill > 500:
discount = bill * 10 / 100
bill = bill - discount
print('Discount given:', discount)
print('Amount to pay:', bill)Enter the bill amount: 800 Discount given: 80.0 Amount to pay: 720.0
Enter the bill amount: 400 Amount to pay: 400.0
Two things are worth noticing. First, the block has three statements in it — a block is not one line, it is every line indented under the header. Second, bill = bill - discount puts the new amount back into the same box, so the last line prints the reduced amount without knowing whether a discount happened.
float() and not int()? Because a bill can be 499.50, and int('499.50') raises a ValueError. Whenever the value could have a decimal point, read it with float().3Program 3 — turn a negative number positive
Ask for a number and print its size, ignoring the minus sign. (−25 and 25 are both a size of 25.)
# turn a negative number into a positive one
num = int(input('Enter a number: '))
if num < 0:
num = -num
print('The size of the number is', num)Enter a number: -25 The size of the number is 25
This is the neatest shape a plain if has: a value is corrected when it needs correcting and left alone otherwise, and the printing happens once, afterwards. A positive number never enters the block, so it reaches the last line untouched.
4Program 4 — does this subject have a practical?
Four subjects have a practical exam. Ask the user for a subject and warn them if theirs is one of them.
# a reminder for the subjects that have a practical exam as well
practical_subjects = ['Computer Science', 'Physics', 'Chemistry', 'Biology']
subject = input('Enter the subject: ')
if subject in practical_subjects:
print('Remember: this subject has a practical exam too')
print('Timetable printed')Enter the subject: Computer Science Remember: this subject has a practical exam too Timetable printed
Enter the subject: History Timetable printed
A condition does not have to be about numbers. in asks is this value somewhere in that list? and answers True or False, which is all an if ever needs. Writing this with four separate comparisons joined by or would work too — and would have to be edited every time the school adds a subject.
in on a list is exact. 'computer science' is not 'Computer Science', and 'Physics ' with a stray space is not 'Physics'. Real programs guard against that with subject.strip().title() before the test.5Program 5 — the scholarship, which needs two things
A scholarship needs at least 75 marks and at least 80% attendance. Ask for both and say whether the student is eligible.
# a scholarship needs good marks AND good attendance
marks = int(input('Enter the marks: '))
attendance = int(input('Enter the attendance percentage: '))
if marks >= 75 and attendance >= 80:
print('Eligible for the scholarship')
print('Application checked')Enter the marks: 82 Enter the attendance percentage: 91 Eligible for the scholarship Application checked
Enter the marks: 82 Enter the attendance percentage: 60 Application checked
and needs both sides to be true, so one short attendance is enough to keep the block shut. Had the rule been “marks or attendance”, or would be the word — and 82 marks alone would have won the scholarship.
marks >= 75 and attendance >= 80 is right; marks >= 75 and >= 80 is a SyntaxError. Each side of an and has to be a complete question, with its own value on the left.6Program 6 — the larger of two numbers, with two ifs
Ask for two numbers and say which is larger. Use only plain if statements.
# the larger of two numbers, using two separate if statements
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
if a > b:
print(a, 'is larger')
if b > a:
print(b, 'is larger')
print('Done')Enter the first number: 15 Enter the second number: 9 15 is larger Done
It works. Two independent ifs, and exactly one of them opens… until the two numbers are the same:
Enter the first number: 12 Enter the second number: 12 Done
ifs leave gaps. Neither 12 > 12 nor 12 > 12 is true, so both blocks are skipped and the user is told nothing. Nothing is broken — the program did exactly what it was asked. This gap is the reason else exists, and it is the next page.7Recap
The block runs, or the program carries on. There is no third possibility and no error either way.
Anything that comes out True or False will do: a comparison, an and/or of two comparisons, or an in test on a list.
Every line indented under the header belongs to it — one line or five. The first line back at the margin does not.
Two ifs can both be false at once. If every case must be covered, you want else, not a second if.
- 1
Ask for a number and print
Evenonly when it is even.Hint · The test is
num % 2 == 0. Nothing is printed for an odd number, and that is correct. - 2
Ask for the temperature and warn the user if it is above 40.
Hint · Read it with
float()— temperatures have decimal points. - 3
Ask for a password and print a warning if it is shorter than 8 characters.
Hint ·
len(password) < 8. Noint()here — the password is meant to stay text. - 4
Ask for three marks and print
Distinctionwhen all three are above 90.Hint · Two
ands in one condition is perfectly normal:a > 90 and b > 90 and c > 90. - 5
Ask for a year and add 1 to a
leap_countvariable if the year divides by 4.Hint · Start the counter before the
if, or the name will not exist when you print it.
A program reads a number and has if num > 100: print('Big'). The user types 40. What happens?
In the discount program, why is print('Amount to pay:', bill) at the margin rather than indented?
Two separate ifs test a > b and b > a. For a = 12 and b = 12 the program prints only 'Done'. Why?