计算机科学 · 第 1 册 · 1–9 年级

Primary & Middle School Computer Science

本书暂未推出简体中文版。现有版本:English。

Primary & Middle School Computer Science · 1–9 年级

17Decisions: if and else

At the cinema, a ticket costs 5 euros for a child under 12, 6 euros from the age of 65 and 9 euros for everyone else. The ticket machine asks only one question, “How old are you?”, and then decides which price to print. It does not run the same instructions for everybody: it chooses. In this chapter, our programs learn to choose.

You already know

A condition is a question whose answer is yes or no, and an algorithm can do one thing or another depending on it (Chapter 10). input reads a typed answer as text, and int converts it into a whole number (Chapter 15). A for loop repeats an indented block (Chapter 16).

17.1 Comparisons give true or false

Definition 17.1 (Comparison and Boolean value)

A comparison asks how two values compare, with one of the signs == (equal), != (not equal), <, <=, > and >=. Its result is a Boolean value: True or False, the only two values of the type bool.

print(3 < 5)
print(3 > 5)
print(7 == 7)
print(7 != 7)
print(10 <= 9)
print("cat" == "Cat")
Listing 17.1. Six comparisons. code/grade-6/04-if-else/listings/compare.py
$ python compare.py
True
False
True
False
False
False
Output 17.1. Capital and small letters are different, so "cat" is not equal to "Cat".

Be careful with the two signs: one = puts a value in a variable, two == ask whether two values are equal. Writing one instead of two in a question is a common mistake, and Python refuses it:

$ python assign_vs_equal.py
  File "~/session/assign_vs_equal.py", line 2
    if x = 3:
       ^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
[exit status 1]
Output 17.2. if x = 3: is not a question. Python even suggests the fix.

17.2 if and else

Definition 17.2 (Conditional statement and branch)

A conditional statement, or if statement, runs a block only when a condition is true: if condition: followed by an indented block. It may have an else: followed by a second block, run when the condition is false. Each block is a branch: on each run, at most one branch is taken, and exactly one when there is an else.

