11. Variables and types

Chapter 7 wrote text directly inside print calls. That works, but any information needed in more than one place has to be retyped every time. Variables fix that. A variable is a name that stands in for a value, so you write the value once and reuse it.

Declaring a variable

The most common shape of a variable declaration in Python:

name = "Keiko"
print(name)

Two things are going on in that first line:

  • name is the variable's name. You pick it.
  • = is the assignment operator. It puts the value on the right into the variable on the left. It does not mean "equal to" the way it does in maths.

Now name stands in for the string "Keiko", so print(name) prints Keiko.

Python has no local keyword. Every variable you declare inside a function belongs to that function, and variables at the top level of a file belong to that file. You will learn about functions in a later chapter; for now, all your variables live at the top level.

Changing a variable

A variable's value can change. Use = again:

score = 0
print(score)   # prints 0
score = 50
print(score)   # prints 50

Open exercises/11/01-variables.py. Change the starting value of score and run the file. Both print calls should change in step.

Types

In Python a value also has a type, not just data. The five types you need right now:

  • str — text, written between quotes: "hello", 'a', "" (the empty string).
  • int — a whole number with no decimal point: 0, -7, 42.
  • float — a number with a decimal point: 3.14, 0.5, -1.0.
  • bool — exactly two values: True and False. No quotes. Note the capital letter — true (lowercase) is an error in Python.
  • NoneType — the type of None, which represents the absence of any value.

type() is a built-in function that returns an object describing a value's type. To get just the type name as a short string, use type(x).__name__:

print(type("hello").__name__)   # str
print(type(7).__name__)         # int
print(type(3.14).__name__)      # float
print(type(True).__name__)      # bool
print(type(None).__name__)      # NoneType

type(x) by itself prints something like <class 'str'>. The .__name__ part pulls out just the word str. Either form works for understanding; .__name__ is easier to read in output.

Variable names

You pick variable names, but Python has rules about which are allowed:

  • They can contain letters, digits, and the underscore _.
  • They cannot start with a digit. level1 is fine; 1level is not.
  • They are case sensitive. Score, score, and SCORE are three different names.
  • They cannot be one of Python's reserved words: and, as, assert, async, await, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield. You will meet most of these later.

Beyond the rules, follow these habits:

  • Choose meaningful names. player_name beats n. hit_points beats hp once code gets long, though hp is fine for short scripts.
  • Lower case with underscores is the standard Python style: max_score, enemy_count. This convention is called snake_case.

Printing a variable

print does not need quotes around variable names. Quotes are only for text you type directly. To combine a label with a variable, either pass them as separate arguments (Python adds a space between them) or use an f-string:

level = 7
print("Level:", level)        # Level: 7
print(f"Level: {level}")      # Level: 7

An f-string starts with f before the opening quote. Any variable or expression inside {} is evaluated and inserted into the string. This is the standard Python way to build strings with values in them.

The comma form print("Level:", level) prints a space between each argument automatically. The f-string f"Level: {level}" builds a single string, so you control every character. Both are correct; f-strings give more control.

Multiple assignment

Python lets you declare several variables and assign several values on one line. Names on the left pair with values on the right by position:

name, level = "Keiko", 7
print(name, level)   # Keiko 7

This groups related declarations neatly. It also enables a handy trick — swapping two variables in one step:

a, b = 1, 2
a, b = b, a
print(a, b)   # 2 1

Python reads the whole right side first, then assigns. So a, b = b, a takes the current b and a and puts them in opposite slots.

Homework

Homework starters are in exercises/11/homework/.

Problem 1 — Player vitals

Open exercises/11/homework/01-player-vitals.py. Declare four variables called name, level, hit_points, and alive, with values of your choice. The first must be a string, the next two numbers, and the fourth a boolean. Print each on its own line with a label, like Name: Keiko.

Problem 2 — Type checker

Open exercises/11/homework/02-type-checker.py. Use type(x).__name__ to print the type name of each of these five values, one per line:

  • the string "world",
  • the integer 42,
  • the float 3.14,
  • the boolean False,
  • None.

Problem 3 — Rename and reassign

Open exercises/11/homework/03-rename-and-reassign.py. The starter file has three variables a, b, and c with random-looking values. Rename them to something meaningful for their values, print the originals, change all three, then print them again.

Challenge — The None mystery

Open exercises/11/homework/04-none-mystery.py. Declare a variable and assign it None, then print its type name. Then give it a string value and print its type name again. Add a short comment block (several lines starting with #) explaining, in your own words, what None means.

Stuck or finished? Open the homework solutions page.