Python Tutorial · Python Basics · Lesson 5 of 42

Python Variables

Create variables, name them well and reassign them to any type.

Creating variables

Python has no command for declaring a variable — it's created the first time you assign a value with =.

Example 1Try it yourself
x = 5
name = "Ada"
print(x)
print(name)

Output

5
Ada

Variables don't have a fixed type. The same name can later refer to a value of a different type:

Example 2Try it yourself
x = 4       # x is an int
x = "Sally" # now x is a str
print(x)

Output

Sally

Naming rules

  • Must start with a letter or underscore, not a number.
  • Can contain only letters, numbers and underscores (A-z, 0-9, _).
  • Case-sensitive (age, Age and AGE are different).
  • Can't be a keyword like if, for or class.

Python style uses snake_case for variables and functions: user_name, total_price.

Many values at once

Example 3Try it yourself
x, y, z = "Orange", "Banana", "Cherry"
print(x, y, z)

a = b = c = 0
print(a, b, c)

Output

Orange Banana Cherry
0 0 0

Names refer to objects

A variable is a name pointing to an object. Assigning one variable to another doesn't copy the object — both names point to the same one. This matters for mutable objects like lists:

Example 4Try it yourself
a = [1, 2, 3]
b = a          # b points to the same list
b.append(4)
print(a)       # a sees the change

Output

[1, 2, 3, 4]

Test yourself

Which variable name is valid in Python?

  1. 2my_var
  2. my-var
  3. my_var
  4. my var
Show answer

Answer: my_var

Names can't start with a digit or contain hyphens or spaces.