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

Primary & Middle School Computer Science

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

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

15Variables and Input

Noor is playing a game on the tablet. At the top of the screen, a word and a number: score 0. She catches a star: score 10. Another one: score 20. The number keeps changing, but its name stays the same, and the game always knows where to find it. Programs keep their numbers and words in the same way, under names.

You already know

print shows text and the results of calculations; Python knows +, -, *, /, // and %; the lines of a program run from top to bottom; an error message names the line and the kind of problem (Chapter 14).

15.1 A name for a value

Definition 15.1 (Value and variable)

A value is a piece of data a program works with: a number such as 25 or 2.5, or a text such as "Noor". A variable is a name that a program gives to a value, to keep it and use it later.

Definition 15.2 (Assignment)

An assignment is an instruction that gives a value to a variable. It is written with the sign =: the name on the left, the value on the right, as in score = 0.

score = 0
print(score)
bonus = 25
print(score + bonus)
print("Noor's score:", score)
Listing 15.1. Two variables. code/grade-6/02-variables-and-input/listings/score.py
$ python score.py
0
25
Noor's score: 0
Output 15.1. Wherever a variable’s name is written, Python uses its value.

A variable is like a box with a label: the label is the name, and the box holds one value. A name is made of letters, digits and the sign _, starts with a letter, and is best chosen so that it says what the value means: score is better than s. Capital and small letters make different names: Score is not score.

15.2 Assignment is not equality

In mathematics, x=x+10x = x + 10 is never true. In Python, score = score + 10 is a perfectly good instruction, because = does not say that two things are equal: it says put into. Python first computes the right side, with the value the variable has now, then puts the result in the box. The old value is gone.

score = 0
score = score + 10
score = score + 10
score = score + 10
print(score)
Listing 15.2. Adding 10 three times. code/grade-6/02-variables-and-input/listings/update.py
$ python update.py
30
Output 15.2. The box held 0, then 10, 20 and 30.
The assignment score = score + 10, step by step: the value in the box is read, 10 is added, and the result replaces the old value.
The assignment score = score + 10, step by step: the value in the box is read, 10 is added, and the result replaces the old value.

To exchange the values of two variables, a third box is needed to keep a copy, just as two glasses of juice cannot be swapped without a third glass.

left = "apple"
right = "pear"
spare = left    # keep a copy of the left value
left = right
right = spare
print(left, right)
Listing 15.3. Exchanging two values with a spare variable. code/grade-6/02-variables-and-input/listings/swap.py
$ python swap.py
pear apple
Output 15.3. The two values have changed places.

15.3 Types

Not all values are of the same kind. Python tells them apart.

Definition 15.3 (Type)

The type of a value is the kind of value it is. Whole numbers have the type int (for integer), decimal numbers the type float, and texts in quotes the type str. The instruction type(...) gives the type of a value.

print(type(12))
print(type(12.5))
print(type("twelve"))
print(type("12"))
Listing 15.4. Asking Python for types. code/grade-6/02-variables-and-input/listings/kinds.py
$ python kinds.py
<class 'int'>
<class 'float'>
<class 'str'>
<class 'str'>
Output 15.4. "12" in quotes is a text, not a number.
Three types, three kinds of box. The same symbol + does different things with them.
Three types, three kinds of box. The same symbol + does different things with them.

The type decides what the operations do. Between two numbers, + adds; between two texts, it glues them end to end.

print(3 + 4)
print("3" + "4")
print("ice" + "cream")
Listing 15.5. The same sign, two types. code/grade-6/02-variables-and-input/listings/glue.py
$ python glue.py
7
34
icecream
Output 15.5. 3 and 4 make 7; the texts "3" and "4" make the text "34".

15.4 Input and conversions

The instruction input(...) prints a question, waits until the user has typed an answer and pressed Enter, and gives the answer as a value. In the outputs of this book, what the user typed appears right after the question.

name = input("What is your name? ")
print("Hello,", name)
print(f"Nice to meet you, {name}!")
Listing 15.6. A program that asks a question. code/grade-6/02-variables-and-input/listings/greet.py
$ python greet.py
What is your name? Noor
Hello, Noor
Nice to meet you, Noor!
Output 15.6. Noor typed her name.

