☰

Variables in Python Programming

Variables in Python: Rules, Types and Multiple Assignment

Every program you will ever write has to remember things. A name, a price, a count of how many times a loop has run. In Python, a variable is how you give such a thing a name so that you can use it again.

Variables look easy, and they are, but there are a few ideas that trip up beginners for months. Does Python need you to declare the type? What names are allowed? Why does one list change when you only edited another? And why does x, y, z = "One" not do what many tutorials say? Getting these right early saves a lot of confusion later.

This tutorial explains variables from the start. We cover how to create one, the types of values it can hold, the naming rules, multiple assignment, how to print variables, type conversion, and scope. We also show the exact error that each common mistake gives. Every example was run on Python 3.13, and the output you see is the real output.

What are Variables in Python?

A variable is a name that refers to a value stored in your computer’s memory. You create it the moment you give it a value, with the equals sign. Python has no separate declaration command, such as int x in other languages.

In some other languages, a variable is the name of a memory location. That is a misleading picture of Python. In Python, a variable is a name that points to an object. The value lives in the object, and the name is a label on it. This matters, and we show why in the section on names and objects below.

Python Variables Example

Here is a short example with its output:

python
x = 10
z = "PrwaTech"
y = 'Python'
print(x, z, y)
output
10 PrwaTech Python

Notice that you do not need a type, or a semicolon at the end. You can use single or double quotes for text, and both are the same.

Data Types a Variable Can Hold

A variable can point to any kind of value. The most common ones are whole numbers, decimals, text, True or False, and None, which means no value.

python
x = 10
y = 2.5
name = "Asha"
passed = True
nothing = None
print(type(x).__name__, type(y).__name__, type(name).__name__, type(passed).__name__, type(nothing).__name__)
output
int float str bool NoneType
Common Python data types
Type Example Used for
int 10 Whole numbers
float 2.5 Decimal numbers
str “Asha” Text
bool True Yes or no answers
NoneType None A value that means nothing yet

Python Is Dynamically Typed

Python is a dynamically typed language, which means a name has no fixed type. The object it points to has one. You can point the same name to an object of another type later.

python
x = 10
print(type(x).__name__)
x = "ten"
print(type(x).__name__)
output
int
str

This is flexible, but it also means that Python will not warn you if you change a type by accident. In big programs, type hints help. We show them near the end.

Rules for Naming Variables in Python

Here is the correct set of rules.

  • A name must start with a letter or an underscore. It cannot start with a digit.
  • The rest can have letters, digits and underscores. No spaces, no hyphens, no other symbols.
  • Names are case sensitive. Total, total and TOTAL are three different names.
  • A name cannot be a Python reserved word, such as class, if or for.

Valid Names

python
age = 30
_count = 2
total_marks = 450
student2 = "Ravi"
Name = "Asha"
name = "Meena"
print(Name, name)
output
Asha Meena

Here Name and name are two different variables, which is why both print.

Invalid Names and the Errors They Give

A name that starts with a number:

python
2student = "Ravi"
output
SyntaxError: invalid decimal literal (<string>, line 1)

A name with a space:

python
total marks = 450
output
SyntaxError: invalid syntax (<string>, line 1)

A name with a hyphen. Python reads the minus sign as maths:

python
my-name = "Asha"
output
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? (<string>, line 1)

A reserved word:

python
class = "Python"
output
SyntaxError: invalid syntax (<string>, line 1)

Case Sensitivity

If you create Total and then ask for total, Python does not find it:

python
Total = 10
print(total)
output
NameError: name 'total' is not defined

Reserved Words

Python 3.13 has 35 reserved words, also called keywords. You can list them yourself:

python
import keyword
print(len(keyword.kwlist))
print(keyword.kwlist)
output
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']

You cannot use these as names. Python also has built in names that are not keywords, such as list, str, print and sum. Python lets you use them as variable names, but that hides the original, and it breaks later code. This is called shadowing:

python
list = [1, 2, 3]
list("ab")
output
TypeError: 'list' object is not callable

