Find a course

Module 1: First Steps in PythonLesson 2 of 1212 min

Variables and Data Types

Store values in variables, update them, and learn the four basic data types (int, float, str and bool) and the rules for naming variables well.

Step 1 of 13Learn

Variables are names for values

Imagine writing a program that calculates a monthly budget. You'll use the rent amount in five different places. Typing 1450 five times is fragile: when the rent changes, you have to find every copy. Instead you give the value a name once and use the name everywhere. That name is a variable.

rent = 1450
groceries = 520
total = rent + groceries
print(total)        # 1970

The single equals sign is the assignment operator. Read rent = 1450 as "let rent refer to 1450", not "rent equals 1450". Python first works out the value on the right, then attaches the name on the left to it.

That's why this line, which is nonsense in algebra, is perfectly normal in Python:

count = 0
count = count + 1   # take the current count, add 1, store the result
print(count)        # 1

There's a shortcut for that pattern: count += 1 does exactly the same thing, and similar shortcuts exist for subtraction and multiplication.

A variable can be given a new value at any time, and the old value is simply forgotten. Using a variable before assigning it causes a NameError: Python has no idea what the name means yet.

Step 2 of 13Learn

How assignment really works

It helps to picture a variable as a label on a value, not a box that contains it. When you write b = a, Python doesn't copy anything; it sticks a second label on whatever a currently refers to.

a = 10
b = a      # b now refers to the same value, 10
a = 20     # a is moved to a new value
print(b)   # still 10

Moving the a label to 20 does not move b. Numbers and strings can never be changed in place, so this is all you need for now. (Lists behave in a way that surprises people, and you'll see why in Module 4.)

Python also lets you assign several variables at once, which makes swapping two values a single line:

x, y = 3, 7
x, y = y, x
print(x, y)   # 7 3

In many languages, swapping needs a temporary variable. In Python, the right side is evaluated completely first (giving 7 and 3), and then the names are reassigned.

Order matters in a script because lines run top to bottom. If you print a variable before the line that changes it, you'll see the old value. When a program shows an unexpected value, trace it line by line on paper, writing each variable's value as it changes. Programmers call this tracing, and it solves a surprising number of bugs.

Step 3 of 13Tap to reveal

Trace it: labels, not boxes

  1. a = 10

    Python creates the value 10 and sticks the label a on it.

  2. b = a

    A second label, b, goes on the same value 10. Nothing is copied.

  3. a = 20

    The label a moves to a new value, 20. b still points at 10.

  4. print(a, b)

    Prints 20 10. Reassigning one name never changes another.

Step 4 of 13Practice · What would you do?

What would you do?

Trace this program line by line. What does it print?

price = 8
qty = 3
price = price + 2
total = price * qty
print(total)

Step 5 of 13Learn

The four basic data types

Every value in Python has a type, which decides what you can do with it. The four you'll use constantly:

TypeNameExamplesTypical use
intinteger42, -7, 0counts, ages, quantities
floatfloating-point number3.14, -0.5, 2.0prices, measurements
strstring (text)"hello", '42', ""names, messages, codes
boolBooleanTrue, Falseyes/no flags, results of comparisons

The built-in type() function tells you a value's type: type(3.0) gives <class 'float'>.

The difference between 5 and "5" is crucial. The first is a number; the second is text that happens to contain a digit. 5 + 5 is 10, but "5" + "5" is "55", because adding strings joins them. And 5 + "5" is a TypeError: Python refuses to guess whether you meant math or joining.

A number with a decimal point is always a float, even if the decimal part is zero: 2.0 is a float, 2 is an int. True and False must be written with a capital first letter, without quotes; "True" in quotes is just a four-letter string.

Python is dynamically typed: you don't declare a type, and a variable can refer to a value of a different type later. That's convenient, but it means you must keep track of what each variable holds.

Step 6 of 13Practice · Diagram

Python’s four basic types

Where does the value "3.5" (in quotes) belong?

Tap the shape that answers the question, then press Check.

Python’s four basic typesHierarchy diagram: A value, Numbers, int: 42, -7, 0, float: 3.14, 2.0, str: "hi", "42", bool: True, False.A valueNumbersint: 42, -7, 0float: 3.14, 2.0str: "hi", "42"bool: True,False
A value
Numbers
int: 42, -7, 0

Whole numbers, any size.

float: 3.14, 2.0

Numbers with a decimal point.

str: "hi", "42"

Text in quotes; "42" is text, not a number.

bool: True, False

Yes/no answers, with a capital T and F.

Step 7 of 13Practice · Sort into groups

Sort each Python value by its data type.

Tap an item, then tap its group (or drag it there).

Step 8 of 13Learn

Naming variables well

Python enforces a few hard rules for names:

  • Use letters, digits and underscores only. No spaces, hyphens or symbols.
  • A name cannot start with a digit: item2 is fine, 2item is not.
  • Names are case sensitive: total, Total and TOTAL are three different variables.
  • You can't use Python's keywords, words with special meaning such as if, for, class, True and def.

Beyond the rules, there are strong conventions. Python programmers write variable names in snake_case: lowercase words joined by underscores, such as monthly_rent or max_score. ALL_CAPS is used for values meant to stay constant, such as TAX_RATE = 0.08.

Good names describe what a value means. x = 1450 forces the reader to guess; monthly_rent = 1450 explains itself. Single letters are fine for short-lived counters, but not for anything that matters.

One sneaky trap: Python lets you reuse the names of built-in functions, such as list, str, sum or print, as variables. sum = 10 is legal, but afterwards calling sum([1, 2]) fails, because sum now means 10. Avoid built-in names.

Step 9 of 13Compare

Variable names: weak vs clear

AspectWeak or invalidClear
Starts with a digit2nd_place (error)second_place
Contains a hyphentotal-cost (error)total_cost
Too shortx, t, dprice, tax_rate, days_left
Hides a built-inlist, print, sumitems, report, total

Step 10 of 13Practice · Select all that apply

Which of these are valid Python variable names? Select all that apply.

Select all that apply.

Step 11 of 13Note

Step 12 of 13Practice · Fill in the blanks

Fill in the blanks

After running a = 10, then b = a, then a = 20, the variable b refers to and a refers to .

Step 13 of 13Practice · Choose one

What is the type of the value produced by 7 / 2 in Python 3?