Line 3 shows a handy way to build a sentence: a text with the letter f just before its quotes is an f-string, and each name between curly brackets {} is replaced by its value.

What the user types reaches the program as text. To compute with it, the text must first be converted into a number.
What the user types reaches the program as text. To compute with it, the text must first be converted into a number.

input always gives a text, even when the user types digits. Adding two typed numbers then glues them:

first = input("First number: ")
second = input("Second number: ")
print("The sum is", first + second)
Listing 15.7. Adding two typed numbers? code/grade-6/02-variables-and-input/listings/add_wrong.py
$ python add_wrong.py
First number: 12
Second number: 30
The sum is 1230
Output 15.7. 12 and 30 make 1230: two texts were glued.

Definition 15.4 (Type conversion)

A type conversion makes, from a value, the value of another type that stands for the same thing: int("12") gives the whole number 12, float("2.5") the decimal number 2.5, and str(12) the text "12".

first = int(input("First number: "))
second = int(input("Second number: "))
print("The sum is", first + second)
Listing 15.8. The typed texts are converted into whole numbers. code/grade-6/02-variables-and-input/listings/add_right.py
$ python add_right.py
First number: 12
Second number: 30
The sum is 42
Output 15.8. Now 12 and 30 make 42.

A program that asks, computes and answers is now within reach:

# The area and the perimeter of a rectangle, from its two sides.
length = float(input("Length in metres: "))
width = float(input("Width in metres: "))
area = length * width
perimeter = 2 * (length + width)
print(f"Area: {area} square metres")
print(f"Perimeter: {perimeter} metres")
Listing 15.9. The area and the perimeter of a typed rectangle. code/grade-6/02-variables-and-input/listings/rectangle.py
$ python rectangle.py
Length in metres: 7.5
Width in metres: 4
Area: 30.0 square metres
Perimeter: 23.0 metres
Output 15.9. A rectangle of 7.5 metres by 4 metres.

15.5 Following a program by hand

To understand a program, or to find a mistake in it, we can run it by hand, like the interpreter, writing down the value of each variable after each line.

Definition 15.5 (Trace table)

A trace table is a table that follows a program by hand: one column for each variable, one row for each line run, holding the values of the variables after that line.

a = 5
b = a + 3
a = b * 2
b = b - a
print(a, b)
Listing 15.10. A program to follow by hand. code/grade-6/02-variables-and-input/listings/trace_me.py

Example 15.6 (Tracing five lines)

A dash means that the variable has no value yet.

lineinstructionab
1a = 55–
2b = a + 358
3a = b * 2168
4b = b - a16−8-8
5print(a, b)16−8-8

The program should print 16 -8. Running it confirms the table:

$ python trace_me.py
16 -8
Output 15.10. The same values as in the trace table.

Method 15.7 (Tracing a program)

Draw one column per variable. Go through the program line by line, in the order Python runs it; for each line, write a new row: copy the values that do not change, and write the new value of the variable that is assigned. Compute the right side of an assignment with the values of the row above.

15.6 Exercises

Exercise 15.1 ★

What does this program print?

a = 4
a = a * 3
a = a - 5
print(a)
Listing 15.11. Three assignments. code/grade-6/02-variables-and-input/exercises/three_a.py
Solution

Solution of Exercise 15.1.

7: a is 4, then 4×3=124 \times 3 = 12, then 12−5=712 - 5 = 7.

Exercise 15.2 ★

What does print(type(4.0)) print? And print(type(4))?

Solution

Solution of Exercise 15.2.

<class 'float'>: the point makes 4.0 a decimal number, even though it is equal to 4. For 4, it prints <class 'int'>.

Exercise 15.3 ★

Try print("5" * 3) and print(5 * 3). What do you see?

Solution

Solution of Exercise 15.3.

"5" * 3 is the text "5" repeated three times: 555. The number 5 times 3 is 15.

Exercise 15.4 ★

Write a program that asks for a name and an age, then prints a sentence such as Sami will be 12 next year.

Solution

Solution of Exercise 15.4.

The age is converted with int so that 1 can be added to it.

name = input("Your name: ")
age = int(input("Your age: "))
print(f"{name} will be {age + 1} next year.")
A name and an age. code/grade-6/02-variables-and-input/exercises/name_age.py

Exercise 15.5 ★★

