Know some Python? Write your own interactive tutorial, with runnable examples and exercises, and share it with a link. Write and share your own tutorial.

Start writing

Learn Python / Variables and Types

Variables and Types

A variable is a name that refers to a value. Variables let your program remember things so you can use them later.

A good way to picture it: a variable is a label stuck on a value. age = 36 sticks the label age on the value 36. Whenever you write age, Python looks up which value that label is stuck on.

Creating variables

You create a variable by assigning a value to a name with =:

name = "Ada"
age = 36

print(name)
print(age)
print(name, "is", age, "years old")
Output

Read age = 36 as "age now refers to 36". The = sign means "store this value", not "equals" as in maths. The name always goes on the left and the value on the right; 36 = age is an error.

Notice the difference between print(name) and print("name"). Without quotes, Python looks up the variable and prints its value, Ada. With quotes, it's just the text name.

A variable has to be created before you use it. Python runs from top to bottom, so using a name before its = line gives a NameError:

print(city)
city = "Paris"
Output

Swap the two lines and run it again.

Changing a variable

Variables can be reassigned at any time: the label moves to the new value.

Predict first: what will each print show? Decide, then press Run.

score = 10
print(score)

score = 25
print(score)

score = score + 5
print(score)
Output

The last line looks odd if you think of = as "equals". Python works it out in two steps:

  1. It calculates the right side using the current value: score + 5 is 25 + 5, which is 30.
  2. It stores the result in score, replacing the old value.

The old value 25 isn't kept anywhere. A variable only ever holds its latest value.

Naming rules

Variable names:

  • can contain letters, digits and underscores (_),
  • can't start with a digit,
  • are case-sensitive (age, Age and AGE are three different variables),
  • can't contain spaces or symbols such as -, ! or .,
  • can't be a Python keyword such as if, for or class.

By convention, Python programmers use snake_case: lowercase words joined with underscores. Good names describe what the value is, like total_price rather than tp.

Name OK? Why
user_name Yes lowercase words joined with _
score2 Yes digits are fine after the first character
2nd_place No starts with a digit
user-name No - is the minus sign, so Python reads user - name
first name No contains a space
class No a Python keyword

Run this to see the error a bad name gives. Because it's a SyntaxError, Python refuses to run any of the code, not even the first line:

print("Starting")
2nd_place = "Bo"
Output

Basic data types

Every value in Python has a type: is it a whole number, a decimal number, some text? These are the ones you'll use most:

Type Meaning Examples
int Whole numbers 42, -7, 0
float Decimal numbers 3.14, -0.5, 2.0
str Text (strings) "hello", 'Python'
bool True or false True, False
NoneType "No value" None

int is short for integer and str for string. None is a special value meaning "nothing here yet".

A few details that trip people up:

  • True, False and None start with a capital letter. true is just an unknown name.
  • A decimal point makes a float, even when the number is whole: 2.0 is a float, 2 is an int.
  • Quotes make a str, even when what's inside looks like a number: "42" is text, not a number.

Use the built-in type() function to find out the type of any value:

count = 42
price = 19.99
language = "Python"
is_ready = True
result = None

print(type(count))
print(type(price))
print(type(language))
print(type(is_ready))
print(type(result))
Output

