4. Python Variables
What you will learn
- How to create and change variables
- The naming rules and good naming habits
- Multiple assignment and swapping values
- How to check a type and build text with f-strings
What is a variable?
A variable is a name that refers to a value. In Python you create one simply by assigning to it with =. There is no keyword like let, and no type to declare.
Python code
name = "Sam"
age = 25
height = 1.75
is_student = True
print(name, age, height, is_student)
Output
Sam 25 1.75 True
The = sign means assign, not “equals” as in maths. Python decides the type from the value you give. This is called dynamic typing.
Changing a variable
Python code
score = 10
score = score + 5
score += 2
print("Score:", score)
score = "ten"
print("Now it holds:", score)
Output
Score: 17 Now it holds: ten
A variable can be given a value of a different type later. Python allows it, but doing so makes code confusing, so keep one kind of value in each variable.
Naming rules
- Names may contain letters, digits, and underscores.
- They cannot start with a digit.
- They cannot contain spaces or hyphens.
- They are case sensitive.
- They cannot be a reserved word such as
if,for,class, orTrue.
| Name | Valid? |
|---|---|
first_name |
Yes |
_count |
Yes |
total2 |
Yes |
2total |
No: starts with a digit |
first-name |
No: the hyphen is read as minus |
class |
No: reserved word |
The Python style (PEP 8) is snake_case: lowercase words joined by underscores, such as total_price. Choose names that explain the value, so user_age beats x.
Assigning several at once
Python code
x, y, z = 1, 2, 3
a = b = c = 0
print(x, y, z)
print(a, b, c)
Output
1 2 3 0 0 0
Swapping two values
Python can swap two variables in one line, with no temporary variable.
Python code
first = "A"
second = "B"
first, second = second, first
print(first, second)
Output
B A
Checking the type
type() tells you what kind of value a variable holds.
Python code
print(type("Sam"))
print(type(25))
print(type(1.75))
print(type(True))
Output
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>
Showing variables in text: f-strings
An f-string starts with f before the quote. Anything inside curly braces is replaced by its value.
Python code
name = "Sam"
price = 4.5
quantity = 3
print(f"{name} bought {quantity} items.")
print(f"Total: {price * quantity:.2f}")
Output
Sam bought 3 items. Total: 13.50
The :.2f after the calculation shows two decimal places. F-strings are the clearest way to build text and are used everywhere in modern Python.
Joining text and numbers
Python will not silently join text and a number. This fails:
Python code: this fails
age = 25
print("Age: " + age)
What Python reports
TypeError: can only concatenate str (not "int") to str
Fix it with an f-string, a comma in print, or str(age):
Python code
age = 25
print(f"Age: {age}")
print("Age:", age)
print("Age: " + str(age))
Constants
Python has no true constants. By convention, a name in CAPITAL_LETTERS means “do not change this”.
Python code
TAX_RATE = 0.2
MAX_ATTEMPTS = 3
print(TAX_RATE, MAX_ATTEMPTS)
Removing a variable
del name removes a variable. Using it afterwards causes a NameError. You rarely need this.
Common mistakes
- Using a variable before giving it a value, which gives a
NameError. - Different capital letters in two places.
- Joining a string and a number with
+. - Using a reserved word, such as
classorlist, as a variable name. (listis not reserved, but using it hides Python’s own function.) - Vague names such as
a,data1, ortemp.
Exercise
Create variables product (Notebook), price (4.5), and quantity (3). Print 3 x Notebook = 13.50 using an f-string, with the total calculated by Python.
Show solution
product = "Notebook"
price = 4.5
quantity = 3
print(f"{quantity} x {product} = {price * quantity:.2f}")
Knowledge check
1. How do you create a variable in Python?
Assign a value to a name, such as age = 25.
2. Which naming style does PEP 8 recommend for variables?
snake_case, such as total_price.
3. Which function shows the type of a value?
type()
Summary
- Variables are created by assignment, and Python works out the type.
- Use snake_case names, avoid reserved words, and remember that names are case sensitive.
- Use f-strings to build text, and convert numbers before joining them to strings.