Tom’s program asks for two numbers and prints their sum, but for 5 and 7 it prints 57. What did he forget?

Solution

Solution of Exercise 15.5.

He forgot to convert the answers of input into numbers: "5" + "7" glues two texts into "57". With int(input(...)), as in Listing 15.8, the program prints 12.

Exercise 15.6 ★★

Write a program that asks for a number of minutes and prints it in hours and minutes: 135 gives 2 hours and 15 minutes.

Solution

Solution of Exercise 15.6.

total = int(input("Minutes: "))
print(f"{total // 60} hours and {total % 60} minutes")
Minutes into hours and minutes. code/grade-6/02-variables-and-input/exercises/minutes.py

For 135: 135=60×2+15135 = 60 \times 2 + 15.

Exercise 15.7 ★★

Make the trace table of Listing 15.3, with the three variables left, right and spare.

Solution

Solution of Exercise 15.7.

lineleftrightspare
1apple––
2applepear–
3applepearapple
4pearpearapple
5pearappleapple

After line 4 the value "apple" survives only in spare; line 5 brings it back into right.

Exercise 15.8 ★★

A notebook costs 2.50 euros. Write a program that asks how many notebooks are bought and prints the price.

Solution

Solution of Exercise 15.8.

count = int(input("How many notebooks? "))
print(f"Price: {count * 2.5} euros")
The price of the notebooks. code/grade-6/02-variables-and-input/exercises/notebooks.py

For 6 notebooks it prints Price: 15.0 euros.

Exercise 15.9 ★★

Lina’s program starts with size = int(input("Size: ")). When she types 2.5, it stops with a ValueError. Why? How can she fix it?

Solution

Solution of Exercise 15.9.

int converts only texts that are written as whole numbers: "2.5" is not one, so int("2.5") fails. The fix is float(input("Size: ")), which accepts both 2.5 and 3.

Exercise 15.10 ★★★

How many assignments does this program carry out? What does it print?

x = 1
y = x + 1
print(x, y)
x = y
y = 10
print(x + y)
Listing 15.12. Count the assignments. code/grade-6/02-variables-and-input/exercises/count_me.py
Solution

Solution of Exercise 15.10.

Four assignments: lines 1, 2, 4 and 5 (the print lines assign nothing). After line 2, x is 1 and y is 2, so line 3 prints 1 2; then x becomes 2 and y becomes 10, so line 6 prints 12.

Exercise 15.11 ★★★

Write a program that asks for a number of seconds and prints it in days, hours, minutes and seconds. What does it print for one million seconds?

Solution

Solution of Exercise 15.11.

A day has 24×3600=86,40024 \times 3600 = 86{,}400 seconds.

total = int(input("Seconds: "))
days = total // 86400
hours = total % 86400 // 3600
minutes = total % 3600 // 60
seconds = total % 60
print(f"{days} days, {hours} h, {minutes} min, {seconds} s")
Seconds into days, hours, minutes and seconds. code/grade-6/02-variables-and-input/exercises/dhms.py

For 1,000,000 seconds it prints 11 days, 13 h, 46 min, 40 s: 11×86,400+13×3600+46×60+40=1,000,00011 \times 86{,}400 + 13 \times 3600 + 46 \times 60 + 40 = 1{,}000{,}000.

Exercise 15.12 ★★★

Tom wants to exchange the values of a and b without a spare variable, so he writes a = b, then b = a. Make the trace table for a = 3 and b = 8, and explain what went wrong.

Solution

Solution of Exercise 15.12.

lineinstructionab
1a = 33–
2b = 838
3a = b88
4b = a88

The program prints 8 8. Line 3 wrote 8 over the 3, and nothing kept a copy of it: line 4 copies back the 8. A spare variable must save the first value before it is overwritten.

15.7 Problem: The Clock of the Day

Problem 15.1

Weekend problem — seconds, minutes and hours

A stopwatch counts only seconds. We want to read its number as a time of day, written h:m:s: hours, minutes and seconds.

Part I — By hand.

  1. How many seconds are there in one minute? In one hour? In one day?
  2. Write 5,000 seconds in hours, minutes and seconds. Show each division with its remainder.
  3. Do the same for 50,000 seconds.

Part II — Two programs. The first program turns seconds into h:m:s, the second does the opposite.

