Variables and basic calculations

Objective

Store intermediate values and calculate a result using arithmetic.

Learning objective

Store intermediate values and calculate a result using arithmetic.

Explanation

A variable is a name associated with a value. Assignment uses one equals sign: minutes = 15. Reading the name later uses its current value. Choose descriptive names such as sessions rather than x when the purpose matters.

Addition, subtraction and multiplication work on numbers. Parentheses make the intended grouping explicit. / performs division; // gives a whole-number floor quotient. A later assignment can replace the value associated with a name. The example separates inputs from a calculation so each step can be checked. The exercise wrapper supplies its named inputs; do not replace them with the sample numbers.

Worked example

minutes = 15
sessions = 3
total = minutes * sessions
print(total)
assert total == 45

Common mistakes

Using a name before assigning it raises NameError. Hard-coding the example answer fails when the inputs change.

Guided practice

Calculate the total for four sessions of twelve minutes. Then change only sessions to zero and predict the result.

Independent practice

Try the exercises linked below. Predict an answer before running code, and explain one boundary case in your own words.

Recap

Store intermediate values and calculate a result using arithmetic. Compare the result with your prediction and use small examples to explain any difference.