Each line prints something like <class 'int'>. Read it as "the type is int". (Class is Python's word for a type.)

The type matters because it decides what you can do with a value. For example, + adds numbers but joins strings:

# two ints: adds them
print(2 + 3)

# two strings: joins them
print("2" + "3")
Output

Numbers get a lesson of their own next.

A variable can change type

You never declare a type in Python. A variable simply takes the type of whatever value it currently holds, and it can hold a different type later:

thing = 10
print(thing, type(thing))

thing = "ten"
print(thing, type(thing))
Output

Converting between types

"25" (text) and 25 (a number) look similar, but they're different types. To change a value's type, use the type's name like a function:

text = "25"
number = int(text)
print(number + 5)

print(float("3.5") * 2)
print(str(100) + " points")
print(int(9.99))
Output
Function Turns a value into Example Result
int() a whole number int("25") 25
float() a decimal number float("3.5") 3.5
str() text str(100) "100"

Converting doesn't change the original variable. int(text) gives back a new value, which is why the code stores it with number = int(text).

Two things to watch for with int():

  • On a decimal number, int() drops everything after the point. It doesn't round, so int(9.99) is 9.
  • The text has to look like a whole number. int("hello") and int("3.5") both stop with a ValueError. (float("3.5") works.)
print(int("42"))

# not a whole number: ValueError
print(int("3.5"))
Output

Mixing text and numbers without converting raises a TypeError. Run this to see it:

age = 30
print("I am " + age + " years old")
Output

Python refuses to guess whether you meant maths or joining text. Fix it by converting the number to text:

age = 30
print("I am " + str(age) + " years old")
Output

That works, but all the + signs and spaces are fiddly to get right. f-strings, next, are the easier way.

f-strings

An f-string has an f before the opening quote. It lets you put variables, and even small calculations, inside curly braces {}:

name = "Ada"
age = 36

print(f"{name} is {age} years old")
print(f"Next year {name} will be {age + 1}")
Output

Inside the braces you can put a variable, or a small expression such as age + 1. Python works it out and puts the result into the text. Everything outside the braces is printed exactly as written.

f-strings convert the values for you, so they're the easiest way to mix text and numbers. You'll use them in almost every lesson from here on.

The most common mistake is forgetting the f. Without it, the braces are printed as ordinary text:

name = "Ada"
# no f: the braces are printed
print("Hello, {name}")

# with f: the value goes in
print(f"Hello, {name}")
Output

Swapping two variables

You can assign several variables in one line by separating them with commas. This gives a neat trick for swapping two values:

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

a = "left"
b = "right"

a, b = b, a
print(a, b)
Output

x, y = 3, 7 gives x the first value and y the second. In a, b = b, a, Python reads both values on the right first ("right", "left") and only then stores them, so neither value gets lost.

Going deeper: Why not just a = b, then b = a? optional

That's the natural first try, but it loses a value:

a = "left"
b = "right"

# a is now "right"; "left" is gone
a = b

# so b gets "right" too
b = a
print(a, b)
Output

Many other languages swap with a third, temporary variable that holds one value while you move the other. Python's a, b = b, a does that for you.

Later, in the User Input lesson, you'll let the person running your program type in the values instead of writing them into the code.

Exercises

Exercise 1: Area of a rectangle

Create variables width and height with the values 7 and 4.5, calculate the area, and print it using an f-string: The area is 31.5.

width = 
height = 
Output

Exercise 2: Add two numbers stored as text

The two variables below hold strings. Convert them and print their sum, which should be 42, not "1527".

first = "15"
second = "27"

print(first + second)
Output

Exercise 3: Swap the values

Swap the values of cup_a and cup_b so the program prints coffee tea.

cup_a = "tea"
cup_b = "coffee"

# swap here

print(cup_a, cup_b)
Output

Exercise 4: Check the types

Print the type of each value: 3, 3.0, "3" and 3 > 2. Can you predict each one before running?

# print the type of each value
Output

Summary

  • A variable is a name for a value, created with = (name on the left, value on the right). Create it before you use it.
  • Reassigning replaces the old value. score = score + 5 uses the current value, then stores the new one.
  • Names use letters, digits and _, can't start with a digit, and are case-sensitive. Use snake_case.
  • Common types: int, float, str, bool, None. Check one with type().
  • Convert with int(), float() and str(). int() drops decimals, and text and numbers don't mix with + without converting.
  • Use f-strings like f"{name} is {age}" to build readable output. Don't forget the f.

Share this tutorial

Know something worth teaching? Write your own tutorial with runnable examples and share it.