After list = [1, 2, 3], the name list no longer means the list type, so list("ab") fails. Pick a different name, such as numbers or items.

Naming Style

The Python style guide, PEP 8, says to write variable names in lower case, with words joined by underscores, such as total_marks. Use names that say what the value is. A name such as total_marks is much clearer than tm, or x, when someone reads your code next month.

Constants in Python

Python has no true constants. By habit, programmers write the names of values that should not change in capital letters, such as MAX_MARKS. Python does not stop you from changing them:

python
MAX_MARKS = 100
MAX_MARKS = 90
print(MAX_MARKS)
output
90

The capital letters are a message to other programmers, and not a rule that Python enforces.

Names and Objects: What Really Happens When You Assign

When you write b = a, Python does not copy the value. It makes b point to the same object as a. For numbers and text, that is safe, because those objects cannot be changed. When you give b a new value, it just points somewhere else:

python
a = 5
b = a
print(a is b, id(a) == id(b))
b = 6
print(a, b)
output
True True
5 6

With a list, the object can be changed, and that is where beginners get surprised. Both names point to the same list, so a change through one shows in the other:

python
first = [1, 2, 3]
second = first
second.append(4)
print(first)
print(first is second)

third = first.copy()
third.append(5)
print(first)
print(third)
output
[1, 2, 3, 4]
True
[1, 2, 3, 4]
[1, 2, 3, 4, 5]

Use the copy method when you want a separate list. This is one of the most common sources of bugs for a beginner, and it follows straight from the idea that a variable is a name, and not a box.

Multiple Variable Assignment in Python

Many Values to Many Names

You can give several names their values in one line. The number of names must match the number of values.

python
x, y, z = "One", "Two", "Three"
print(x, y, z)
output
One Two Three

If they do not match, Python raises an error:

python
x, y, z = 1, 2
output
ValueError: not enough values to unpack (expected 3, got 2)

One Value to Many Names

It is easy to think that x, y, z = "One" gives the same value to all three names. It does something else, and it works only by luck, because One has three letters:

python
x, y, z = "One"
print(x, y, z)
output
O n e

Python took the text and split it into letters. With a text of a different length, it fails:

python
x, y, z = "Python"
output
ValueError: too many values to unpack (expected 3)

To give the same value to several names, use chained assignment:

python
x = y = z = "One"
print(x, y, z)
output
One One One

A warning for lists. With x = y = z = [], all three names point to the same list, as we saw above. For lists, give each name its own.

Swapping Two Variables

A very Pythonic trick. You do not need a third variable.

python
a, b = 1, 2
a, b = b, a
print(a, b)
output
2 1

Unpacking a List or Tuple

You can pull the items out of a list or tuple into names in one line.

python
name, age = ["Asha", 29]
print(name, age)
r, g, b = (255, 128, 0)
print(r, g, b)
output
Asha 29
255 128 0

A star takes the items that are left over:

python
first, *middle, last = [10, 20, 30, 40, 50]
print(first, middle, last)
output
10 [20, 30, 40] 50

Output Variables: How to Print Them

The print function shows a value on the screen. The plus sign joins text, and joining text and a number gives an error. Here is a working example with the output:

python
x = 4
print(x)
y = "Python"
print(y)
z = "Python"
print("hello", z)
k = "Hello"
l = k + z
print(l)
a = 3
b = 4
print(a + b)
output
4
Python
hello Python
HelloPython
7

A common slip is an extra plus sign in front of a name, such as print("hello", +z). It gives this error:

python
z = "Python"
print("hello", +z)
output
TypeError: bad operand type for unary +: 'str'

A comma in print puts a space between the items, and the plus sign joins text with no space. That is why you get HelloPython, with no space, in the joined line above.

Joining Text and a Number

This is the error you get when you join text and a number with a plus sign:

python
print("Age: " + 30)
output
TypeError: can only concatenate str (not "int") to str

There are three ways to fix it. The last is the best, and is available from Python 3.6:

