Variables and values¶
Goal: store information in variables, print it inside sentences, and ask the user for input.
Why this matters¶
In the last lesson every program printed the same thing every time. That is not very useful. Real programs remember things: a name, a score, a price. In Python you remember things with variables.
What is a variable?¶
A variable is a name that points to a value. You create one with the equals sign:
Run it and you get:
Read the first line as "let name be "Ada"". From then on, whenever you write name, Python uses the value "Ada".
The equals sign is not a question
In math, = asks whether two things are equal. In Python, = is an instruction: put this value in that name.
The name is always on the left, the value on the right.
Three kinds of values¶
The example above uses three different kinds of value, and Python treats each a little differently:
| Value | What it is | Python calls it |
|---|---|---|
"Ada" |
text, in quotes | a string, or str |
36 |
a whole number | an integer, or int |
1.65 |
a number with a decimal point | a float |
Notice that 36 has no quotes. "36" with quotes would be a string, a piece of text that happens to look like a number.
You can do math with 36 but not with "36". This difference will matter in a moment.
Naming rules¶
Python is picky about names. A variable name:
- can contain letters, digits, and underscores:
score,player_1,total_cost - cannot start with a digit:
1st_placeis not allowed - cannot contain spaces: write
first_name, notfirst name - is case-sensitive:
Nameandnameare two different variables
By convention, Python programmers write names in lowercase with underscores between words. This style is called snake_case.
Pick names that say what the value means. age is better than a, and price_per_kilo is better than p.
Changing a variable¶
You can give a variable a new value at any time. The old value is forgotten:
Printing variables inside text¶
You will often want to mix variables into a sentence. The neatest way is an f-string: put the letter f right before the
opening quote, then wrap each variable in curly braces.
name = "Ada"
age = 36
print(f"My name is {name} and I am {age} years old.")
print(f"Next year I will be {age + 1}.")
Anything inside { } is evaluated by Python and dropped into the text. That includes math, as the second line shows.
Forgot the f?
Without the f, Python prints the braces literally: My name is {name}. If you see curly braces in your output,
check for the missing f.
Asking the user for input¶
So far, values were typed into the program by you. The input() function lets the person running the program type a value.
Run it. The program prints the question, then pauses and waits for you to type something and press Enter:
The text inside input(...) is the prompt shown to the user. Whatever they type is handed back and stored in name.
Input is always text¶
Here is the catch: input() always gives you a string, even if the user types a number. Try this and see it break:
Python is saying: you asked me to add a string and a number, and I don't know how to do that.
The fix is to convert the text into an integer with int():
age_text = input("How old are you? ")
age = int(age_text)
print(f"Next year you will be {age + 1}.")
You can do the conversion in one step: age = int(input("How old are you? ")). Both styles are fine.
For decimal numbers use float() instead of int().
Try it¶
Write a program that asks for your favourite number, then prints that number times ten. Remember to convert the input.
Common mistakes¶
NameError: name 'nmae' is not defined
You used a variable that was never created, usually a typo. Python reports the misspelled name, so read it carefully.
SyntaxError: cannot assign to literal
The value and name are swapped, like 36 = age. The name must be on the left of the =.
ValueError: invalid literal for int() with base 10: 'abc'
You called int() on text that is not a number. For now, make sure to type a number when the program asks for one.
Later in the course you will learn how to handle this gracefully.
Exercises¶
- Personal greeting. Ask for the user's name and city, then print one sentence that uses both.
- Number tricks. Ask for a number and print it doubled, then print it squared (multiplied by itself).
- Mad libs. Ask the user for an animal, a food, and a place. Then print a short silly story that uses all three.
Solution 1
Solution 2
number = int(input("Type a number: "))
print(f"{number} doubled is {number * 2}.")
print(f"{number} squared is {number * number}.")
number * number works, and so does number ** 2. The ** operator means "to the power of".
Solution 3
Summary¶
- A variable stores a value under a name:
age = 36. - Strings are text in quotes. Integers and floats are numbers, without quotes.
- Use
snake_casenames that describe the value. - Put an
fbefore a string and use{braces}to insert variables into text. input()asks the user for a value and always returns a string. Convert withint()orfloat()when you need a number.