Python Variables
Python variables are names that store values so you can use them later. Unlike many languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it with the equals sign.
Creating Variables
product = "Green Tea"
price = 6.5
quantity = 3
print(product)
print(price * quantity)Green Tea 19.5
Here product holds text, price holds a decimal number and quantity holds a whole number. You did not have to say which type each one is; Python works it out from the value.
Variables Can Change Type
Python is dynamically typed, so a variable can be reassigned to a value of a different type. Use the type() function to see what a variable currently holds.
x = 10
print(type(x))
x = "ten"
print(type(x))<class 'int'> <class 'str'>
Python Variable Naming Rules
- A name must start with a letter or an underscore (_)
- A name cannot start with a number
- A name may only contain letters, numbers and underscores
- Names are case-sensitive: total and Total are different variables
- A name cannot be a Python keyword such as if, for, class or True
- By convention, use lowercase words separated by underscores (snake_case), like first_name
Assign Multiple Variables
Python lets you assign several variables in one line. You can also give the same value to many variables, or unpack the items of a list into separate variables.
a, b, c = "red", "green", "blue"
print(a, b, c)
x = y = z = 0
print(x, y, z)
colors = ["cyan", "magenta"]
first, second = colors
print(second)
# Swap two values without a temporary variable
a, b = b, a
print(a, b)red green blue 0 0 0 magenta green red
Global and Local Variables
A variable created outside any function is global and can be read inside functions. A variable created inside a function is local and only exists there. To change a global variable from inside a function, use the global keyword.
counter = 0
def add_one():
global counter
counter = counter + 1
add_one()
add_one()
print(counter)2
Without the global line, Python would treat counter inside the function as a new local variable and raise an error, because you would be reading it before giving it a value. In real programs, returning values from functions is usually cleaner than changing globals.
Frequently asked questions
How do you declare a variable in Python?
You do not need a declaration. Just assign a value, for example age = 30, and the variable exists from that point on.
Can a Python variable name start with a number?
No. A name must start with a letter or underscore. Names like 2nd_place are invalid, but place_2 is fine.
What are constants in Python?
Python has no true constants. By convention, names written in ALL_CAPS such as MAX_SIZE = 100 are treated as constants that should not be changed.
How do I check the type of a variable in Python?
Use type(variable) to get its type, or isinstance(variable, int) to check whether it is a particular type.