python
age = 30
print("Age: " + str(age))
print("Age:", age)
print(f"Age: {age}")
output
Age: 30
Age: 30
Age: 30

An f string starts with the letter f, and puts the variable inside curly brackets. It is easier to read, and there is no need to convert the number.

Changing the Separator

By default print separates items with a space. The sep argument changes that.

python
x, y, z = "One", "Two", "Three"
print(x, y, z, sep=", ")
print(x + y + z)
output
One, Two, Three
OneTwoThree

A Small Real Example

Here variables hold a price and a quantity, and the answer is built from them.

python
price = 250
qty = 3
total = price * qty
print(f"Total for {qty} items: Rs.{total}")
output
Total for 3 items: Rs.750

Type Conversion

Text that looks like a number is still text. Use int, float or str to convert it. This matters most for input from a user or from a file, which always arrives as text.

python
s = "42"
n = int(s)
print(n + 1)
print(float("2.5") * 2)
print(str(3.0) + " units")
output
43
5.0
3.0 units

If the text cannot be turned into a number, Python raises an error:

python
int("abc")
output
ValueError: invalid literal for int() with base 10: 'abc'

Variable Scope: Local and Global

Where you create a variable decides where you can use it. A variable made inside a function is local, and exists only while the function runs. A variable made outside is global. If a function makes a name that is the same as a global one, it creates a new local one, and leaves the global one alone:

python
total = 100

def show():
    total = 5
    print("inside:", total)

show()
print("outside:", total)
output
inside: 5
outside: 100

To change a global variable from inside a function, you must say so with the global keyword:

python
count = 0

def add_one():
    global count
    count += 1

add_one()
add_one()
print(count)
output
2

A local variable cannot be used outside its function:

python
def f():
    inner = 1

f()
print(inner)
output
NameError: name 'inner' is not defined

Use global sparingly. It is usually cleaner to pass values into a function and return the answer.

Deleting a Variable

The del statement removes a name. After that, using it is an error. This is rarely needed, but it is good to know.

python
x = 5
del x
print(x)
output
NameError: name 'x' is not defined

Type Hints: A Note for Larger Programs

Python lets you write the expected type next to a name. This is called a type hint. Python does not enforce it when the program runs, but editors and tools such as mypy use it to warn you.

python
age: int = 30
name: str = "Asha"
print(age, name)
age = "thirty"
print(age)
output
30 Asha
thirty

Notice that Python let us put the text thirty in a variable that was hinted as int. A hint is a note, and not a lock. The tool mypy was not run for this page, so test it in your own setup.

Common Variable Errors and How to Fix Them

Variable errors and fixes
Error Usual cause Fix
NameError: name is not defined A spelling or case mistake, or using a name before creating it Check the spelling and the order
SyntaxError: invalid decimal literal A name that starts with a number Start with a letter or an underscore
SyntaxError: invalid syntax A space in a name, or a reserved word used as a name Use an underscore, or a different word
SyntaxError: cannot assign to expression A hyphen in a name Use an underscore
TypeError: can only concatenate str to str Joining text and a number with a plus sign Use str(), a comma, or an f string
TypeError: bad operand type for unary plus A stray plus sign before a text value Remove the plus sign
ValueError: not enough values to unpack Fewer values than names in a multiple assignment Match the number of names and values
TypeError: object is not callable A built in name such as list was used as a variable Rename the variable
SyntaxError on a curly quote Code copied from a web page or a Word file Type straight quotes in your editor

Best Practices for Python Variables

  • Use clear, lower case names with underscores, such as total_marks.
  • Do not reuse built in names, such as list, str, sum or max.
  • Use capital letters for values you treat as constants, such as MAX_MARKS.
  • Keep variables local when you can, and pass values into functions.
  • Do not use one letter names, except for short loops and maths.
  • When you copy a list, use copy, and not an equals sign.

