Giving a value a name
Writing every number out in full works until you need the same number twice. Say you earn 15 an hour, you worked 9 hours this week, and you want to see your pay, and then your pay with a bonus of 20:
print(9 * 15)
print(9 * 15 + 20)It works, but there are two problems. 9 * 15 is written twice, and nothing in the program says that 9 is the hours and 15 is the rate. And when your rate goes up to 16, you have to find every 15 and change it. Miss one and you get a wrong answer, with no error message to warn you.
Names fix both. A name is a word you choose that stands for a value. You work the value out once, give it a name, and from then on you use the name:
hours = 9
rate = 15
pay = hours * rate
print(pay)
print(pay + 20)A line like pay = hours * rate is an assignment. Python first works out the expression on the right of =, here , and then binds the name on the left to that value. After that, pay is an expression like any other: wherever you write it, Python uses 135. And if the rate changes, you edit one line, rate = 15.
You choose the names yourself. A name can use letters, digits and underscores, but it can't contain a space or start with a digit. So week_pay and pay2 are fine, but week pay and 2nd are errors. Capitals count, so Pay and pay are two different names. Pick a name that says what the value means: hours tells the next person who reads your program much more than h.
You have to assign a name before you use it. If the program started with print(rate), Python would stop with NameError: name 'rate' is not defined. A misspelled print, such as prnt, gives the same error, and it means the same thing here: Python met a name that has no value.
Giving a name a new value
Suppose you got the hours wrong and actually worked 10. You can assign hours again, and the new value replaces the old one. Here we change hours after pay has been worked out, and then add the bonus to pay itself. Before you run it, guess what the second line of output will be:
hours = 9
rate = 15
pay = hours * rate
print(pay)
hours = 10
print(pay)
pay = pay + 20
print(pay)The second line is still 135. When pay = hours * rate ran, it worked out 135 and gave pay that number. pay doesn't remember that the number came from hours * rate, so changing hours later doesn't touch it. If you want the pay for 10 hours, you run pay = hours * rate again after the change.
The last assignment, pay = pay + 20, looks wrong if you read it as maths, because nothing equals itself plus 20. In a program = means something else: work out the right side, then make that the new value of the name on the left. So the right side uses the old pay, 135, and only then does pay become 155.
Step through the names
It helps to watch this happen. The demo below runs a program one step at a time. The box beside the code is a frame: it lists every name the program has bound so far, with its current value. Python calls this one the global frame. Step through the payroll and keep an eye on pay when hours changes.
The other two programs are worth a look too. In the second, height became 7 while width was still 3, so the last line prints , not . In the third, each line reads total before replacing it, so it goes 5, then 15, then 30.
Calling a function
So far we can add, subtract, multiply and divide. But some simple questions have no symbol. Which of two numbers is larger? How far apart are two numbers, whichever one is bigger? For questions like these, the language gives you functions: named pieces of code that take some values and work out a new one. Here we use three of them to compare this week's pay with last week's:
this_week = 135
last_week = 150
print(max(this_week, last_week))
print(min(this_week, last_week))
print(abs(this_week - last_week))Using a function is a call. You write the function's name, then the values you want it to work on in parentheses, separated by commas. Those values are the arguments. In max(this_week, last_week), max gets 135 and 150 and gives back the larger, 150. min gives back the smaller. abs takes one argument and gives it back without its minus sign: , and abs turns that into 15.
The value a function gives back is its return value, and that is the value of the call. A call is an expression, just like 2 + 5, so you can put it anywhere you could put a number: inside print, on the right of = as in gap = abs(this_week - last_week), or even inside another call. The arguments can be any expressions too: this_week - last_week is worked out to −15 first, and abs receives the −15.
You may have noticed that print looks the same. It is a function too, and print(pay) is a call with one argument, so you have been calling functions since your first program. max and min take as many arguments as you like: max(3, 9, 4) is 9.
With max and min the order of the arguments doesn't matter. With many functions it does, because each position has its own job. pow raises its first argument to the power of its second, so swapping them gives a different answer:
Functions you have to bring in
abs, max, min, pow and print are always there for you to use. Python has many more functions, but it keeps them in modules, collections of related functions that you load when you need them. The square root, for example, lives in a module called math. You load it by writing import math at the top, and then math.sqrt is its square-root function. Here we work out the diagonal of a 3 by 4 rectangle, :
print(math.sqrt(3 * 3 + 4 * 4))The argument 3 * 3 + 4 * 4 is worked out to 25 first, and math.sqrt(25) returns 5. You see 5.0 rather than 5 because math.sqrt always returns a number that can have a fraction, as math.sqrt(2) does; Data types explains why that matters. If you forget the import line, Python stops with a NameError and even asks Did you forget to import 'math'?. There is also a second way to write it: after from math import sqrt, you can write sqrt(25) without math. in front.
Working out calls inside calls
Since a call is an expression, you can put one call inside another. Here is a line with three calls and a multiplication. Try to work out what it prints before you run it:
print(max(abs(-8), min(5, 2 * 3)))To get it right, you need to know what happens first. Every call, however deeply it is nested, is worked out in the same two steps:
- Evaluate the part before the parentheses to find the function, and each argument to get its value.
- Call the function with those values. Its return value is the value of the call.
Now apply that to our line. The arguments of max are calls themselves, so before max can run, both steps have to happen for abs(-8) and for min(5, 2 * 3). And min can't run until 2 * 3 has been worked out. It is easier to see if we draw each call above its arguments. That drawing is an expression tree:
The expression tree of max(abs(-8), min(5, 2 * 3))
- a call or operator, worked out after everything below it
Read it from the bottom up. 2 * 3 gives 6, min turns 5 and 6 into 5, abs turns −8 into 8, and at the top max turns 8 and 5 into 8. A call can only run once everything below it has a value, so the work starts at the bottom of the tree and finishes at the top.
At the very bottom of a tree you only ever find numbers and names, and each has a one-line rule: a number evaluates to itself, and a name evaluates to the value it is bound to. That includes max. It is a name just like pay: when Python starts, it binds max to the built-in function that finds the largest value, and step 1 looks the function up by that name. This is why you should not call one of your own values max; Common mistakes shows what goes wrong.
Step through a nested call
The tree shows you the finished values, but not the order they were worked out in. The demo does: it takes the same line one call or operator at a time. The other two programs mix in names, so you can see a name being looked up in the frame.
Notice in the first program that abs(-8) is finished before 2 * 3 even starts, and min waits until both of its arguments have values. In the third, abs(a + b) is , so min receives 9 and 14 and returns 9.
Showing a value and returning it
abs and print are both functions, and you call them the same way, but they do very different jobs. abs gives back a value that the rest of your program can use. print shows something. You can see the difference if you store what each one returns:
distance = abs(4 - 9)
shown = print(4 - 9)
print(distance * 2, shown)Python details
print with two arguments shows both on one line, separated by a space.
The −5 appeared while the second line ran, because showing it is the whole job of print. What print gives back is None, Python's way of saying "no value", and that is what ended up in shown. So you can compute with distance, but not with shown. If you tried print(4 - 9) * 2, you would see −5 and then a TypeError, because Python can't multiply None.
Putting text on the screen is a side effect: something a call does besides returning its value. abs has no side effects. Call it with −5 as many times as you like, and it returns 5 and does nothing else. A function like that, whose only job is its return value, is called a pure function. Pure functions are the easiest kind to check, because one call tells you what every call with the same arguments will return.
Most programs in this course are built like that. They work out the answer with calls that return values, give the pieces names, and print the answer once, at the end.
Judge answers that fit in one expression
With names and calls you can already solve real judge problems. Many beginner problems give you a few numbers and ask for one value, and the answer is a single expression like the ones above. There is one new thing: a judge doesn't put the numbers in your code. It gives them to your program as input, a line of text your program reads while it runs. We take input apart properly in the next lesson. For now, you can copy this line, which reads a line of three whole numbers and names them n, a and b, in order:
n, a, b = map(int, input().split())If the line has two numbers, list two names instead. Our first problem is a choice between two prices:
people are travelling together. The train costs each of them yen, while a taxi costs yen for the whole group. Print the cheaper total.
Constraints
- All values are integers, given on one line as
N A B.
Sample 1 · Input
4 2 9
Output
8
Sample 2 · Input
4 2 7
Output
7
Sample 3 · Input
4 2 8
Output
8
The train costs the group and the taxi costs . We want the smaller of the two, so the last step is a call to min, and its arguments are the two prices:
n, a, b = map(int, input().split())
print(min(n * a, b))In the first sample the train costs yen and the taxi 9, so the program prints 8. Notice how we found the expression: we decided the last step first, the top of its tree, and then what that step needs as arguments. Try the same thing on the next two problems before you read our programs.
Two integers and are given on one line. Print the largest of , and .
Constraints
- and are integers.
Sample 1 · Input
-13 3
Output
-10
Sample 2 · Input
1 -33
Output
34
Sample 3 · Input
13 3
Output
39
The last step picks the largest of three numbers, so max goes at the top, and the three calculations are its arguments:
a, b = map(int, input().split())
print(max(a + b, a - b, a * b))On the first sample the arguments are −10, −16 and −39, and max returns −10. The third problem needs a little thinking before you can write the expression.
Three tasks have values , and , given on one line. The first task you do costs 0. After doing task , doing task next costs . Print the smallest total cost of doing all three.
Constraints
- All values are integers.
Sample 1 · Input
1 6 3
Output
5
Sample 2 · Input
11 5 5
Output
6
Sample 3 · Input
100 100 100
Output
0
Put the first sample on a number line: 1, 3 and 6. However you order the tasks, you have to cover the stretch from the smallest to the largest, so the cost is at least . Doing them from smallest to largest, 1 then 3 then 6, costs exactly . So the answer is the largest value minus the smallest:
a, b, c = map(int, input().split())
print(max(a, b, c) - min(a, b, c))Common mistakes
Expecting a name to follow the names it was computed from.
- Where it breaks
- After
pay = hours * ratewith 9 hours, thenhours = 10,paystill holds 135. - The fix
- Assign
payagain after changinghours:pay = hours * ratenow gives 150.
Naming a value after a built-in function:
max = 10.- Where it breaks
- A later
max(3, 4)fails. Python stops withTypeError: 'int' object is not callable, and GCC refuses to compile it with'max' cannot be used as a function. - The fix
- Choose a name that says what the value is, such as
bestorlargest.
In C++, passing three values to
max:max(3, 9, 4).- Where it breaks
- C++'s
maxtakes a third argument as a function for comparing the first two, so the compiler complains that anintis not a function. - The fix
- Put the values in braces:
max({3, 9, 4}).
Calling
math.sqrtwithoutimport math, orsqrtwithout#include <cmath>.- Where it breaks
- Python stops with
NameError: name 'math' is not defined. GCC reports thatsqrtwas not declared. Clang on a Mac compiles it anyway, because its<iostream>happens to bringsqrtin, so the missing include shows up only on another compiler, such as the judge's GCC. - The fix
- Write
import mathat the top in Python and#include <cmath>in C++.
Recall After `x = 4`, then `y = x * x`, then `x = y - x`, what are `x` and `y`?
y is 16 and x is 12. The right side of x = y - x uses the old x: . y stays 16, because changing x does not change a value already given to y.
Recall What does `max(abs(-6), min(4, 2 * 5))` evaluate to, and in what order are its calls worked out?
6. abs(-6) finishes first, giving 6. Then 2 * 5 gives 10, min(4, 10) gives 4, and max(6, 4) gives 6.
Key terms
| Term | Meaning |
|---|---|
| name | A word that stands for a value: after pay = hours * rate, pay stands for 135. |
| variable (C++) | A name that holds a value of one type, created before use: int pay. |
| assignment | A line that evaluates the right side of = and gives the result to the name on the left. |
| frame | The list of names a program has so far, each beside its current value. |
| function | A named piece of code that works out a value from the values it is given: max, abs. |
| call | Using a function: its name, then its arguments in parentheses, as in max(3, 9). |
| argument | A value handed to a function in a call: 3 and 9 in max(3, 9). |
| return value | The value a function gives back, which becomes the value of the call. |
| module (Python) | A collection of related functions loaded with import, such as math. |
| header (C++) | A file of related functions brought in with #include, such as <cmath>. |
| expression tree | A nested expression drawn with each call above its arguments. |
| side effect | Something a call does besides returning a value, such as showing text. |
| pure function | A function whose only job is its return value, the same one for the same arguments: abs. |
None (Python) | The value meaning "no value"; print returns it. |
