What is a variable?
🌍 In real life. In a kitchen, sugar, salt and rice live in jars with labels. When a recipe says "two spoons from the sugar jar", you don't need to know where the sugar came from; you find the jar by its label and use what's inside. If the jar is refilled, the label stays the same.
Programs need to remember things too: a score, a name, a price. A variable is a labelled jar for a value.
The idea in one sentence: a variable is a name that holds a value, so you can store the value once and use it by name as often as you like.
Its words:
- variable: a name for a value, like a labelled box
- value: what's inside, such as
12or"Rimi" - assignment: the line that puts a value in,
age = 12 =: read it as "gets": "age gets 12"
Step by step, for age = 12:
- Python works out the right side:
12. - It makes a box labelled
age(or finds it, if it already exists). - It puts
12inside. - Later, wherever you write
age, Python looks in the box and uses12.
Watch the box, and the code tracker under it, as age is filled and then changed after a birthday:
How Python does it. In Python, = doesn't mean "equals" like in maths. It's an instruction: "put the value on the right into the box on the left". The name always goes on the left.
When you use a name, there are no quotes around it. print(age) means "show what's in the box called age", but print("age") just shows the word age. Text values still need quotes when you write them: name = "Rimi".
You can use variables in calculations too: Python swaps each name for the value inside its box, then does the maths.
age = 12
print(age)name = "Rimi"
city = "Dhaka"
print(name, "lives in", city)apples = 5
print(apples + 3)
print(apples * 2)Mistakes and edge cases.
- Using a name before making it. Python reads from top to bottom (remember Chapter 1?), so
print(score)beforescore = 10givesNameError: name 'score' is not defined. See the example below. - Quotes around the name.
print("age")shows the wordage, not12. - The name on the wrong side.
12 = agegivesSyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?. The box goes on the left. - A different spelling is a different name. After
age = 12,print(Age)givesNameError: name 'Age' is not defined
print(score)
score = 10Quiz
What does this print?
x = 7 print(x)And this one? Look at the quotes.
x = 7 print("x")What does
price = 50do?- Puts 50 into a box named price
- Checks whether price is 50
- Prints 50
What does this print?
a = 4 print(a + a)Which line causes an error?
total = 3 print(totl) print("done")
Coding tasks
Make a variable called
colorthat holds the text"blue", then print it.pensholds 6. Printpenstimes 3. Use the variable, not the number 6.