Python
Topic 4 · Python basics · ⏱ about 3 h

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.

Show:
In this topic
Beginner

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".

age = 27 city = "Brisbane" age = age + 1 # take the current value (27), add 1, and attach the name to the result (28) print(city, age) # Brisbane 28

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.

Try it

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.

Beginner

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(...).

TypeWhat it holdsExamples
intwhole numbers (integers)27, -3, 1_000_000
floatnumbers with a decimal point3.14, -0.5, 2.0
strtext (a string of characters)"hello", '27', ""
boolTrue or FalseTrue, False, 5 > 3
Python
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"
Open in playground ↗
Beginner

Arithmetic

OperatorMeaningExampleResult
+ - *add, subtract, multiply4 * 2.510.0
/divide (always gives a float)7 / 23.5
//divide and round down7 // 23
%remainder ("modulo")7 % 21
**power2 ** 38

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 -=, *=, /=).

Python
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 approximately
Open in playground ↗
Beginner

Why 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.

Beginner

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.

Python
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 number
Open in playground ↗
Beginner

Practice: 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.

Exercise 1. Total with GST

Create price = 80 and quantity = 3. Calculate subtotal (price × quantity), gst (10% of the subtotal) and total (subtotal + gst).

Exercise 2. Minutes to hours

minutes = 200. Use // and % to set hours to the whole hours (3) and left to the minutes left over (20).

Exercise 3. Fix the types

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".

Beginner

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 / 2 to be 3. It is 3.5; use // for whole-number division.
  • Adding a number to text: "Total: " + 5. Use str(5), a comma in print, or an f-string (next lesson).
  • Spaces or dashes in names: total price and total-price are not valid names; use total_price.
Check yourself

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?

Go deeper

📚 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.

Ready