Variables
Programs need to remember values: a user's name, a price, a score in a game. For that, they use variables. A variable is like a box with a label: it has a name, and it holds a value that you can use later.
You create a variable by writing its name, an equals sign = and a value:
city = "Prague"
print(city)This prints:
PragueThe first line creates a variable named city and stores the value "Prague" in it. The = sign stores the value on its right in the variable on its left. In programming, it doesn't mean “equals” as in math; read it as “gets”: city gets the value "Prague".
To use the value, write the name of the variable without quotes. print(city) prints the value of the variable, Prague, while print("city") prints the text city. And if you forget the quotes around text, Python reads it as the name of a variable: print(Prague) stops with the error NameError: name 'Prague' is not defined, because there is no variable called Prague.
A variable can also hold a number, and you can print it together with other values, separated by commas:
temperature = 18
print("It is", temperature, "degrees outside.")This prints:
It is 18 degrees outside.Rules for the names of variables:
- A name can contain letters, digits and the underscore
_, but it can't start with a digit:price2is fine,2priceisn't. - A name can't contain spaces. If it has more words, write them in lowercase and join them with underscores:
first_name,chocolate_price. This style is called snake_case, and Python programmers use it for the names of variables. - Uppercase and lowercase letters matter:
ageandAgeare two different variables.
Choose names that say what the variable holds: price tells you more than p or x.
Instructions
- 1
Create a variable
first_namewith the value"John". - 2
On the next line, print the value of
first_name. - 3
Below, create a variable
agewith the value25. It's a number, so no quotes. - 4
Finally, print this sentence. Use the variables
first_nameandage, and separate the values with commas:John is 25 years old.