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)
PythonThe = 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)
helloShout into the canyon: hello
hello
hello
helloA 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")
soupFood: soup
soup
foodNaming 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.room2is a good name;2roomsandmy roomare not names at all. - Python tells capital and small letters apart, so
score,ScoreandSCOREwould be three separate variables. Use the wrong one, and Python stops with theNameErrorexplained 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)
redColor: redTraceback (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.