Practice Exercises

  1. Create variables for your name, your age and your city, and print one sentence with them, using an f string.
  2. Create two numbers, and swap them in one line. Print them before and after.
  3. Make a list, assign it to a second name, change the second, and print both. Then repeat with a copy.
  4. Try each invalid name from this page, and read the error message.
  5. Write a function that has a local variable with the same name as a global one. Print both, and explain why they are different.

Complete Script to Run Yourself

Here is the full script that was used to test every example on this page. It ran on Python 3.13. The blocks that show an error are written to fail on purpose, so run those one at a time, or wrap them in try and except.

python
# first
x = 10
z = "PrwaTech"
y = 'Python'
print(x, z, y)

# types
x = 10
y = 2.5
name = "Asha"
passed = True
nothing = None
print(type(x).__name__, type(y).__name__, type(name).__name__, type(passed).__name__, type(nothing).__name__)

# dynamic
x = 10
print(type(x).__name__)
x = "ten"
print(type(x).__name__)

# ident
a = 5
b = a
print(a is b, id(a) == id(b))
b = 6
print(a, b)

# alias
first = [1, 2, 3]
second = first
second.append(4)
print(first)
print(first is second)

third = first.copy()
third.append(5)
print(first)
print(third)

# valid
age = 30
_count = 2
total_marks = 450
student2 = "Ravi"
Name = "Asha"
name = "Meena"
print(Name, name)

# bad1
2student = "Ravi"

# bad2
total marks = 450

# bad3
my-name = "Asha"

# bad4
class = "Python"

# kw
import keyword
print(len(keyword.kwlist))
print(keyword.kwlist)

# case
Total = 10
print(total)

# shadow
list = [1, 2, 3]
list("ab")

# const
MAX_MARKS = 100
MAX_MARKS = 90
print(MAX_MARKS)

# multi
x, y, z = "One", "Two", "Three"
print(x, y, z)

# multi_str
x, y, z = "One"
print(x, y, z)

# multi_str_err
x, y, z = "Python"

# multi_err2
x, y, z = 1, 2

# chain
x = y = z = "One"
print(x, y, z)

# swap
a, b = 1, 2
a, b = b, a
print(a, b)

# star
first, *middle, last = [10, 20, 30, 40, 50]
print(first, middle, last)

# seq
name, age = ["Asha", 29]
print(name, age)
r, g, b = (255, 128, 0)
print(r, g, b)

# out1
x = 4
print(x)
y = "Python"
print(y)
z = "Python"
print("hello", z)
k = "Hello"
l = k + z
print(l)
a = 3
b = 4
print(a + b)

# out_err_plus
z = "Python"
print("hello", +z)

# out_err_mix
print("Age: " + 30)

# out_fix
age = 30
print("Age: " + str(age))
print("Age:", age)
print(f"Age: {age}")

# sep
x, y, z = "One", "Two", "Three"
print(x, y, z, sep=", ")
print(x + y + z)

# convert
s = "42"
n = int(s)
print(n + 1)
print(float("2.5") * 2)
print(str(3.0) + " units")
print(int("abc"))

# convert_ok
s = "42"
n = int(s)
print(n + 1)
print(float("2.5") * 2)
print(str(3.0) + " units")

# scope
total = 100

def show():
    total = 5
    print("inside:", total)

show()
print("outside:", total)

# scope_global
count = 0

def add_one():
    global count
    count += 1

add_one()
add_one()
print(count)

# scope_err
def f():
    inner = 1

f()
print(inner)

# undefined
print(not_defined)

# delete
x = 5
del x
print(x)

# hints
age: int = 30
name: str = "Asha"
print(age, name)
age = "thirty"
print(age)

# fstr_calc
price = 250
qty = 3
total = price * qty
print(f"Total for {qty} items: Rs.{total}")

A variable is only a name, and once that idea is clear, many Python puzzles stop being puzzles. Type the examples, break them on purpose, and read the error each time. Then move on to data types in detail, starting with numbers and strings, and then lists and dictionaries.

Popular Tags:

Variables in Python Programming