# A number of seconds written as hours, minutes and seconds.
total = int(input("Seconds: "))
hours = total // 3600
rest = total % 3600
minutes = rest // 60
seconds = rest % 60
print(f"{hours}:{minutes}:{seconds}")
Listing 15.13. From seconds to h:m:s. code/grade-6/02-variables-and-input/listings/clock.py
# Hours, minutes and seconds turned back into seconds.
hours = int(input("Hours: "))
minutes = int(input("Minutes: "))
seconds = int(input("Seconds: "))
print("Seconds:", hours * 3600 + minutes * 60 + seconds)
Listing 15.14. From h:m:s back to seconds. code/grade-6/02-variables-and-input/listings/back.py
  1. Make the trace table of Listing 15.13 when the user types 50000. Does it agree with your answer to question 3?
  2. What does Listing 15.14 print when the user types 13, 53 and 20? Why?
  3. What does the first program print for 3,599 seconds? For 3,600?
  4. The first program prints 13:53:20 in the same way it would print a time with a minute such as 7, without a 0 in front: 13:7:5. Which real time is 13:7:5?

Part III — Why it always works.

  1. Explain why the minutes and the seconds printed by the first program are always less than 60.
  2. Explain why the second program always gives back the number typed into the first one.
  3. Using the times printed for 0 and for the last second of a day, say which values h, m and s can take during one day.
  4. How many different h:m:s times does one day hold? Count them by hand, then let Python do the multiplication with the program below, and state the result.
# How many different h:m:s times does one day hold?
print("times in a day:", 24 * 60 * 60)
print("last second:", 24 * 60 * 60 - 1)
Listing 15.15. Counting the times of a day. code/grade-6/02-variables-and-input/listings/day.py
Solution

Solution of Problem 15.1.

1. 60 seconds in a minute; 60×60=360060 \times 60 = 3600 in an hour; 24×3600=86,40024 \times 3600 = 86{,}400 in a day.

2. 5000=3600×1+14005000 = 3600 \times 1 + 1400, then 1400=60×23+201400 = 60 \times 23 + 20: 1 hour, 23 minutes and 20 seconds, 1:23:20.

3. 50,000=3600×13+320050{,}000 = 3600 \times 13 + 3200, then 3200=60×53+203200 = 60 \times 53 + 20: 13:53:20.

4. The table, one row per line run (line 1 is a comment):

linetotalhoursrestminutesseconds
250000––––
35000013–––
450000133200––
55000013320053–
6500001332005320

Line 7 prints 13:53:20, as in question 3:

$ python clock.py
Seconds: 50000
13:53:20
Output 15.11. The first program.

5. It prints 50000: 13×3600+53×60+20=46,800+3180+20=50,00013 \times 3600 + 53 \times 60 + 20 = 46{,}800 + 3180 + 20 = 50{,}000. It undoes the first program.

$ python back.py
Hours: 13
Minutes: 53
Seconds: 20
Seconds: 50000
Output 15.12. The second program.

6. 0:59:59 for 3,599 seconds (one second short of an hour), and 1:0:0 for 3,600.

7. 13 hours, 7 minutes and 5 seconds, usually written 13:07:05.

8. The minutes are rest // 60, where rest is a remainder by 3600, so it is at most 3599, and 3599//60=593599 // 60 = 59. The seconds are rest % 60, a remainder by 60: a remainder is always less than the number we divide by.

9. The first program writes total as 3600×h+r3600 \times h + r, then rr as 60×m+s60 \times m + s, so total=3600×h+60×m+s\texttt{total} = 3600 \times h + 60 \times m + s. That is exactly what the second program computes.

10. The first second, 0, gives 0:0:0; the last, 86,399, gives 23:59:59. So hh goes from 0 to 23, and mm and ss from 0 to 59.

11. hh can take 24 values, mm 60 and ss 60: 24×60×60=86,40024 \times 60 \times 60 = 86{,}400 times, one for each second of the day.

$ python day.py
times in a day: 86400
last second: 86399
Output 15.13. One time for each second.

Result. A day holds 86,400 seconds, and each is written in exactly one way as h:m:s with h<24h < 24, m<60m < 60 and s<60s < 60: the first program gives a different time to each second, and the second program gives back the second from its time.

本章定义的术语

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