---
title: "Decisions: if and else"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 17
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 17 — Decisions: 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](https://one-course.com/books/computer-science/1/en/chapter/2-instructions-in-order#def-g1-instructions-in-order-instruction) for everybody: it chooses. In this chapter, our [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) learn to choose.

**You already know.**

A [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is a question whose answer is yes or no, and an [algorithm](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-algorithm) can do one thing or another depending on it ([Chapter 10](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#ch-g4-algorithms-repeat-and-decide)). `input` reads a typed answer as text, and `int` converts it into a whole number ([Chapter 15](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#ch-g6-variables-and-input)). A `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) repeats an indented block ([Chapter 16](https://one-course.com/books/computer-science/1/en/chapter/16-repeating-with-for-turtle-drawings#ch-g6-for-loops-turtle)).

## 17.1 Comparisons give true or false

**Definition 17.1 (Comparison and Boolean value).**

A *comparison* asks how two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) compare, with one of the signs `==` (equal), `!=` (not equal), `<`, `<=`, `>` and `>=`. Its result is a *Boolean value*: `True` or `False`, the only two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the type `bool`.

```python
print(3 < 5)
print(3 > 5)
print(7 == 7)
print(7 != 7)
print(10 <= 9)
print("cat" == "Cat")
```

***Listing 17.1.** Six [comparisons](#def-g6-if-else-comparison). 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](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), two `==` ask whether two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) 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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is true: `if condition:` followed by an indented block. It may have an `else:` followed by a second block, run when the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-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`.

```python
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](#def-g6-if-else-if) ran; line 6 runs in every case.*

As for the `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-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](#def-g6-if-else-if) 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.](https://one-course.com/images/onecourse/chapters/computer-science-1/g6-if-else/fig-21786429432b.svg)

*An `if` statement is a fork: the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) sends the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition). Python checks the [conditions](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) 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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) was true.

```python
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](#def-g6-if-else-if).*

![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.](https://one-course.com/images/onecourse/chapters/computer-science-1/g6-if-else/fig-1c5e52d59174.svg)

*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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) wins, the order of the cases matters. Here the two questions are swapped: every child is also under 65, so the second [branch](#def-g6-if-else-if) can never be reached.

```python
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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) 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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) below prints, for each of the four ways to choose `a` and `b`, the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of `a and b` and of `a or b`.

```python
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.](https://one-course.com/images/onecourse/chapters/computer-science-1/g6-if-else/fig-7caa899efeff.svg)

*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.

```python
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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) would mean something else.

## 17.5 Testing every branch

A [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) with [branches](#def-g6-if-else-if) can be right for one [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) and wrong for another. To test it, we choose [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) that reach every [branch](#def-g6-if-else-if), and we try the *boundaries*: the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) where the answer changes. For the cinema, they are 12 and 65, and the ages just before them.

```python
# 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.](https://one-course.com/images/onecourse/chapters/computer-science-1/g6-if-else/fig-1d36e2696396.svg)

*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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), the whole rule can be checked at once:

```python
# 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](#def-g6-if-else-if) 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 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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print?

```python
x = 7
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")
```

***Listing 17.9.** Which [branch](#def-g6-if-else-if)? code/grade-6/04-if-else/exercises/which.py*

**Solution of Exercise 17.2.**

`medium`: 7 is not more than 10, so the first [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is false; it is more than 5, so the `elif` [branch](#def-g6-if-else-if) 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 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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that asks for a number and prints `positive or zero` or `negative`.

**Solution of Exercise 17.4.**

```python
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](#def-g6-if-else-if) because the [comparison](#def-g6-if-else-comparison) is `>=`.

**Exercise 17.5 ★★.**

Lina wants to give `x` the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) 3. Her [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) is `x = 1`, then `x == 3`, then `print(x)`, one per line. It prints `1`, with no [error message](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-error). What does her second line do? Fix it.

**Solution of Exercise 17.5.**

`x == 3` is a [comparison](#def-g6-if-else-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](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-error). To give `x` the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) 3, the line must be an [assignment](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-assignment), with one `=`: `x = 3`. It is the mirror of the slip of [Output 17.2](#out-g6-if-else-assign), where one `=` stood where `==` was needed.

**Exercise 17.6 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) never prints `senior`, whatever the age. Why? Fix it.

```python
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 of Exercise 17.6.**

Anyone older than 65 is also older than 12, so the first [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) is already true and the `elif` is never checked. The narrower case must come first:

```python
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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that asks for three numbers and prints the largest.

**Solution of Exercise 17.7.**

The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) keeps the largest number seen so far in a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) and compares each new number with it.

```python
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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that turns a mark out of 20 into a letter: A from 16, B from 12, C from 8, D below 8.

**Solution of Exercise 17.8.**

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

```python
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](#def-g6-if-else-if) of this [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), with the boundaries.

```python
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](#def-g6-if-else-if). code/grade-6/04-if-else/exercises/reach.py*

**Solution of Exercise 17.9.**

One [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) inside each band and the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) on both sides of each boundary: $-5$ (ice), $-1$ and $0$ (ice, then cool), $19$ and $20$ (cool, then warm), $30$ and $31$ (warm, then hot). The boundary 30 belongs to `warm` because the test is `<=`.

**Exercise 17.10 ★★★.**

A [password](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-password) should have at least 12 characters, and `len(password)` gives the number of characters of a text. Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that asks for a [password](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-password) and says whether it is long enough, and if not, how many characters are missing.

**Solution of Exercise 17.10.**

```python
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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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.

```python
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 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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints `yes yes` only for `True True`, and `no no` in the three other cases.

**Exercise 17.12 ★★★.**

Tom’s leap-year [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) says that 1900 is a leap year. Find the mistake, fix it, and give a year that shows the fix is right.

```python
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 of Exercise 17.12.**

The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) tests only “divisible by 4” and forgets the exception for the centuries. The fix is the [condition](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) of [Listing 17.6](#lst-g6-if-else-leap): `year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)`. The year 1900 shows the fix: the old [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-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](#lst-g6-if-else-leap) 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](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-condition) of [Listing 17.6](#lst-g6-if-else-leap) , which part is true for 2000, and which for 2024?

**Part II — A program.**

5. Run [Listing 17.6](#lst-g6-if-else-leap) for your four years of question 2. Do the answers agree with yours?
6. Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that counts the leap years from 1901 to 2100, both included, with a `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) , an `if` and a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) `count` that grows by 1 for each leap year.
7. Change it to count from 2001 to 2400. Why are there more?
8. 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.**

9. 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?
10. How many days are there in 400 years?
11. What is the average length of a year, in days? Compare it with $365  + 1/4$ .
12. State the result.

**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 \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](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) agrees: leap years for 2024 and 2000, not for 2100 and 1900.

**6.** and **7.** The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) below does both counts:

```python
# 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 + 400$ has the same remainders by 4, 100 and 400 as $y$. 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 = 97$ leap years.

**10.** $400 \times 365 + 97 = 146{,}097$ days.

**11.** $146{,}097 \div 400 = 365.2425$ days. Every fourth year a leap year would give $365.25$: the century rule takes away 3 days in 400 years, and makes the average year $0.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.
