A program needs to remember things: a score, a name, whether the game is over. A variable is a name that refers to a value.
Creating a variable#
age = 21
name = "Asha"
price = 99.5
is_member = True
The = means assign: work out the value on the right, then make the name on the left refer to it. It is not "equals" in the maths sense, which is why this is fine:
count = 1
count = count + 1 # count is now 2
You do not declare a type first. Python works it out from the value.
Naming rules#
- Letters, digits and underscores only, and not starting with a digit:
total_2is fine,2totalis not. - Case matters:
Scoreandscoreare different names. - By convention, Python uses snake_case:
max_speed, notmaxSpeed. - Choose names that say what the value means.
days_leftbeatsd.
The basic types#
| Type | Holds | Examples |
|---|---|---|
int | whole numbers, any size | 0, -7, 1000000 |
float | numbers with a fractional part | 3.14, -0.5, 2.0 |
str | text | "hello", 'A', "" |
bool | true or false | True, False |
There is also None, which means "no value yet".
Python's integers have no upper limit, which is unusual. 2 ** 100 simply works. In C, C++ and Java an ordinary integer stops at about two billion.
Checking a type#
print(type(42)) # <class 'int'>
print(type(4.2)) # <class 'float'>
print(type("42")) # <class 'str'>
Notice the last one: "42" in quotes is text, not a number. "42" + 1 is an error, because Python will not guess whether you meant text or arithmetic.
Converting between types#
int("42") # 42
float("3.5") # 3.5
str(42) # "42"
int(3.9) # 3: the fraction is cut off, not rounded
round(3.9) # 4
bool(0) # False; any other number is True
Converting text that is not a number fails loudly:
int("hello") # ValueError: invalid literal for int()
That is a good thing. A silent wrong answer is far harder to find than an error.
Floats are approximate#
print(0.1 + 0.2) # 0.30000000000000004
Floats store a close binary approximation of most decimals. For money, count in whole paise or cents with int. To compare floats, check whether they are close rather than exactly equal:
abs((0.1 + 0.2) - 0.3) < 1e-9 # True
Several at once#
x, y = 3, 4 # x is 3, y is 4
x, y = y, x # swap them: x is 4, y is 3
a = b = 0 # both refer to 0
The swap is a small piece of Python elegance; most languages need a temporary variable.
Key points#
- A variable is a name for a value;
=assigns. int,float,strandboolare the everyday types, andtype()tells you which you have.- Text that looks like a number is still text until you convert it with
int()orfloat(). - Floats are approximate; never compare them with
==.
Next: doing things with values, with operators.