A program needs to remember values: how many apples, a student's mark, a wallet balance. So you put the value in a variable: a name you choose, like a labelled box.
Write name = value; this is called assignment. Then print the value by writing the variable name without quotes:
apples = 5
print(apples)
print("apples")5 apples
print(apples) prints the stored value (5); print("apples") prints the word itself.Changing a variable
It is called a variable because its value can vary. apples = apples + 3 means: take the current value, add 3, and put the result back in the same variable.
apples = 0 apples = apples + 3 print(apples) apples = apples + 7 print(apples) apples = 100 print(apples)
3 10 100
= means "put into", not "equals" as in maths. That is why x = x + 3 is perfectly fine.You use variables in calculations just like numbers, and join them to text with str():
price = 45
plates = 3
total = price * plates
print("Total: " + str(total) + " pounds")Total: 135 pounds
Naming variables
| Rule | Valid | Invalid / note |
|---|---|---|
| Letters, digits and _ only, no spaces | math_score | math score |
| Cannot start with a digit | score2 | 2score |
| Upper and lower case are different | Age , age | two different variables |
| Cannot be a reserved word | my_print | if |
Pick a name that says what is inside: pocket_money is much clearer than x. A name that breaks the rules causes an error:
2score = 90 print(2score)
SyntaxError: invalid decimal literal
Practice
Complete the last line so it prints the value of apples (not the word apples).
apples = 0 apples = apples + 3 apples = apples + 7 ___
Press Run to see the result. Assign 0 to strawberries, add 5, then add 8, then print its value.
Press Run to see the result. Assign 4 to pears, add 6, then add 7, then print its value.
Press Run to see the result. Add two lines after the first: increase number by 10, then print its value.
number = 3
Press Run to see the result. Assign 5 to the variable num, then print its value.
Press Run to see the result. Omar has 200 pounds of pocket money. He buys koshary for 45, then a book for 30. Assign 200 to money, subtract each amount on its own line, then print Left: 125.
Press Run to see the result. A classroom is 8 metres long and 6 wide. Put the length in length and the width in width, calculate area, then print Area: 48 m2.
Press Run to see the result. Key points
x = valueassigns a value;print(x)without quotes prints it.x = x + 3adds 3 to the current value;=means "put into".- Names use letters, digits and _, never start with a digit, and should say what they hold.