Table of Contents
What Will You Learn
This guide explains how variables work in Python, including naming rules, assignment, and dynamic typing. You'll learn how to store and update values, use different data types, and avoid common beginner mistakes.
Every program works with data. To store and use this data, variables are used. In a programming language, a variable is considered a fundamental building block. It is a name associated with a specific value. In Python, variables do not require type declaration — everything is determined automatically upon assignment.
What is the Variable in Python?
A variable is a name that refers to an object in memory. It is used to store data that the program operates with: numbers, strings, lists, boolean values, and any other types. When you assign a value to a variable, Python automatically creates an object of the required type and links it to the specified name.
It is important to understand that in Python, variables do not store data directly but refer to objects. This means that the same value can be accessible under different names. This model is based on reference architecture and requires caution, especially when working with mutable data types.
Unlike statically typed languages, Python does not require prior declaration of a variable or specifying its type. Everything happens dynamically at runtime.
Main properties of variables in Python:
- do not require type specification;
- are automatically created upon first assignment;
- are case-sensitive (variables
Name
andname
are different); - can be reassigned at any time;
- refer to an object rather than contain the value themselves.
Understanding that a variable is a name for an object, not just a container, is critically important for proper programming. This principle underlies all data structures and functions in Python.
Naming variables
Variable names are not just textual labels. They are the key to understanding the code, especially if you come back to it after a few days. Therefore, proper naming is not optional but an essential part of clean code.
Python allows the use of Latin letters, digits, and underscores. A name should not start with a digit, or you will get a SyntaxError
. For example,
2value
is invalid, while value2
is correct. Spaces are also not allowed. Instead of total price
, you should write total_price
.
Maintain readability: names should convey meaning. x
, y
, z
are acceptable in short functions, but avoid them in large projects. Do not use
one-letter variables unless they represent something specific, like coordinates or counters.
Assigning Values to Variables
Assignment is the moment when you first link a name with a certain value. In Python, assignment is done using the =
sign. The left side is the variable name, the
right side is the value.
It is important to understand that at the moment of assignment, the variable becomes a reference to an object in memory. This is especially critical when working with mutable structures. You can assign any values: strings, numbers, lists, boolean expressions, and even the result of functions.
Python also allows you to override the value of a variable at any time — the language is dynamically typed. This is convenient but requires responsibility: you shouldn't change the type thoughtlessly during program execution.
Assignment is done using the =
sign. The value can be of any type: string, number, list, boolean, and so on.
name = "Alice"
age = 30
is_admin = True
In this example, the variables name
, age
, and is_admin
receive the values "Alice", 30, and True
respectively.
The same variable can store values of different types at different times.
Multiple Assignments
Multiple assignment allows you to assign values to several variables in a single line. This saves space and makes the code more compact. This approach is often used when unpacking tuples or returning multiple values from functions.
Example: when working with coordinates x, y = 10, 20
instantly creates two variables. This is more convenient than writing two separate lines. You can also assign
the same value to multiple variables simultaneously: a = b = c = None
.
Python supports multiple assignment of values to several variables in one line. This enables writing compact and readable code.
x, y, z = 1, 2, 3
In this example, the variables x
, y
, and z
receive the values 1, 2, and 3 respectively.
You can also assign a single value to multiple variables at once:
a = b = c = 0
in this case, a
, b
, and c
will refer to the same object containing 0. This is useful when you need to initialize several variables with the
same value.
This syntax is often used for initialization.
But it is important to understand: in the case of mutable types, such as lists, all variables will reference the same object.
Getting the Type of Variable
Python provides a built-in function type()
, which helps to determine the type of a variable. This is useful when you're not sure what type you're working with,
especially when debugging complex logic or handling data from external sources.
Example:
x = 5
print(type(x))
y = "Hello"
print(type(y))
In this example, type(x)
will return <class 'int'>
, and type(y)
— <class 'str'>
. This allows you to quickly check
what data type you are dealing with. It is useful when you need to check the variable type before performing operations on it. For example, if you expect a number but receive a
string, it may cause an error.
This check is also used for argument validation inside functions or during testing.
Below is a table of the main data types used when working with variables in Python. These types appear in every program — from simple scripts to large systems. Knowing their features helps to work with data correctly, choose appropriate structures, and avoid common mistakes in calculations, checks, and conversions.
Data Type | Description | Example |
---|---|---|
int |
Integer number (e.g., 0, -1, 100) | x = 42 |
float |
Floating-point number (e.g., 3.14, -2.0) | price = 19.99 |
str |
String of characters in quotes (e.g., 'hello' ) |
name = 'Alice' |
bool |
Boolean value: True or False |
is_ready = True |
list |
Mutable list of values in square brackets | items = [1, 2, 3] |
tuple |
Immutable collection in parentheses | point = (4, 5) |
dict |
Dictionary — key-value pairs in curly braces | person = {'name': 'Bob', 'age': 30} |
set |
Set — unique values without order | unique_nums = {1, 2, 3} |
Note: each data type has its own use cases, behavior, and limitations. This table is the starting point for understanding how memory, references, and logic work in Python.
Type Casting
Type casting is the process of converting a value from one type to another. It is used in arithmetic operations, string concatenation, and user input handling.
For example, if a user inputs a number as a string, it needs to be converted using int()
or float()
. Conversion back is done using str()
.
Errors at this stage occur when a programmer tries to convert a string that cannot be interpreted as a number. For instance, int("abc")
will raise a
ValueError
.
Sometimes you need to explicitly convert a value to another type. This is done using built-in functions:
x = str(10) # Converts to string
y = int("25") # Converts to integer
z = float("5.6") # Converts to float
In this example, x
becomes the string "10", y
becomes the integer 25, and z
becomes the float number 5.6. This helps prevent errors when
working with different data types.
Type conversion is useful when dealing with user input, strings, and arithmetic operations.
Scope of a Variable
Scope is the context in which a variable is accessible. It defines where it can be used. There are two types of scope:
- Global variable — declared outside a function and accessible everywhere.
- Local variable — created inside a function and accessible only within it.
If a variable is declared inside a function body, it is not accessible outside of it. Attempting to access it will raise a NameError
. On the other hand, a global
variable is available in any part of the code, except when you try to modify it inside a function — in that case, you must explicitly declare it with global
.
x = 10 # Global
def test():
y = 5 # Local
print(x)
print(y)
test()
In this example, x
is a global variable accessible in the test()
function, while y
is local and only accessible within it.
Trying to access y
outside the function will cause an error because it is local.
Working with variable scope requires attention. This is especially important in nested functions where name collisions and shadow variables can occur.
Object Reference
In Python, variables are not containers like in other languages. They are references to objects in memory. When you write a = [1, 2, 3]
, the variable
a
points to a list object. If you then write b = a
, both variables will refer to the same list. Modifying it through b
will affect
a
. This behavior often surprises beginners.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
In this example, a
and b
refer to the same list. Changing b
affects a
.
To create a copy of a mutable object, use the .copy()
method, the list()
constructor, slicing, or the copy
module. Ignoring this rule may
lead to hard-to-detect bugs.
Delete a Variable Using del
Deleting a variable with del
frees up the name and the object if no other variables reference it. After deletion, the variable becomes unavailable, and trying to
access it will raise a NameError
. The del
keyword can also be used on list elements or dictionary keys. For example, del my_list[0]
will
delete the first element, and del my_dict['key']
will remove the corresponding key-value pair.
x = 100
del x
# print(x) # NameError: name 'x' is not defined
In this example, the variable x
is deleted using del
. After that, trying to use it will raise a NameError
, because it no longer exists.
But keep in mind:
del
does not always free memory immediately. It depends on whether other references to the object remain.
Common Mistakes Made by Beginners
Practice shows that when learning about variables, beginners often make the same mistakes:
- Using a variable before assigning it a value.
- Assigning a variable a name that matches a built-in function (e.g.,
list
,str
,input
). - Violating scope: trying to use a local variable outside of a function.
- Not understanding that variables are references. A beginner might think they are copying an object, but in reality, they're just creating another reference.
- Using different types without explicit conversion — for example, adding a number and a string without using
int()
orstr()
. - Incorrect order of multiple assignments, especially when variables depend on each other.
- Errors in variable names (misspelled letters, incorrect case).
- Trying to delete a variable using
del
and then using it again without reassigning it.
Frequently Asked Questions About Variables in Python
Do I need to specify a variable's type when creating it?
No, the language determines the type based on the assigned value. If you write x = 10
, Python understands that it's an integer (int
). This is called
dynamic typing. You don't need to declare the type in advance, unlike in Java or C++.
Can I change a variable's type after it's created?
Yes. A variable can be reassigned at any time. You can store a number first, and then a string:
x = 5
x = "five"
This is allowed, but requires caution — especially when handling user data or in long functions.
What happens if I use a variable before it's created?
Python will raise a NameError
. Any variable must be initialized — that is, assigned a value — before it can be used. This rule applies in all versions of the
language.
Why do people say a variable is a reference to an object?
Because in Python, a variable points to a memory location where the object is stored. If you assign a list to a variable a
, and then create b = a
,
both variables will reference the same list. Changes made through b
will affect a
. Understanding this behavior is especially important when working
with mutable objects like lists and dictionaries.