Python Arena
Step 2 of 4

Variables

In the last step, city = input(...) stored the user's answer in city. A variable is a name that holds a value, so the program can use that value later. You create one by writing its name, an equals sign = and the value. The value can come from input, or you can write it straight into the code:

language = "Python"
print(language)
Output
Python

The = doesn't mean "is equal to" as in mathematics. It's an instruction: work out the value on the right, then store it under the name on the left. This is called assignment.

Use it as often as you like

Once a value is stored, the program can use it again and again. input runs only once, and the variable remembers the answer:

shout = input("Shout into the canyon: ")
print(shout)
print(shout)
print(shout)
Input
hello
Output
Shout into the canyon: hello
hello
hello
hello

A variable or a piece of text?

Quotes make all the difference here too. Without quotes, food is the variable and Python prints its value. With quotes, "food" is just a string of four letters:

food = input("Food: ")
print(food)
print("food")
Input
soup
Output
Food: soup
soup
food

Naming variables

You pick a variable's name yourself, within a few rules:

  • Use letters, digits and the underscore _, with no spaces, and don't begin with a digit. room2 is a good name; 2rooms and my room are not names at all.
  • Python tells capital and small letters apart, so score, Score and SCORE would be three separate variables. Use the wrong one, and Python stops with the NameError explained below.
  • By convention, Python names are all small letters, with an underscore where a space would go: pet_name, home_town. This style is called snake case.

A good name tells the reader what the value is. Python is just as happy with x, but city explains itself to anyone who reads the code later, including you a week from now.

A name Python doesn't know

If you misspell a variable's name, Python has no variable by that name, so it stops with a NameError, the same error a misspelled print gives:

color = input("Color: ")
print(colr)
Input
red
Output
Color: red
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(colr)
          ^^^^
NameError: name 'colr' is not defined. Did you mean: 'color'?

The variable is color, but line 2 asks for colr, with a letter missing. Python even suggests the name it knows.

Your task

Challenge 1 of 3

This program should ask for a pet's name and print it on a name tag, but it stops with a NameError. Fix it, so that a run looks like this:

Pet's name: Rex
Hello, my name is
Rex

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Python can't even start this program, because one of its variable names breaks the rules. Rename the variable to home_town everywhere, so that a run looks like this:

Home town: Bergen
You come from
Bergen