BeginnerLesson 2 of 305 min read

Variables and data types: int, float, str and bool

Store information in variables and learn Python's basic data types: whole numbers, decimals, text and True or False.

In this lesson you will

  • Create and update variables
  • Follow Python naming style
  • Recognise int, float, str and bool
  • Convert between types

About 16 minutes

Labelled boxes for information

When you move house, you write on each box: “Kitchen”, “Books”. A variable is a labelled box inside the computer’s memory. You put a value in it, give the box a name, and use the name whenever you need the value. Programs would be impossible without them: a game needs a score, a shop needs a price, a form needs a name.

Creating variables

name = "Sara"
age = 28
height = 1.65
is_student = True

print(name)
print(age)
print(height)
print(is_student)
Sara
28
1.65
True

The single = is the assignment operator. Read it as “put the value on the right into the box on the left”, not as “equals” in maths. Python needs no keyword like let or var. You simply write the name, an equals sign and the value.

Changing a variable

score = 10
print(score)

score = 25          # replace the old value
print(score)

score = score + 5   # take the current value, add 5, store it again
print(score)
10
25
30

The line score = score + 5 looks odd as mathematics, but as an instruction it reads naturally: take what is in the box, add five, put the result back in the same box.

Naming rules and style

  • Names may contain letters, digits and underscores, but cannot start with a digit: player1 is fine, 1player is not.
  • No spaces. Use snake_case: first_name, total_price, is_logged_in.
  • Names are case-sensitive: Score and score are different.
  • Do not use Python’s own words, such as if, for, class or print.
  • Choose meaningful names: price beats p.

The basic data types

Every value has a type, which decides what you can do with it. You can add two numbers, but you cannot sensibly add a number to a name. Python has four types you will use constantly:

Type Python name Examples Used for
Whole number int 7, -3, 2026 Counting
Decimal number float 3.14, 0.5 Measurements, prices
Text str "Hello", 'Hi' Words and sentences
True or False bool True, False Yes or no answers

Ask Python what type something is with the type() function.

print(type(42))
print(type(3.14))
print(type("Python"))
print(type(True))
print(type("42"))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'str'>

Notice the last line: "42" in quotes is text, not a number, even though it looks like one. That difference matters a lot, as you are about to see.

Why types matter

print(5 + 3)        # numbers add
print("5" + "3")    # text joins together
print("Ha" * 3)     # text repeats
8
53
HaHaHa
age = 28
print("I am " + age)
Traceback (most recent call last):
  ...
TypeError: can only concatenate str (not "int") to str

Python refuses to guess how to join text and a number, and tells you clearly. The fix is to convert the number to text with str(), or better, to use f-strings, which you will learn in the strings lesson.

age = 28
print("I am " + str(age))
I am 28

Converting between types

text = "25"
number = int(text)          # text to whole number
print(number + 5)

price = float("19.99")      # text to decimal
print(price * 2)

print(int(7.9))             # drops the decimal part: 7
print(str(100) + " rupees")
print(bool(0), bool(5), bool(""), bool("hi"))
30
39.98
7
100 rupees
False True False True

bool() shows an important idea: zero, empty text and a few other “empty” values count as False, while everything else counts as True. You will use this when you write conditions.

Several variables at once

x, y, z = 1, 2, 3
print(x, y, z)

a = b = 0           # both start at zero
print(a, b)

x, y = y, x         # swap two values
print(x, y)
1 2 3
0 0
2 1

Constants and None

Python has no true constants, but by convention names in CAPITALS mean “do not change this”: MAX_PLAYERS = 4. There is also a special value, None, which means “nothing here yet”.

MAX_PLAYERS = 4
winner = None
print(MAX_PLAYERS, winner)
print(winner is None)
4 None
True
Practice

Create variables for a product: name (text), price (decimal) and in_stock (True or False). Print all three on one line, then print the type of price.

Show one possible answer
name = "Notebook"
price = 120.5
in_stock = True
print(name, price, in_stock)
print(type(price))
Notebook 120.5 True
<class 'float'>
Common mistake

Using a variable before giving it a value. print(total) when total was never created gives NameError: name 'total' is not defined. Check the spelling, the capitals, and that the line creating it runs first.

Name things for the reader

Code is read far more often than it is written. days_until_exam tells a story. d forces everyone, including you next month, to guess.

Worked example: a tiny receipt

Let us combine variables, types and conversion in one realistic mini program. The goal: store a customer’s details, work out the total, and print a tidy receipt. Read each line and say what it does in plain words before looking at the output.

customer = "Sara Khan"
item = "Notebook"
quantity = 3
unit_price = 120.50
paid_in_cash = True

total = quantity * unit_price

print("Customer:", customer)
print("Item:", item, "x", quantity)
print("Total:", total)
print("Paid in cash:", paid_in_cash)
print("Types:", type(quantity), type(unit_price))
Customer: Sara Khan
Item: Notebook x 3
Total: 361.5
Paid in cash: True
Types: <class 'int'> <class 'float'>

Notice that quantity is an int and unit_price is a float, and Python happily multiplies them, giving a float. When different number types meet, Python picks the one that can hold the answer.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which is a valid variable name?

  1. first name
  2. first_name
  3. 1st_name
  4. class

Letters, digits and underscores; no spaces; no reserved words.

What type is "42"?

  1. int
  2. float
  3. str
  4. bool

Anything in quotes is text.

What does int(7.9) return?

  1. 7
  2. 8
  3. 7.9
  4. An error

int drops the decimal part.

What does "Ha" * 3 give?

  1. Ha3
  2. An error
  3. HaHaHa
  4. 9

Multiplying text repeats it.

What is None?

  1. A value meaning nothing here
  2. Zero
  3. An empty string
  4. An error

None represents the absence of a value.

Summary

  • A variable is a named box holding a value.
  • Use snake_case names.
  • The four basic types are int, float, str and bool.
  • Convert with int(), float(), str() and bool().

Next lesson

Next: numbers and operators, calculating with Python.

Questions

Do I have to declare a variable's type?

No. Python works out the type from the value, and the same name can later hold a different type.

What is the difference between int and float?

int holds whole numbers, float holds numbers with a decimal point.

Why does '5' + 3 fail?

Text and numbers cannot be added directly. Convert one of them first.

Progress is saved in this browser.