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 =.
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:
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,AgeandAGEare different). - Can't be a keyword like
if,fororclass.
Python style uses snake_case for variables and functions: user_name, total_price.
Many values at once
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:
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?
2my_varmy-varmy_varmy var
Show answer
Answer: my_var
Names can't start with a digit or contain hyphens or spaces.