Learn / Programming / Python / Variables and Types

Python · Lesson 2 of 15

Variables and Types

Names, assignment, and the core built-in types: int, float, str, and bool.

  • Beginner
  • 12 min read
  • 3 objectives

Before this lessonLesson 1: Hello, Python

What you will learn

  • Assign and reassign variables
  • Use type() to inspect values
  • Cast between types

A variable is a name that points at a value. You create one with the assignment operator =. Python is dynamically typed: you never declare a type, because the type belongs to the value, not the name. The same name can later point at a value of a different type, although doing that on purpose is usually a sign of confusing code.

Variables are labels, not boxes

Many tutorials say a variable is a box that holds a value. A better picture is a sticky label attached to a value. The value lives somewhere in memory; the label lets you find it again. Writing age = 28 creates the number 28 and sticks the label age on it. Later, age = 29 simply moves the label to a different value.

age = 28
print(age)
age = 29          # move the label to a new value
print(age)

other = age       # two labels on the same value
print(other)
Output
28
29
29

The core types

  • int: whole numbers of any size, such as 28 or -5.
  • float: decimal numbers such as 19.99. They are binary approximations, so 0.1 + 0.2 is not exactly 0.3.
  • str: text, written in single or double quotes.
  • bool: True or False (note the capital letters).
  • None: a special value that means "nothing here yet".
age = 28
price = 19.99
name = "Amar"
active = True
nickname = None

print(type(age), type(price), type(name), type(active))
Output
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

Naming rules and style

Names can contain letters, digits and underscores but cannot start with a digit or be a reserved word like class or if. The community style is snake_case for variables: total_price, not totalPrice. Pick names that say what the value is.

Doing math and building strings

Arithmetic uses + - * /. Also useful: // for floor division, % for the remainder and ** for powers. To put values inside text, use an f-string: prefix the string with f and place expressions in braces.

items = 3
unit_price = 4.5
total = items * unit_price

print(7 // 2, 7 % 2, 2 ** 10)
print(f"{items} items cost ${total:.2f}")
Output
3 1 1024
3 items cost $13.50

Type conversion

Input from files and users usually arrives as text. Convert it with int(), float(), str() and bool(). Conversion can fail: int("abc") raises a ValueError, which you will learn to handle in the error-handling lesson.

n = int("42")
price = float("19.99")
label = str(3.14)
print(n + 1, price * 2, label + "!")
Output
43 39.98 3.14!

Walkthrough: a tiny shopping cart

Let us combine everything: several variables, arithmetic, and formatted output. Read the code line by line and predict the output before you look at it.

item = "notebook"
unit_price = 3.50
quantity = 4

subtotal = unit_price * quantity
tax = subtotal * 0.08
total = subtotal + tax

print(f"Item: {item}")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax: ${tax:.2f}")
print(f"Total: ${total:.2f}")
Output
Item: notebook
Subtotal: $14.00
Tax: $1.12
Total: $15.12

Notice how each line uses names defined above it. A variable must exist before you use it; asking for one that does not exist raises a NameError. Also notice the :.2f inside the braces: it means "show two decimal places", which is how you print money.

Checking a value's type

When something behaves strangely, ask Python what type it is. type() tells you, and isinstance() answers yes or no. This is the fastest way to spot a number that is secretly text.

value = "42"
print(type(value), value + value)

number = int(value)
print(type(number), number + number)
print(isinstance(number, int))
Output
<class 'str'> 4242
<class 'int'> 84
True

Integer division and remainders, visually

// answers "how many whole times does it fit?" and % answers "what is left over?". Together they solve everyday problems such as converting minutes to hours and minutes.

total_minutes = 135
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{total_minutes} minutes = {hours}h {minutes}m")
Output
135 minutes = 2h 15m

Key takeaways

  • A variable is a label attached to a value; assignment moves the label.
  • The core types are int, float, str, bool and None.
  • Use type() to inspect a value and int()/float()/str() to convert.
  • // gives the whole-number quotient, % the remainder; f-strings format output.
# Write your solution here
Up next · Lesson 3Working with StringsIndexing, slicing, the everyday string methods and clean formatting with f-strings.