Lesson 02 · Beginner · 18 min

Python Variables and Types

Store values in named variables and learn how Python decides what kind of value you have.

assignmenttype inspectionarithmetic and conversion

By noon Maya is holding six numbers in her head and dropping two of them. Giving each one a name — cups, price, change — is the first step. But what happens when the same name is handed text instead of a number?

Variables give names to values so your program can reuse them. Python is dynamically typed: you do not declare a type, but every value still has one. Knowing the type helps you predict how operators and functions will behave. You will also see how aliasing changes a list and why conversion belongs at the boundary.

Assignment creates a name

The equals sign assigns the value on the right to the name on the left. Reassigning a variable replaces its old value. Use descriptive names such as order_total rather than t.

price = 4.5
quantity = 3
total = price * quantity
print(total)

A small calculation

The four types you need first

Integers hold whole numbers, floats hold decimals, strings hold text, and booleans hold True or False. type() reveals the type of any value. A value that looks numeric can still be a string if it is quoted.

print(type(7).__name__)
print(type(4.5).__name__)
print(type("7").__name__)
print(type(True).__name__)

Inspecting types

Convert deliberately

int() converts compatible text or decimals to an integer, float() converts to a decimal, and str() converts a value to text. Conversion can fail: int("hello") raises ValueError, which you will handle in a later lesson.

count = int("12")
price = float("4.5")
label = str(2026)
print(count, price, label)

Explicit conversion

A name can point to a mutable object

Assignment does not copy a list. alias = orders makes both names point to the same object, so a change through one name is visible through the other. A full slice orders[:] creates a shallow copy; nested lists still share their inner objects.

orders = ["latte", "tea"]
alias = orders
copy = orders[:]
alias.append("mocha")
copy.append("water")
print(orders)
print(copy)
records = [{"id": 1}]
shallow = records[:]
shallow[0]["id"] = 99
print(records)

Aliases, shallow copies, and shared inner objects

Convert at the edge

Values from files, URLs, and forms arrive as text. Convert at the boundary, then work with numbers. Converting more than once spreads type errors through the program; converting once keeps the rest of the code predictable.

raw_count = "3"
raw_price = "4.50"
count = int(raw_count)
price = float(raw_price)
total = count * price
print(type(count).__name__, type(price).__name__)
print(f"{total:.2f}")

Turn text into numbers once

Do not compare floats with ==

0.1 + 0.2 is not exactly 0.3 in binary floating point. The tiny difference is invisible with print() but fatal in an equality check. For display, round the value; for decisions, use math.isclose() or compare integer cents. Money is often stored as integer cents for this reason.

total = 0.1 + 0.2
print(total)
print(total == 0.3)
print(round(total, 2) == 0.3)
cents = 10 + 20
print(cents / 100)

Approximate floats versus exact cents

Key points

  • Assignment binds a name to a value; reassignment replaces it.
  • int, float, str, and bool are the first four types to recognise.
  • type(value).__name__ gives a readable type name.
  • Convert input and text before doing arithmetic with them.
  • Assignment can alias a mutable object; a slice copies only the outer list.
  • Floats are approximations; compare with a tolerance or use integer cents.

Common mistakes

  • Trying to add a string and a number without converting one side.
  • Assuming / returns an integer; in Python 3 it returns a float.
  • Using a variable before assigning it, which raises NameError.
  • Assuming b = a copies a list; both names point to the same object.
  • Writing if total == 0.3 after arithmetic on floats.
Your turn

Create variables for an item name, unit price, and quantity. Print the total with two decimal places.

Try it yourself

Change the values, predict the output, then run the code. The Python runtime is downloaded the first time you press Run, so the first run can take a few seconds.

In-browser PythonRuns locally · no account
First run downloads Pyodide from a CDN. Use Run code after editing.

Practice this lesson

12 questions with immediate explanations.

See all 12 answersStart practice
← Print & stringsString methods →