n = int(input("A whole number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")
print("Thank you!")
Listing 17.2. Even or odd? code/grade-6/04-if-else/listings/even_odd.py
$ python even_odd.py
A whole number: 17
17 is odd
Thank you!
Output 17.3. 17 divided by 2 leaves 1, so the else branch ran; line 6 runs in every case.

As for the for loop, the line before a block ends with a colon, and the block is indented. Line 6 is not indented: it is after the if statement and runs whichever branch was taken.

An if statement is a fork: the condition sends the program into one of the two blocks, and both roads meet again after them.
An if statement is a fork: the condition sends the program into one of the two blocks, and both roads meet again after them.

17.3 elif: more than two cases

The cinema has three prices. Between if and else, any number of elif parts (short for “else if”) can be added, each with its own condition. Python checks the conditions in order, from top to bottom, and runs the block of the first one that is true; it skips all the others. The else block runs only if no condition was true.

age = int(input("Age: "))
if age < 12:
    price = 5
elif age < 65:
    price = 9
else:
    price = 6
print(f"Ticket: {price} euros")
Listing 17.3. The ticket machine. code/grade-6/04-if-else/listings/ticket.py
$ python ticket.py
Age: 70
Ticket: 6 euros
Output 17.4. 70 is not less than 12, nor less than 65: the else branch.
The elif chain is a ladder of questions, asked from the top. The first “yes” gives the answer, and the questions below it are not asked.
The elif chain is a ladder of questions, asked from the top. The first “yes” gives the answer, and the questions below it are not asked.

Because the first true condition wins, the order of the cases matters. Here the two questions are swapped: every child is also under 65, so the second branch can never be reached.

for age in [8, 30, 70]:
    if age < 65:
        price = 9
    elif age < 12:
        price = 5        # this line can never run
    else:
        price = 6
    print(age, price)
Listing 17.4. The cases in the wrong order. code/grade-6/04-if-else/listings/wrong_order.py
$ python wrong_order.py
8 9
30 9
70 6
Output 17.5. The child of 8 pays the adult price.

17.4 and, or, not

Definition 17.3 (Compound condition)

A compound condition joins conditions with and, or and not. a and b is true when both are true; a or b is true when at least one of them is true; not a is true when a is false.

The program below prints, for each of the four ways to choose a and b, the values of a and b and of a or b.

for a in [False, True]:
    for b in [False, True]:
        print(a, b, a and b, a or b)
Listing 17.5. The four cases. code/grade-6/04-if-else/listings/truth.py
$ python truth.py
False False False False
False True False True
True False False True
True True True True
Output 17.6. Columns: a, b, a and b, a or b.
The four cases (T for True, F for False). and needs both; or needs at least one.
The four cases (T for True, F for False). and needs both; or needs at least one.

A real rule that needs them is the rule of leap years: a year has a 29th of February if it is divisible by 4, except the years that end a century, which are leap years only when divisible by 400.

year = int(input("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")
Listing 17.6. Leap year or not? code/grade-6/04-if-else/listings/leap.py
$ python leap.py
Year: 1900
1900 is not a leap year
Output 17.7. 1900 is divisible by 4, but it ends a century and is not divisible by 400.

The brackets matter: Python works out and before or, like ×\times before ++, so without them the condition would mean something else.

17.5 Testing every branch

A program with branches can be right for one input and wrong for another. To test it, we choose inputs that reach every branch, and we try the boundaries: the values where the answer changes. For the cinema, they are 12 and 65, and the ages just before them.

# The ages on each side of the two boundaries, 12 and 65.
for age in [11, 12, 64, 65]:
    if age < 12:
        price = 5
    elif age < 65:
        price = 9
    else:
        price = 6
    print(age, price)
Listing 17.7. Both sides of each boundary. code/grade-6/04-if-else/listings/boundaries.py
$ python boundaries.py
11 5
12 9
64 9
65 6
Output 17.8. At 12 the child price stops; at 65 the senior price starts.
The price bands. The red dots are the four ages tried above, on both sides of each boundary. Age 12 is in the middle band: age < 12 is false for it.
The price bands. The red dots are the four ages tried above, on both sides of each boundary. Age 12 is in the middle band: age < 12 is false for it.

With a loop, the whole rule can be checked at once:

# Every age from 0 to 80, by fives: each branch of the ticket rule is reached.
for age in range(0, 81, 5):
    if age < 12:
        price = 5
    elif age < 65:
        price = 9
    else:
        price = 6
    print(age, price)
Listing 17.8. Ages 0 to 80, by fives. code/grade-6/04-if-else/listings/all_prices.py
$ python all_prices.py
0 5
5 5
10 5
15 9
55 9
60 9
65 6
70 6
75 6
80 6
Output 17.9. Each of the three branches is reached. Some lines are left out.

17.6 Exercises

Exercise 17.1 ★

What do print(3 < 5) and print(4 == 4.0) print?

Solution

Solution of Exercise 17.1.

True and True: the whole number 4 and the decimal number 4.0 are equal, even though their types differ.

Exercise 17.2 ★

Which line does this program print?

x = 7
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")
Listing 17.9. Which branch? code/grade-6/04-if-else/exercises/which.py
Solution

Solution of Exercise 17.2.

medium: 7 is not more than 10, so the first condition is false; it is more than 5, so the elif branch runs, and the else is skipped.

Exercise 17.3 ★

With a = True and b = False, what is not (a and b)? And not a or b?

Solution

Solution of Exercise 17.3.

a and b is False, so not (a and b) is True. not a is False and b is False, so not a or b is False: not applies only to a.

Exercise 17.4 ★

Write a program that asks for a number and prints positive or zero or negative.

Solution

Solution of Exercise 17.4.

n = float(input("A number: "))
if n >= 0:
    print("positive or zero")
else:
    print("negative")
Positive or negative. code/grade-6/04-if-else/exercises/sign.py

Zero goes to the first branch because the comparison is >=.

Exercise 17.5 ★★

Lina wants to give x the value 3. Her program is x = 1, then x == 3, then print(x), one per line. It prints 1, with no error message. What does her second line do? Fix it.

Solution

Solution of Exercise 17.5.

x == 3 is a comparison, a question: it computes False, since x is 1, and the answer is thrown away. Nothing changes x, and nothing is wrong in the language, so there is no error message. To give x the value 3, the line must be an assignment, with one =: x = 3. It is the mirror of the slip of Output 17.2, where one = stood where == was needed.

Exercise 17.6 ★★

This program never prints senior, whatever the age. Why? Fix it.

age = 70
if age > 12:
    print("adult")
elif age > 65:
    print("senior")
else:
    print("child")
Listing 17.10. Where is the senior? code/grade-6/04-if-else/exercises/senior_bug.py
Solution

Solution of Exercise 17.6.

Anyone older than 65 is also older than 12, so the first condition is already true and the elif is never checked. The narrower case must come first:

age = 70
if age > 65:
    print("senior")
elif age > 12:
    print("adult")
else:
    print("child")
The senior case first. code/grade-6/04-if-else/exercises/senior.py

Exercise 17.7 ★★

Write a program that asks for three numbers and prints the largest.

Solution

Solution of Exercise 17.7.

The program keeps the largest number seen so far in a variable and compares each new number with it.

a = float(input("First: "))
b = float(input("Second: "))
c = float(input("Third: "))
largest = a
if b > largest:
    largest = b
if c > largest:
    largest = c
print("The largest is", largest)
The largest of three. code/grade-6/04-if-else/exercises/largest.py

For 4, 9 and 2 it prints 9.0. It should be tested with the largest number in each of the three places, and with two equal numbers.

Exercise 17.8 ★★

Write a program that turns a mark out of 20 into a letter: A from 16, B from 12, C from 8, D below 8.

Solution

Solution of Exercise 17.8.

The highest band is tested first, so each elif only sees the marks below the bands above it.

mark = float(input("Mark out of 20: "))
if mark >= 16:
    letter = "A"
elif mark >= 12:
    letter = "B"
elif mark >= 8:
    letter = "C"
else:
    letter = "D"
print("Grade:", letter)
A grade letter. code/grade-6/04-if-else/exercises/grade.py

Exercise 17.9 ★★

Give a list of temperatures that reaches every branch of this program, with the boundaries.

t = int(input("Temperature: "))
if t < 0:
    print("ice")
elif t < 20:
    print("cool")
elif t <= 30:
    print("warm")
else:
    print("hot")
Listing 17.11. Four branches. code/grade-6/04-if-else/exercises/reach.py
Solution

Solution of Exercise 17.9.

One value inside each band and the values on both sides of each boundary: −5-5 (ice), −1-1 and 00 (ice, then cool), 1919 and 2020 (cool, then warm), 3030 and 3131 (warm, then hot). The boundary 30 belongs to warm because the test is <=.

Exercise 17.10 ★★★

A password should have at least 12 characters, and len(password) gives the number of characters of a text. Write a program that asks for a password and says whether it is long enough, and if not, how many characters are missing.

Solution

Solution of Exercise 17.10.

password = input("New password: ")
if len(password) >= 12:
    print("Long enough.")
else:
    print("Too short:", 12 - len(password), "more characters needed.")
A password-length check. code/grade-6/04-if-else/exercises/password.py

For abc it says that 9 more characters are needed. It should be tested with 11, 12 and 13 characters.

Exercise 17.11 ★★★

The program below decides “yes” or “no” in two ways: with an if inside an if, and with and. Do the two always agree? Check it on all four cases, by hand and by running it.

for a in [False, True]:
    for b in [False, True]:
        if a:
            if b:
                first = "yes"
            else:
                first = "no"
        else:
            first = "no"
        if a and b:
            second = "yes"
        else:
            second = "no"
        print(a, b, first, second)
Listing 17.12. Two ways to decide. code/grade-6/04-if-else/exercises/nested_vs_and.py
Solution

Solution of Exercise 17.11.

They always agree. If a is false, the first way goes to the outer else (no), and a and b is false (no). If a is true, the first way answers as b decides, and a and b is true exactly when b is. The program prints yes yes only for True True, and no no in the three other cases.

Exercise 17.12 ★★★

Tom’s leap-year program says that 1900 is a leap year. Find the mistake, fix it, and give a year that shows the fix is right.

year = int(input("Year: "))
if year % 4 == 0:
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")
Listing 17.13. Wrong for 1900. code/grade-6/04-if-else/exercises/leap_bug.py
Solution

Solution of Exercise 17.12.

The program tests only “divisible by 4” and forgets the exception for the centuries. The fix is the condition of Listing 17.6: year % 4 == 0 and (year % 100 != 0 or year % 400 == 0). The year 1900 shows the fix: the old program says leap year, the new one says not. The year 2000 must also be tried, to check that the exception of the exception still works: it is a leap year.

17.7 Problem: The Calendar’s Leap Years

Problem 17.1

Weekend problem — 97 leap years

The Earth goes round the Sun in a little less than 365 days and a quarter. A calendar must give each year a whole number of days, and the leap years add a day from time to time so that the seasons stay in the same months. Introduced in 1582, the rule of Listing 17.6 is now used by most of the world.

Part I — By hand.

  1. Is 2024 a leap year? Is 2023?
  2. Is 2100 a leap year? Is 2000? Is 1900? Give the reason each time.
  3. How many days does a leap year have? How many do four years in a row have, if exactly one of them is a leap year?
  4. In the condition of Listing 17.6, which part is true for 2000, and which for 2024?

Part II — A program.

  1. Run Listing 17.6 for your four years of question 2. Do the answers agree with yours?
  2. Write a program that counts the leap years from 1901 to 2100, both included, with a for loop, an if and a variable count that grows by 1 for each leap year.
  3. Change it to count from 2001 to 2400. Why are there more?
  4. Explain why every block of 400 years in a row, such as 2001 to 2400 or 1601 to 2000, has the same number of leap years.

Part III — The average year.

  1. Count the leap years in 400 years by hand: how many years are divisible by 4, how many of them end a century, and how many of those are divisible by 400?
  2. How many days are there in 400 years?
  3. What is the average length of a year, in days? Compare it with 365+1/4365 + 1/4.
  4. State the result.
Solution

Solution of Problem 17.1.

1. 2024 is divisible by 4 and does not end a century: a leap year. 2023 is not divisible by 4: not a leap year.

2. 2100 ends a century and is not divisible by 400: not a leap year. 2000 is divisible by 400: a leap year. 1900, like 2100: not a leap year.

3. 366 days. Four years with one leap year: 3×365+366=14613 \times 365 + 366 = 1461 days.

4. Both need year % 4 == 0. For 2024 the bracket is true because year % 100 != 0 (2024 does not end a century); for 2000 it is true because year % 400 == 0.

5. The program agrees: leap years for 2024 and 2000, not for 2100 and 1900.

6. and 7. The program below does both counts:

# How many leap years between two years, both included?
count = 0
for year in range(1901, 2101):
    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        count = count + 1
print("1901 to 2100:", count)

count = 0
for year in range(2001, 2401):
    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        count = count + 1
print("2001 to 2400:", count)
print("days in 400 years:", 400 * 365 + count)
print("average year:", (400 * 365 + count) / 400)
Counting leap years. code/grade-6/04-if-else/listings/count_leap.py
$ python count_leap.py
1901 to 2100: 49
2001 to 2400: 97
days in 400 years: 146097
average year: 365.2425
Output 17.10. 49 and 97.

From 1901 to 2100 there are 49 leap years: the 50 multiples of 4 from 1904 to 2100, minus 2100. From 2001 to 2400 there are 97, in twice as many years.

8. The rule depends only on the remainder of the year divided by 400: the year y+400y + 400 has the same remainders by 4, 100 and 400 as yy. So any 400 years in a row have the same leap years, moved by a multiple of 400.

9. In 400 years, 100 years are divisible by 4. Four of them end a century, and one of those four is divisible by 400. So 100−4+1=97100 - 4 + 1 = 97 leap years.

10. 400×365+97=146,097400 \times 365 + 97 = 146{,}097 days.

11. 146,097÷400=365.2425146{,}097 \div 400 = 365.2425 days. Every fourth year a leap year would give 365.25365.25: the century rule takes away 3 days in 400 years, and makes the average year 0.00750.0075 days shorter, much closer to the time the Earth takes to go round the Sun.

12. Result. There are 97 leap years in every 400 years, so 400 years have 146,097 days, and the average year of the calendar lasts 365.2425 days.

本章定义的术语

在术语表中查看全部 1050 个术语