Values, Variables & Numbers
Store values in variables, meet the basic types (whole numbers, decimals, text and True/False), do arithmetic, and convert between types. Then watch variables change one line at a time.
Variables: names for values
A variable is a name you give to a value so you can use it later. Think of a label stuck on a box: the label is the name, the contents is the value. You create one with =, which in Python means "make this name refer to this value", not "is equal to".
The right-hand side is worked out first, then the name is attached to the result. That is why age = age + 1 makes sense in Python, even though it looks wrong in maths.
Naming rules: letters, digits and underscores; cannot start with a digit; no spaces; capitals matter (Age and age are different). The Python style is lowercase words joined by underscores: total_price, num_patients. Choose names that say what the value means: price beats p.
Watch variables change
Step through the code one line at a time. The table shows every variable after each line.
Interactive: this part runs in your browser.
The four basic types
Every value has a type, which decides what you can do with it. You can ask any value its type with type(...).
| Type | What it holds | Examples |
|---|---|---|
int | whole numbers (integers) | 27, -3, 1_000_000 |
float | numbers with a decimal point | 3.14, -0.5, 2.0 |
str | text (a string of characters) | "hello", '27', "" |
bool | True or False | True, False, 5 > 3 |
print(type(27), type(3.14), type("27"), type(True))
print(27 + 3) # numbers add
print("27" + "3") # strings join: "273"
print(5 > 3, 2 == 3) # comparisons give True or False
print(type(None)) # None means "no value"Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 4 * 2.5 | 10.0 |
/ | divide (always gives a float) | 7 / 2 | 3.5 |
// | divide and round down | 7 // 2 | 3 |
% | remainder ("modulo") | 7 % 2 | 1 |
** | power | 2 ** 3 | 8 |
Python follows the usual maths order: brackets first, then powers, then * / // %, then + -. When in doubt, add brackets. The shortcut x += 5 means x = x + 5 (also -=, *=, /=).
minutes = 135
hours = minutes // 60 # 2 whole hours
left = minutes % 60 # 15 minutes left over
print(hours, "h", left, "min")
price = 19.99
qty = 3
total = price * qty
print("total:", total)
print("rounded:", round(total, 2))
print("with 10% GST:", round(total * 1.10, 2))
score = 10
score += 5 # same as score = score + 5
print(score)
print(0.1 + 0.2) # 0.30000000000000004: decimals are stored approximatelyWhy 0.1 + 0.2 is not exactly 0.3
Computers store decimals in binary, and most decimals (like 0.1) cannot be stored exactly, just as 1/3 cannot be written exactly as a decimal. So 0.1 + 0.2 is 0.30000000000000004. This is normal in every programming language. Two habits avoid trouble: round when you show a number (round(x, 2)), and never compare decimals with ==; use abs(a - b) < 1e-9 or math.isclose(a, b). For money in serious programs, professionals use whole cents or the decimal module.
Converting between types
Use the type's name as a function to convert: int(...), float(...), str(...), bool(...). You need this all the time, because text from input(), files and websites always arrives as strings.
text = "42"
number = int(text)
print(number + 8) # 50
print(float("3.5") * 2) # 7.0
print(str(99) + " bottles")
print(int(7.9)) # 7: int() cuts off the decimals, it does not round
print(round(7.9)) # 8
print(bool(0), bool(5), bool(""), bool("hi")) # empty and zero are False
# int("3.5") or int("abc") is a ValueError: the text must look like a whole numberPractice: check yourself
Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
Create price = 80 and quantity = 3. Calculate subtotal (price × quantity), gst (10% of the subtotal) and total (subtotal + gst).
minutes = 200. Use // and % to set hours to the whole hours (3) and left to the minutes left over (20).
The code below crashes because age_text is text. Convert it so next_year is the number 28, and make message the string "Next year: 28".
Summary
Variables are names attached to values with =. Values have types: int, float, str and bool. Arithmetic follows maths rules, / always gives a float, and int(), float() and str() convert between types.
Key words
- variable
- a name that refers to a value
- assignment
- giving a name a value with
= - type
- the kind of value: int, float, str, bool
- int / float
- whole number / number with a decimal point
- str
- a string: text in quotes
- bool
- a Boolean: True or False
- operator
- a symbol that does something to values:
+ - * / // % ** - None
- a special value meaning "nothing here"
Common mistakes
- Using
=when you mean "is equal to": comparing uses==. - Using a variable before giving it a value: NameError.
- Expecting
7 / 2to be 3. It is 3.5; use//for whole-number division. - Adding a number to text:
"Total: " + 5. Usestr(5), a comma in print, or an f-string (next lesson). - Spaces or dashes in names:
total priceandtotal-priceare not valid names; usetotal_price.
Quiz
1. After x = 5 then x = x * 2, what is x?
2. What is 17 // 5?
3. What is 17 % 5?
4. What is the type of "3.5"?
5. Which is a valid variable name?
6. What does int(9.99) give?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- The Python Tutorial ↗ Official tutorial from python.org
- Think Python, 3rd edition (Allen Downey) ↗ free online textbook that teaches thinking like a programmer