Python course · Module 2: Values · Lesson 5 of 63
Quick answer: A Python variable is a name that refers to a value. You create one with =, for example age = 21, and Python works out the type by itself, so you never declare it. A name may contain letters, digits and underscores, must not start with a digit, and must not be a keyword such as class. By the PEP 8 style guide, variable names are lowercase with underscores, like student_name.
In this lesson you will learn:
- how to create a variable with
=and check its type withtype() - what “dynamic typing” means and how to change a variable
- how to assign several variables in one line and swap two values
- the naming rules Python enforces and the PEP 8 style it recommends
- how to read and fix
NameErrorand the other errors beginners meet
Before you start: finish Lesson 4, Python Indentation and Syntax, so you can write and run a .py script. Every example here was run as a script with Python 3.14.6. Python 3.15.2, the newest release on python.org, gave exactly the same output.
Table of Contents
What is a variable?
A variable is a name you give to a value so you can use it later. In this lesson we keep one small example: a student profile.
name = "Ayesha"
age = 21
score = 87.5
print(name)
print(age)
print(score)
print(name, "is", age, "years old.")
Ayesha
21
87.5
Ayesha is 21 years old.
The = sign does not mean “is equal to” like in maths. It means assign: take the value on the right and give it the name on the left. The Python tutorial says it simply: “The equal sign (=) is used to assign a value to a variable.”
print() shows the value of a variable, not its name.
Python decides the type for you
Every value has a type: text, whole number, decimal number and so on. The built-in type() function tells you the type.
name = "Ayesha"
age = 21
score = 87.5
is_student = True
print(type(name))
print(type(age))
print(type(score))
print(type(is_student))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
stris a string (text). Quotes make a value a string.intis an integer (a whole number).floatis a number with a decimal point.boolisTrueorFalse.
You never wrote the type; Python decided from the value. Each type gets its own lesson in this module.
Dynamic typing: a variable can change type
In Python, the type belongs to the value, not to the name. So the same name can refer to a number now and to a string later. This is called dynamic typing.
age = 21
print(age, type(age))
age = "twenty-one"
print(age, type(age))
21 <class 'int'>
twenty-one <class 'str'>
It is allowed, but it confuses readers. Keep one kind of value in each variable.
Changing a variable
To change a variable, assign to it again. The right side is calculated first, using the old value, and then the name is pointed at the new value.
score = 87.5
print("Old score:", score)
score = score + 5
print("New score:", score)
score += 2.5
print("Final score:", score)
Old score: 87.5
New score: 92.5
Final score: 95.0
score = score + 5 reads as “the new score is the old score plus 5”. score += 2.5 is a short way to write score = score + 2.5. The result 95.0 has a .0 because the value is a float. Lesson 6 explains floats.
A name points to a value
What happens when you assign one variable to another?
city = "Lahore"
home_city = city
city = "Karachi"
print("city:", city)
print("home_city:", home_city)
city: Karachi
home_city: Lahore
home_city = city makes home_city refer to the same value, "Lahore". Then city = "Karachi" moves only the city label to a new value. Think of a variable as a label on a value.
Assigning several variables at once
Python can assign many names in one line.
name, age, score = "Ayesha", 21, 87.5
print(name, age, score)
wins = losses = 0
print(wins, losses)
first = "Ali"
second = "Sara"
first, second = second, first
print(first, second)
Ayesha 21 87.5
0 0
Sara Ali
- The first line gives each name on the left the value in the same position on the right.
wins = losses = 0gives the same value to both names.first, second = second, firstswaps two values. The tutorial explains that “the expressions on the right-hand side are all evaluated first before any of the assignments take place”, so no extra variable is needed.
The number of names and values must match. Otherwise you get an error:
name, age = "Ayesha", 21, 87.5
Traceback (most recent call last):
File "/home/learner/python-course/err1_unpack.py", line 1, in <module>
name, age = "Ayesha", 21, 87.5
^^^^^^^^^
ValueError: too many values to unpack (expected 2, got 3)
Two names, three values. (Your path will show your own folder.)
Naming rules Python enforces
The language reference sets the rules for names (it calls them identifiers):
- A name can use letters
A-Zanda-z, the underscore_and digits0-9. (Python also accepts letters from other alphabets, such asé, but this course uses English letters only.) - A name cannot start with a digit.
- There is no length limit, and “Case is significant”:
scoreandScoreare different names. - A name cannot be a keyword.
Break a rule and Python refuses to run the file. A name that starts with a digit:
File "/home/learner/python-course/err2_starts_with_digit.py", line 1
1st_place = "Ali"
^
SyntaxError: invalid decimal literal
Python saw 1 and expected a number. Use first_place instead.
A hyphen in the name:
File "/home/learner/python-course/err3_hyphen.py", line 1
first-name = "Ayesha"
^^^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
Python reads first-name as “first minus name”, a calculation, and you cannot assign to a calculation. Ignore the == hint; the fix is first_name.
A keyword as a name (a space in a name, like first name, gives the same message):
File "/home/learner/python-course/err5_keyword.py", line 1
class = "7B"
^
SyntaxError: invalid syntax
The list of keywords
Python can print its keyword list. The import line loads the built-in keyword module; you will learn import in Module 6.
import keyword
print(len(keyword.kwlist))
print(keyword.kwlist)
35
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
There are also a few soft keywords, such as match, case and type, which are special only in certain statements (Python 3.15 adds lazy). They are allowed as names, but avoiding them keeps your code clear.
Naming style: PEP 8
The rules above are what Python accepts. PEP 8, the official style guide, says what Python programmers expect:
- Variable and function names are lowercase, “with words separated by underscores as necessary to improve readability”. This is often called snake_case:
student_name. - Constants, values that should not change, are “written in all capital letters with underscores separating words”:
MAX_SCORE. Python does not stop you from changing them; the capitals are only a signal to the reader. - Never use
l(lowercase L),O(capital o) orI(capital i) as single-letter names, because they look like1and0. - If the best name is a keyword, add an underscore at the end, like
class_, or choose another name, likeclass_name. - Put one space on each side of
=.
# Hard to read
x = 21
StudentName = "Ayesha"
# Easy to read (PEP 8 style)
student_age = 21
student_name = "Ayesha"
MAX_SCORE = 100
print(student_name, student_age, MAX_SCORE)
Ayesha 21 100
All names here are legal, but x says nothing about its value, and StudentName uses the CapWords style that PEP 8 keeps for class names.
NameError: using a name that does not exist
NameError means you used a name that has no value yet. A typo is the usual cause:
score = 87.5
print(scor)
Traceback (most recent call last):
File "/home/learner/python-course/err6_typo.py", line 2, in <module>
print(scor)
^^^^
NameError: name 'scor' is not defined. Did you mean: 'score'?
Python even suggests the name you probably meant. The second cause is order. Python runs from top to bottom, so a variable must be assigned before you use it:
print(total)
total = 100
Traceback (most recent call last):
File "/home/learner/python-course/err7_use_before_assign.py", line 1, in <module>
print(total)
^^^^^
NameError: name 'total' is not defined
Fix: move total = 100 above the line that uses it.
Try it yourself
Exercise 1: A product variable set
Create three variables for a shop item: product_name (“Notebook”), price (120) and quantity (3). Calculate the total in a fourth variable and print a line like Notebook x 3 = 360.
Exercise 2: Swap two classes
Make morning_class = "Maths" and evening_class = "English". Swap them in one line, then print both.
Exercise 3: Fix the names
This script stops with SyntaxError: invalid decimal literal. Rename all three variables so the script runs and prints Maths Physics 7B.
1st_subject = "Maths"
subject-two = "Physics"
class = "7B"
print(1st_subject, subject-two, class)
Solutions
Solution 1
product_name = "Notebook"
price = 120
quantity = 3
total = price * quantity
print(product_name, "x", quantity, "=", total)
Notebook x 3 = 360
total is calculated from the other two variables, and print() puts a space between its items.
Solution 2
morning_class = "Maths"
evening_class = "English"
morning_class, evening_class = evening_class, morning_class
print("Morning:", morning_class)
print("Evening:", evening_class)
Morning: English
Evening: Maths
Python reads both values on the right first, then assigns them, so the swap needs no third variable.
Solution 3
first_subject = "Maths"
subject_two = "Physics"
class_name = "7B"
print(first_subject, subject_two, class_name)
Maths Physics 7B
Each name now starts with a letter, uses underscores instead of a hyphen, and avoids the keyword class.
Common mistakes
- Forgetting quotes around text.
name = AyeshagivesNameError: name 'Ayesha' is not defined. Without quotes, Python thinksAyeshais another variable. Writename = "Ayesha". - Using a variable before you assign it.
print(total)abovetotal = 100givesNameError: name 'total' is not defined. Assign first, use later. - Hyphens, spaces or a digit at the start.
first-name,first nameand1st_placeall give aSyntaxError. Use letters, digits and underscores, and start with a letter. - Reusing a built-in name. After
print = "Hello", the lineprint("Hi")fails withTypeError: 'str' object is not callable, becauseprintnow refers to a string. Avoid names likeprint,str,listandinput.
Frequently asked questions
Do I need to declare a variable in Python?
No. Python creates the variable the first time you assign a value with =, and it works out the type from the value. There is no separate declaration step and no type keyword like int in C or Java.
How do I check the type of a variable in Python?
Use type(), for example print(type(age)), which prints <class 'int'> for a whole number. The built-in functions page also recommends isinstance() for testing a type inside your program, which you will meet later in the course.
Can a Python variable name start with an underscore?
Yes, _count is legal. PEP 8 describes a single leading underscore as a weak “internal use” signal, so beginners should use plain lowercase names.
Summary
- A variable is a name for a value;
=assigns the value on the right to the name on the left. - Python decides the type from the value (dynamic typing);
type()shows it. - Assign again to change a variable;
a, b = b, aswaps two values in one line. - Names use letters, digits and underscores, cannot start with a digit, cannot be keywords, and are case sensitive.
- Follow PEP 8:
snake_casefor variables,UPPER_CASEfor constants, and descriptive names.
Related lessons: How to run a Python script, Python strings and f-strings, Python type conversion.
Next lesson
Next: Lesson 6, Python Numbers: int, Float vs Decimal and Rounding.
Sources
- An Informal Introduction to Python (Python tutorial)
- Lexical analysis: names and keywords (Python language reference)
- PEP 8: Style Guide for Python Code, naming conventions
- Built-in Functions: type() (Python docs)
- What’s New in Python 3.15
- Python downloads page (python.org)





