MSIT

Names and printing

A name points at a value. name = "Ada" stores the text "Ada" under the name name. print(name) shows that value in the output.

A function can hand a value back to the caller with the return statement.

Names are how a program remembers. Without a name, a value exists only for the moment Python computes it. With a name, later lines can use that same value again. The Python tutorial calls this an assignment statement: the name on the left, the value on the right.

A name stores a value

The equals sign does not ask whether two things are equal. It stores. Read name = "Ada" as "the name name now points at the text Ada."

Python evaluates the right-hand side first, then attaches the name. You can point the same name at a new value later. The old value is not changed. The name simply stops pointing at it.

Text in quotes is a string. A number written without quotes is a number. "Ada" and Ada are not the same thing: the first is text, and the second is a name that must already point at a value.

  • A string is text, written in quotes.
  • A number is written without quotes, as in year = 1843.
  • A name is a label you choose. It is not written in quotes when you use it.

Printing is not returning

print writes a value where you can see it. It does not hand that value back to the caller. A function that should give back a result uses return.

+ joins two strings when both sides are text. "Name: " + "Ada" is the string "Name: Ada". The space after the colon is part of the first string. Leave it out, and the result is "Name:Ada".

The call label("Ada") does three things:

  1. It matches the argument "Ada" to the parameter name.
  2. It runs the body, which builds one new string.
  3. It returns that string to the caller. print then shows it.

Code after return in the same function does not run. If you need to see a value and hand it back, print it before the return, or print the call from outside the function.

Try the example before you change the exercise.

Worked example

Suppose the page should introduce a person by name. The function takes the name and returns a short line. It does not print. The caller decides whether to print.

The first call returns "Name: Ada". The second returns "Name: Grace". Same function, different argument, different result. That is why a function is more useful than a line that prints one fixed name.

This program cannot be stepped through.

Step through the trace. The first line stores a value. The second line looks up that name and shows the value. Nothing in those two lines builds a new string.

What does print do?

Click the line that stores a value.


Exercise: Labeling

Write a function named label that takes a string name as an argument and returns the string "Name: " joined with the provided name. For example, label("Ada") should return "Name: Ada".

Output