By Lisa Tagliaferri and Vinayak Baranwal
Variables are the foundation of almost every Python program you will write. Without them, you cannot store user input, hold the results of calculations, or pass data between conditional statements and for loops. This tutorial covers variable basics in Python 3: how to declare and reassign them, naming rules and conventions, data types and the type() function, scope, constants, and common mistakes so you can use variables confidently in your own code.
name = value. No type declaration is required.type() to inspect a variable’s type. Python uses dynamic typing and infers types at assignment.global only when necessary. Constants are named with SCREAMING_SNAKE_CASE; typing.Final can document non-reassignment.list or str.A variable is a symbolic name that refers to a value stored in memory. You use the variable name in your code to read or update that value instead of repeating the value itself.
You can think of a variable as a label tied to a value. For example, storing the integer 103204934813 in a variable lets you reuse it without retyping the number:

Info: To follow along, open a Python interactive shell with the python3 command and run the examples after the >>> prompt.
my_int = 103204934813
print(my_int)
103204934813

The label has the name my_int and is tied to the integer 103204934813. Variables let you do math and other operations using the name:
print(my_int - 813)
103204934000
You declare a variable in Python by writing the variable name, the assignment operator =, and the value. No separate declaration or type keyword is required.
An assignment statement has three parts: the variable name, the assignment operator =, and the value. Together they create (or initialize) the variable. For example:
x = 76 + 145
print(x)
221
The variable x is set to the result of 76 + 145, which is 221. In Python, the variable must always be on the left side of =; the expression is evaluated and then bound to the name. You can start using the variable immediately after assignment.
What happens if you flip the sides of the assignment operator:
76 = x
SyntaxError: cannot assign to literal
The variable must always be on the left side of =; placing a value on the left causes a SyntaxError.
In Python, a variable does not exist until you assign it a value. There is no way to declare a variable name without also giving it a value. If you reference a name before assigning it, Python raises a NameError.
print(my_variable)
my_variable = 10
NameError: name 'my_variable' is not defined
Assignment must happen before any reference to that name in the current scope.
If you need a variable name to exist before you have a meaningful value for it, assign it None. None is Python’s way of representing the absence of a value.
result = None
print(result)
print(type(result))
None
<class 'NoneType'>
You can reassign result to a real value later once it is available, for example after a calculation or user input.
Variable names must be one word (no spaces), contain only letters, digits, and underscores, and must not start with a digit.
The following table summarizes valid and invalid names:
| Valid | Invalid | Why invalid |
|---|---|---|
my_int |
my-int |
Hyphens are not allowed |
int4 |
4int |
Cannot start with a digit |
MY_INT |
$MY_INT |
Only _ is allowed, no symbols |
another_int |
another int |
No spaces; must be one word |
Variable names are case-sensitive: my_int, MY_INT, My_Int, and mY_iNt are four different variables. Using very similar names in one program makes bugs and confusion more likely.
Conventional style in Python is lowercase with underscores (snake_case). Other styles are valid but less common:
| Conventional style | Unconventional style | Why unconventional |
|---|---|---|
my_int |
myInt |
camelCase not standard |
int4 |
Int4 |
Leading capital not standard |
my_first_string |
myFirstString |
camelCase not standard |
Be consistent. If an existing project uses camelCase, follow that style. PEP 8 is the standard Python style guide and favors readability and consistency.
Variables in Python can hold values of different data types. Common built-in types include integers, floats, strings, and booleans. Python infers the type at assignment time; you do not declare it.
You can inspect the type of any value or variable with the built-in type() function:
my_int = 103204934813
my_flt = 45.06
my_string = 'Hello, World!'
my_bool = 5 > 9
print(type(my_int))
print(type(my_flt))
print(type(my_string))
print(type(my_bool))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
The following table shows the same variables and their type() result:
| Variable | Assigned value | type() result |
|---|---|---|
my_int |
103204934813 |
<class 'int'> |
my_flt |
45.06 |
<class 'float'> |
my_string |
'Hello, World!' |
<class 'str'> |
my_bool |
5 > 9 (False) |
<class 'bool'> |
Variables can also refer to collections. For example, a variable can hold a list:
my_list = ['item_1', 'item_2', 'item_3', 'item_4']
print(my_list)
print(type(my_list))
['item_1', 'item_2', 'item_3', 'item_4']
<class 'list'>
For string variables, you can use Python string functions and indexing and slicing. Modern string formatting with f-strings embeds variable values directly:
name = "Sammy"
score = 42
message = f"Player {name} scored {score} points."
print(message)
Player Sammy scored 42 points.
The f prefix before the string allows expressions in curly braces to be evaluated and inserted into the string.
Python variables can be reassigned to new values at any time. The same name can refer to a different value, and even a different type, after reassignment.
This is dynamic typing: the type is inferred from the value at assignment time, not from a declaration. Reassignment is useful for accepting new values (for example from user input) or updating a value as the program runs, such as a score that increases each round.
x = 76
print(x)
x = "Sammy"
print(x)
76
Sammy
Reassignment changes what a variable name refers to. Whether the value itself can be changed in place depends on whether the type is mutable or immutable.
Immutable types (e.g. int, float, str, tuple) cannot be changed in place. Reassigning the variable gives it a new value; the old value is unchanged. Mutable types (e.g. list, dict) can be modified in place without reassigning the variable.
Example with an integer (immutable): reassignment produces a new object. You can confirm this with id():
a = 10
print(id(a))
a = 20
print(id(a))
140704199837472
140704199837792
The two different id values confirm that a no longer refers to the original object; Python created a new one holding 20. The exact numbers will differ per system.
Example with a list (mutable): in-place modification keeps the same object. Again, id() shows the difference:
items = ['apple', 'banana']
print(id(items))
items.append('cherry')
print(id(items))
2025123456789
2025123456789
The matching id values confirm that append() modified the existing list object rather than creating a new one.
If you reassign items to a new list, the variable then refers to that new list; the old list is unchanged and may be discarded if nothing else references it.
You can assign one value to several variables in one statement, or assign several values to several variables in one line.
Same value to multiple variables:
x = y = z = 0
print(x)
print(y)
print(z)
0
0
0
This pattern is useful when you need several counters, scores, or flags that should all start at the same value before a loop or scoring system updates them individually. For example, you might set wins = losses = ties = 0 at the start of a game, then increment each variable as rounds complete.
x, y, and z all refer to the integer 0. Multiple values to multiple variables (order must match):
j, k, l = "shark", 2.05, 15
print(j)
print(k)
print(l)
shark
2.05
15
j gets "shark", k gets 2.05, and l gets 15. Use this when it keeps the code clear; avoid sacrificing readability for fewer lines.
A variable’s scope is the part of the program where that name is defined and accessible. Variables defined outside functions are global; variables defined inside a function are local to that function.
Why this matters: using the wrong scope leads to NameError or to reading and updating the wrong variable. Prefer local variables and explicit arguments and return values; overusing global variables makes code harder to reason about and test.
glb_var = "global"
def var_function():
lcl_var = "local"
print(lcl_var)
var_function()
print(glb_var)
local
global
The function printed local because lcl_var was defined and assigned inside it. It did not print anything about glb_var because glb_var was never referenced inside the function body.
glb_var is defined at module level, so it is visible inside the function too:
glb_var = "global"
def var_function():
lcl_var = "local"
print(lcl_var)
print(glb_var)
var_function()
print(glb_var)
local
global
global
A local variable is not visible outside the function:
glb_var = "global"
def var_function():
lcl_var = "local"
print(lcl_var)
print(lcl_var)
NameError: name 'lcl_var' is not defined
The same name can be used for both a global and a local variable. Inside the function, the local name takes precedence:
num1 = 5
def my_function():
num1 = 10
num2 = 7
print(num1)
print(num2)
my_function()
print(num1)
10
7
5
The function prints the local num1 (10) and num2 (7). After the call, print(num1) prints the global num1 (5).
You can assign to a global variable inside a function using the global statement:
def new_shark():
global shark
shark = "Sammy"
new_shark()
print(shark)
Sammy
Use global sparingly. Relying on it often makes control flow and testing harder; passing arguments and returning values is usually clearer. If you only read a variable inside a function and never assign to it, that variable is the global one; to have a local variable, you must assign to it in the function body.
A common mistake is trying to modify a global variable inside a function without declaring it global. Python sees the assignment inside the function and treats the variable as local for the entire function body, even lines before the assignment. This causes an UnboundLocalError:
counter = 0
def increment():
counter = counter + 1
increment()
UnboundLocalError: local variable 'counter' referenced before assignment
To modify the global variable, declare it with the global statement before referencing it:
counter = 0
def increment():
global counter
counter = counter + 1
increment()
print(counter)
1
Without global counter, Python treats counter as a local variable the moment it sees the assignment counter = counter + 1, which means the right-hand side tries to read a local variable that does not exist yet.
Constants are names that you intend not to change. Python does not enforce immutability; convention and optional type hints communicate intent.
The idiomatic approach is to use SCREAMING_SNAKE_CASE for constant names and, when you want to signal non-reassignment, the typing.Final annotation:
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
# Optional: signal that PI should not be reassigned (tools can check this)
from typing import Final
PI: Final[float] = 3.14159
MAX_RETRIES and DEFAULT_TIMEOUT are constants by convention. PI is annotated as Final; reassigning it is still allowed at runtime, but type checkers and linters can flag it. Using SCREAMING_SNAKE_CASE for constants helps readers distinguish them from regular variables.
Avoiding these mistakes reduces bugs and makes code easier to maintain.
Case sensitivity: my_var and My_Var are different. A typo in case causes NameError or uses the wrong variable.
count = 5
print(Count)
NameError: name 'Count' is not defined
Unintentional reassignment: Reusing a variable name for a different purpose overwrites the original value and can break logic that still expects the old value.
total = 100
total = total - 20 # intended: deduct 20
total = 50 # accidental: overwrites the calculated value
print(total)
50
The third line silently discards the result of the subtraction, so the program continues with 50 instead of the expected 80. This kind of bug produces no error and is hard to spot on a quick read.
Shadowing built-in names: Using names like list, str, dict, or id for your own variables hides the built-in functions or types and can cause subtle errors:
list = [1, 2, 3]
other = [4, 5]
combined = list(other)
TypeError: 'list' object is not callable
Here list refers to your list, not the built-in list constructor. Use names like my_list or items instead.
A common use of variables is to store user input and then use it in output or calculations. The input() function reads a line from the user and returns it as a string:
name = input("Enter your name: ")
age_str = input("Enter your age: ")
age = int(age_str)
print(f"Hello, {name}. In 10 years you will be {age + 10}.")
Example session:
Enter your name: Alex
Enter your age: 25
Hello, Alex. In 10 years you will be 35.
name holds the string from the first prompt. age_str holds the second input; int(age_str) converts it to an integer for the calculation. The result is printed with an f-string.
How do you declare a variable in Python?
You declare a variable by writing the variable name, the assignment operator =, and the value (e.g. x = 5). No type keyword or separate declaration is needed. The variable exists as soon as the assignment runs.
Does Python require variable types to be declared?
No. Python uses dynamic typing and infers the type from the value at assignment time. You can check the type of any value or variable with the built-in type() function.
Can a Python variable change type?
Yes. Reassigning a variable to a value of a different type is allowed. For example, x = 10 followed by x = "hello" is valid; x first refers to an integer, then to a string.
What are the rules for naming variables in Python?
Names must be one word (no spaces), contain only letters, digits, and underscores, and must not start with a digit. They are case-sensitive. By convention, use lowercase with underscores (snake_case).
Are variables case-sensitive in Python?
Yes. my_var, My_Var, and MY_VAR are three different variables. Using the wrong case causes a NameError if the name is not defined.
Variables are the basic building blocks for storing and using data in Python 3. This tutorial covered declaration and reassignment, naming rules and conventions, data types and the type() function, scope, constants, and common mistakes. Use variables to hold user input, results of calculations, and values you pass between functions and classes. Apply consistent naming and scope choices to keep your code clear and maintainable.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Python is a flexible and versatile programming language that can be leveraged for many use cases, with strengths in scripting, automation, data analysis, machine learning, and back-end development. It is a great tool for both new learners and experienced developers alike.
Browse Series: 36 tutorials
Community and Developer Education expert. Former Senior Manager, Community at DigitalOcean. Focused on topics including Ubuntu 22.04, Ubuntu 20.04, Python, Django, and more.
Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
def new_shark():
global shark = "Sammy" #Assign variable as global — SyntaxError: invalid syntax
#Print global variable shark
print(shark)
should be changed to
def new_shark():
global shark #Assign variable as global on its own line
shark = "Sammy"
new_shark() #Call new_shark() function
#Print global variable shark
print(shark)
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.