- Create a variable and update its value
- Tell the
int,float,strandbooltypes apart - Use arithmetic operators, including whole-number division and remainder
- Convert values with
int(),float()andstr()
You are scoring points in a game: first 0, then 10, then 25. The program has to remember this number somewhere and update it each time. That is what variables are for. Think of a variable as a box with a label: you put a value inside, and later you find it by its name to look at it or change it.
Variables
A name given to a value stored in memory. You create a variable with the = sign: the name goes on the left, the value on the right.
name = 'Murad'
age = 14
height = 1.62
print(name, age, height)
age = age + 1
print('Next year:', age)▸ Expected output
Murad 14 1.62 Next year: 15
Note that in programming = is not the equals sign from maths but assignment. The line age = age + 1 reads: “take the old value of age, add 1 and store the result back in age”. A variable's value can change at any time — that is where the name comes from.
- A name may contain letters, digits and the underscore (
_) but cannot start with a digit:score2is fine,2scoreis not. - Names cannot contain spaces. Join words with underscores:
first_name,total_price. - Upper and lower case matter:
ageandAgeare two different variables. - You cannot use Python's reserved words (
if,for,class,Trueand others) as names. - Choose meaningful names:
pricetells you much more thanx.
Basic data types
Every value has a type, and the type decides what you can do with it: numbers can be added up, strings can be joined together. Python works out the type by itself — you do not have to write it.
| Type | What it is | Examples |
|---|---|---|
int | integer (whole number) | 14, -3, 2026 |
float | floating-point (decimal) number | 1.62, 3.14, -0.5 |
str | string (text) | 'Baku', '42' |
bool | Boolean (truth value) | True, False |
You can check the type of a value with the type() function.
print(type(14))
print(type(1.62))
print(type('Baku'))
print(type(True))
print(type('42'))▸ Expected output
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'str'>
Look at the last line: '42' is in quotes, so it is a string, not a number. True and False are the answers “yes” and “no” — you will need them a lot in the lesson on conditions.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | addition | 7 + 2 | 9 |
- | subtraction | 7 - 2 | 5 |
* | multiplication | 7 * 2 | 14 |
/ | division | 7 / 2 | 3.5 |
// | whole-number division | 7 // 2 | 3 |
% | remainder | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
Leyla buys 3 notebooks at 2.5 manat each. Let's hand the calculation to Python and try the other operators too.
price = 2.5
count = 3
total = price * count
print('Total:', total)
print(17 // 5, 17 % 5)
print(2 ** 10)
print(2 + 3 * 4, (2 + 3) * 4)▸ Expected output
Total: 7.5 3 2 1024 14 20
Python follows the order of operations from maths: first powers, then *, /, //, %, and finally + and -. Use parentheses to change the order: 2 + 3 * 4 gives 14, but (2 + 3) * 4 gives 20.
A film lasts 135 minutes. How many hours and minutes is that?
Show solutionHide solution
//: 135 // 60 = 2.Find the minutes left over with
%: 135 % 60 = 15.Answer: 2 hours 15 minutes.
minutes = 135
hours = minutes // 60
rest = minutes % 60
print(hours, 'h', rest, 'min')▸ Expected output
2 h 15 min
Updating a variable based on its own value is so common that Python has a shortcut: score += 10 means the same as score = score + 10. The same works for -=, *= and /=.
score = 0
score += 10
score += 5
score -= 3
score *= 2
print('Score:', score)▸ Expected output
Score: 24
Converting between types
You cannot add a number to a string directly: if you write '5' + 5, Python raises a TypeError, because it does not know how to combine text and a number. In such cases, convert the value to the type you need: int() makes an integer, float() a decimal number and str() a string.
text = '25'
number = int(text)
print(number + 5)
print(text + '5')
print(float('3.5') * 2)
print('Age: ' + str(14))
print(int(7.9))▸ Expected output
30 255 7.0 Age: 14 7
text + '5' glues two strings together, so we get 255 — not the number two hundred and fifty-five but text made of the characters 2, 5 and 5.
A room is a rectangle: width = 7 and height = 4 (in metres). Store the area in a variable area and the perimeter in perimeter, then print two lines: Area: with the area and Perimeter: with the perimeter.
width = 7
height = 4
# area = ...
# perimeter = ...
# print Area: and Perimeter:▸ Expected output
Area: 28 Perimeter: 22
47 candies are shared equally among 6 children. The numbers are given as strings ('47' and '6'). Convert them to numbers with int(), then print two lines: Each child: with the number of candies each child gets, and Left over: with the candies that remain.
candies_text = '47'
children_text = '6'
# 1) convert both strings to int
# 2) print Each child: and the share (use //)
# 3) print Left over: and the rest (use %)▸ Expected output
Each child: 7 Left over: 5
Key points
- A variable is a name for a value, created with
=(assignment). - The basic types are
int,float,strandbool;type()shows a value's type. /always gives afloat;//gives the whole part of a division and%the remainder.x += 1is short forx = x + 1.int(),float()andstr()convert a value to another type;int()drops the decimal part.
Check yourself
10 questions. Every correct answer earns XP.
x = 5 and then x = x + 2. What will print(x) show?