Variables are the starting point for every Python program. They let you store data, give it a name, and use it later. This tutorial walks through everything an absolute beginner needs to know: what variables are, how to create them, the rules for naming them, and how Python handles their types behind the scenes.
If you have never written a line of code before, this is the right place to start. Variables are the single concept that every other Python topic builds on. Once you understand how they work, concepts like functions, loops, and data structures will make far more sense. Every example in this tutorial runs on Python 3.14, the current stable release as of 2026, though the fundamentals covered here apply to every version of Python 3.
What Is a Variable?
A variable is a name that refers to a value stored in your computer's memory. When you write age = 25, you are telling Python to create an integer object with the value 25 and attach the name age to it. From that point forward, any time you use the name age in your code, Python looks up the object it points to and uses that value.
A common beginner misconception is to picture variables as boxes that hold data. The Python language reference describes variables as names that refer to objects. A more accurate mental model is a name tag or label. The data (the object) exists independently in memory. The variable is just a reference attached to it. If you reassign the variable, you move that reference to a different object -- the original object may still exist in memory until Python's reference-counting garbage collector removes it. This "pass by assignment" model is fundamental to how Python works and distinguishes it from languages like C where variables are fixed-size memory locations.
Python has no var, let, or int keyword for declaring variables. A variable is created the instant you assign a value to it with the = operator. This is one of the features that makes Python approachable for beginners.
Creating Your First Variable
The assignment operator in Python is a single equals sign (=). On the left side, you write the name you want to give your variable. On the right side, you write the value.
You can use the type() function to check what type a variable holds at any time. Try running print(type(age)) to see <class 'int'> printed to the console.
message = "Hello, Python"
age = 25
temperature = 98.6
is_active = True
print(message) # Hello, Python
print(age) # 25
print(temperature) # 98.6
print(is_active) # True
Multiple Assignment
Python lets you assign values to multiple variables in a single line. There are two forms of this. The first assigns different values to different names:
# Assign different values to different variables
x, y, z = 10, 20, 30
print(x) # 10
print(y) # 20
print(z) # 30
# Assign the same value to multiple variables
a = b = c = 0
print(a) # 0
print(b) # 0
print(c) # 0
The number of variable names on the left must match the number of values on the right when using the first form. If they do not match, Python raises a ValueError.
Build a valid Python statement that creates a variable called username and assigns it the string "alice":
Naming Rules and Conventions
Python enforces strict rules on what counts as a valid variable name. Breaking these rules causes a SyntaxError before your code even runs. Beyond the enforced rules, the Python community follows naming conventions defined in PEP 8, the official style guide, to keep code consistent and readable.
The Rules (Enforced by the Interpreter)
A variable name must begin with a letter (a-z, A-Z) or an underscore (_). After the first character, the name can contain letters, digits (0-9), and underscores. Names are case-sensitive, so score, Score, and SCORE are three separate variables. You cannot use Python's reserved keywords (like if, for, class, return, or True) as variable names.
# Valid variable names
player_name = "Kira"
_hidden = 42
score2 = 100
totalXP = 9500
# Invalid variable names — these cause SyntaxError
# 2fast = "error" # starts with a digit
# my-score = 10 # contains a hyphen
# class = "Python 101" # uses a reserved keyword
The Conventions (PEP 8 Recommendations)
PEP 8 recommends using snake_case for variable names: all lowercase letters, with words separated by underscores. This keeps names readable and consistent across Python codebases. Single-letter names like x or i are acceptable in short loops or throwaway expressions, but for anything meaningful, a descriptive name makes your code far easier to read and maintain. PEP 8 also explicitly warns against using the lowercase letter l, the uppercase letter O, or the uppercase letter I as single-character variable names because they are visually indistinguishable from the digits 1 and 0 in certain fonts.
- Example
player_score,file_path,max_retries- When to Use
- Variables and function names. This is the standard in Python per PEP 8.
- Example
MAX_CONNECTIONS,PI,BASE_URL- When to Use
- Constants -- values that should not change after they are set. Python does not enforce immutability, but the naming convention signals intent.
- Example
playerScore,filePath,maxRetries- When to Use
- Common in JavaScript and Java, but not standard in Python. Avoid this for variables. PEP 8 specifies snake_case for nearly everything except class names.
- Example
_internal_count,_cache,_helper- When to Use
- A weak "internal use" indicator. PEP 8 says a leading underscore signals that the name is intended for internal use within a module or class. It is not enforced by the interpreter (except that
from module import *skips names starting with_).
This code tries to create three variables and print one of them. One line breaks Python's naming rules. Click the line you think is wrong, then hit check.
2nd_language to second_language or language_2. Python's naming rules require the first character to be a letter or underscore.
Dynamic Typing and Reassignment
Python is a dynamically typed language. This means you do not declare the type of a variable when you create it. The interpreter determines the type at runtime based on the value assigned. This is different from statically typed languages like Java or C++, where you must specify a type (like int age = 25;) before using a variable.
status = 200
print(type(status)) # <class 'int'>
status = "OK"
print(type(status)) # <class 'str'>
status = True
print(type(status)) # <class 'bool'>
In the example above, the variable status starts as an integer, then gets reassigned to a string, and finally to a boolean. No error occurs because Python does not lock a variable to a particular type. Each assignment simply moves the name tag to a new object.
Dynamic typing gives you flexibility, but it also means Python will not stop you from accidentally changing a variable's type. If a function expects an integer and you pass it a string, the error surfaces at runtime -- not before. Use type() to check when you are unsure.
Checking Types with type() and isinstance()
The type() function returns the exact class of an object. The isinstance() function checks whether an object belongs to a particular type (or a tuple of types) and returns True or False.
score = 95.5
# type() returns the exact class
print(type(score)) # <class 'float'>
# isinstance() returns True or False
print(isinstance(score, float)) # True
print(isinstance(score, int)) # False
print(isinstance(score, (int, float))) # True
Under the Hood: How CPython Stores Variables
Every Python object has three properties: an identity (a unique number assigned by the interpreter), a type, and a value. You have already seen type(). The identity is accessible through the id() function, which in CPython returns the object's memory address.
a = 42
b = 42
print(id(a) == id(b)) # True — same object in memory
c = 300
d = 300
print(id(c) == id(d)) # False — two separate objects
This is not a bug. CPython pre-allocates integer objects in the range -5 to 256 when the interpreter starts up. Any variable assigned a value in that range points to the same pre-existing object rather than creating a new one. This optimization is called integer interning, and it saves memory and speeds up comparisons for the small numbers that appear frequently in programs. Integers outside that range get a fresh object on each assignment, which is why id(c) == id(d) returns False in the interactive interpreter.
Never use is to compare variable values. The is operator checks identity (same object in memory), while == checks equality (same value). For value comparisons, always use ==. The only common exception is is None, because None is a guaranteed singleton.
Common Beginner Mistake: Using a Variable Before Assignment
If you reference a variable name that has not been assigned yet, Python raises a NameError. This is one of the first errors new Python programmers encounter.
# This will raise a NameError
print(greeting) # NameError: name 'greeting' is not defined
# Fix: assign the variable first
greeting = "Hello, world"
print(greeting) # Hello, world
The fix is straightforward: always assign a value to a variable before trying to use it. If you see a NameError, check for typos in the variable name -- a misspelled name is a different name entirely, and Python treats it as undefined.
"Code is read much more often than it is written." — Guido van Rossum, PEP 8
Beyond the Basics: Five Things Beginners Ask Next
Once you understand assignment, naming, and typing, five follow-up questions come up in nearly every beginner conversation. Each one is a preview of a larger topic you will explore later, but knowing the answers now will save you from early confusion.
Can I delete a variable?
Yes. The del statement removes a variable's name from the current scope. After deletion, referencing that name raises a NameError, just as if the variable had never been created.
temp = "delete me"
print(temp) # delete me
del temp
print(temp) # NameError: name 'temp' is not defined
In practice, you rarely need del in short scripts. Python's garbage collector automatically reclaims memory when no references to an object remain. The del statement is more useful in long-running programs or when you want to explicitly signal that a name is no longer needed.
Why can't I add a string and a number together?
Python is dynamically typed but also strongly typed. Dynamic typing means you do not declare types in advance. Strong typing means Python refuses to implicitly convert between incompatible types. If you try to concatenate a string and an integer with the + operator, Python raises a TypeError instead of guessing what you meant.
name = "Alice"
age = 30
# This raises TypeError:
# print(name + " is " + age + " years old")
# Fix 1: convert with str()
print(name + " is " + str(age) + " years old")
# Fix 2: use an f-string (preferred)
print(f"{name} is {age} years old")
The built-in functions int(), float(), and str() let you convert between types explicitly. This process is called type casting. The f-string approach (the f"..." syntax) handles the conversion for you automatically and is the preferred method in modern Python.
What are augmented assignments like += and -=?
Python provides shorthand operators that combine an arithmetic operation with assignment. Instead of writing score = score + 10, you can write score += 10. The result is identical, but the shorthand is more concise and signals your intent more clearly.
score = 0
score += 10 # same as score = score + 10 → 10
score -= 3 # same as score = score - 3 → 7
score *= 2 # same as score = score * 2 → 14
print(score) # 14
What is variable scope?
Scope determines where in your code a variable name is visible. A variable created inside a function is local to that function and cannot be accessed outside it. A variable created at the top level of a script is global and can be read from anywhere in the file. If you need to modify a global variable inside a function, you must declare it with the global keyword.
greeting = "hello" # global variable
def change_greeting():
greeting = "goodbye" # local variable — different from the global
print(greeting) # goodbye
change_greeting()
print(greeting) # hello — the global was never changed
This is one of the trickiest concepts for beginners. The key rule: assignment inside a function creates a new local variable, even if a global variable with the same name already exists. This protects you from accidentally modifying global state, but it also means you need to be deliberate when you want a function to update something outside its own scope.
What is the difference between mutable and immutable objects?
Immutable objects (like integers, floats, strings, and tuples) cannot be changed after they are created. Any operation that appears to modify them creates a new object instead. Mutable objects (like lists, dictionaries, and sets) can be changed in place. This distinction matters because when two variables reference the same mutable object, changes through one variable are visible through the other.
# Immutable: strings
word = "hello"
word_upper = word.upper() # creates a NEW string
print(word) # hello — original unchanged
# Mutable: lists
items = [1, 2, 3]
alias = items # both names point to the same list
alias.append(4)
print(items) # [1, 2, 3, 4] — original changed too
Understanding mutability will become essential when you start passing variables to functions and working with data structures. For now, remember that strings and numbers are always safe from accidental modification, but lists and dictionaries are not.
How to Create and Use Variables in Python
Follow these five steps every time you need a new variable in your Python code. This process works whether you are writing a simple script or a larger project.
-
Choose a descriptive name
Pick a name that describes the data the variable will hold. Use lowercase letters and underscores to separate words (snake_case). For example, use
player_scoreinstead ofpsorx. -
Assign a value with the = operator
Write the variable name, followed by a single equals sign, followed by the value. For example:
player_score = 0. Python creates the variable and stores the value the moment this line runs. -
Use the variable in expressions
Reference the variable by name wherever you need its value. For example:
print(player_score)ornew_score = player_score + 10. Python substitutes the stored value each time it encounters the name. -
Reassign when needed
Update the variable by assigning it a new value:
player_score = 42. The old value is replaced. You can even assign a different type, likeplayer_score = "retired", because Python is dynamically typed. -
Verify with type() and print()
Use
type(player_score)to confirm the current data type andprint(player_score)to see the current value. These two functions are your primary debugging tools as a beginner.
"Readability counts." — Tim Peters, The Zen of Python
Python Learning Summary Points
- A variable is a name (a label) that points to an object in memory. You create one with the assignment operator
=. No declaration keyword is needed. - Variable names must start with a letter or underscore, can contain letters, digits, and underscores, are case-sensitive, and cannot be reserved keywords. Use
snake_caseper PEP 8. - Python is dynamically typed: the interpreter determines a variable's type from its assigned value at runtime. Use
type()andisinstance()to inspect types. Reassignment can change a variable's value and even its type at any time.
Variables are the foundation that every other Python concept builds on. With assignment, naming rules, and dynamic typing understood, you are ready to move on to data types, operators, and control flow. Practice creating variables with different types, printing them, checking their types, and reassigning them until the process feels natural.
Frequently Asked Questions
A variable in Python is a name that refers to a value stored in memory. You create one by writing a name, an equals sign, and a value, like age = 25. Python does not require you to declare a type -- the variable is created the moment you assign it.
No. Python has no variable declaration keyword. A variable is created automatically the first time you assign a value to it. This is different from languages like Java or C++ where you must declare the type before use.
Variable names must start with a letter (a-z, A-Z) or an underscore (_). After the first character, names can include letters, digits (0-9), and underscores. Names are case-sensitive, and you cannot use Python reserved keywords like if, for, or class as variable names.
Dynamic typing means Python determines the type of a variable at runtime based on the value assigned to it, rather than requiring the programmer to declare a type in advance. You can reassign a variable to a value of a completely different type without an error.
Use the built-in type() function. For example, type(age) returns <class 'int'> if age holds an integer. This is useful for debugging and confirming that a variable contains the data type you expect.
Yes. You can reassign a variable to a new value at any time using the assignment operator (=). Because Python is dynamically typed, the new value can even be a different type than the original.
snake_case is a naming convention where words are lowercase and separated by underscores, like user_name or total_score. PEP 8, the official Python style guide, recommends snake_case for variable and function names because it improves readability.
Python raises a NameError. Because Python creates variables only upon assignment, referencing a name that has not been assigned yet tells the interpreter that no such variable exists in the current scope.
Yes. Python allows chained assignment like x = y = z = 0, which sets all three variables to the same value. You can also use multiple assignment like a, b, c = 1, 2, 3 to assign different values to different variables in a single line.
The == operator compares the values of two variables (equality), while the is operator checks whether two variables point to the exact same object in memory (identity). For comparing values, always use ==. The is operator is appropriate only for singleton checks like if x is None.
CPython, the standard Python implementation, pre-allocates integer objects in the range -5 to 256 when the interpreter starts. Any variable assigned a value in that range references the same pre-existing object rather than creating a new one. This saves memory and speeds up operations for commonly used small integers. This is an implementation detail, not a language guarantee, so you should never write code that depends on it.
Not exactly. A more accurate way to think about Python variables is as name tags or labels attached to objects in memory. When you assign x = 5, Python creates an integer object 5 and the name x points to it. Reassigning x to a new value moves the label, not the data.
Use the del statement followed by the variable name: del my_variable. After deletion, referencing that name raises a NameError. In practice, you rarely need del because Python's garbage collector automatically frees memory when no references to an object remain.
Python is strongly typed, which means it does not automatically convert between incompatible types. Writing "age: " + 25 raises a TypeError because Python will not silently turn the integer into a string. Use str(25) to convert explicitly, or use an f-string: f"age: {25}".
A local variable is created inside a function and exists only while that function is running. A global variable is created at the top level of a script and can be read from anywhere in the file. Assignment inside a function creates a local variable by default, even if a global variable with the same name exists. To modify a global variable from inside a function, you must declare it with the global keyword.
The += operator is an augmented assignment that adds a value to a variable and reassigns the result in one step. Writing x += 5 is equivalent to x = x + 5. Python also supports -=, *=, /=, and other augmented assignment operators.