How to Declare Variables in Python: A Beginner’s Guide
To declare a variable in Python, write a name, the assignment operator =, and a value — for example, age = 25. No keyword like var, int, or let is needed. Python creates the variable the moment you assign a value to it, and the type is inferred automatically from that value.
There is no separate declaration step in Python. The interpreter binds the name to an object in memory, and the type follows from the object, not the name. This surprises almost every developer coming from Java or C. When you learn how to python declare variable correctly from the start, you avoid the scope and mutability bugs that trip up most beginners.
- Key Takeaway 1: Python has no separate declaration step. Assignment is declaration.
- Key Takeaway 2: Python is dynamically typed, so the same variable name can hold an integer now and a string a line later.
- Key Takeaway 3: PEP 8 mandates
snake_casefor variable names. Ignore this and interviewers will notice. - Key Takeaway 4: Python has no true constants. The convention is ALL_CAPS, and that is enforced by discipline, not the language.
- Key Takeaway 5: Most beginner errors, including
NameErrorandUnboundLocalError, come down to scope confusion, not syntax mistakes.
How Python Variable Declaration Actually Works
Python uses a binding model. When you write score = 95, Python creates an integer object with the value 95 in memory and binds the name score to it. The name is just a label. This is fundamentally different from C, where you reserve a typed slot in memory first and then put a value in it.
Because of this, you can do things that would cause a compile error in Java:
age = 21 # age is an int
age = "twenty-one" # now age is a str, perfectly valid Python
The built-in function id() shows the memory address of the object a name points to. Run id(age) before and after the reassignment and you will see two different addresses. The name moved; the original integer object did not change.
The Reference vs Value Mental Model
This is where most beginners hit their first real bug. When you write b = a and a holds a list, both names point at the same list object. Mutate it through b and a reflects the change.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4] -- surprise!
Integers, floats, strings and booleans are immutable. Lists, dicts and most user-defined objects are mutable. Understanding that distinction is not optional if you are heading toward data work with Pandas and NumPy, where in-place operations on DataFrames catch people off guard constantly.
How to Declare Multiple Variables in Python at Once
Python supports tuple unpacking, which lets you python declare variable assignments on a single line. This is a common pattern in real codebases and a frequent interview question:
x, y, z = 1, 2, 3
name, age, city = "Priya", 24, "Bengaluru"
print(x, y, z) # 1 2 3
You can also assign the same value to multiple names in one statement:
a = b = c = 0
Dynamic Typing vs Static Declaration: Python vs Java
| Feature | Python | Java / C |
|---|---|---|
| Explicit type declaration | Not required | Required |
| Type checked at | Runtime | Compile time |
| Variable reassignment to different type | Allowed | Not allowed |
| Naming convention | snake_case (PEP 8) | camelCase |
| Memory managed by | Garbage collector (CPython) | JVM / manual (C) |
Python’s popularity is not accidental. According to the Stack Overflow Developer Survey 2024, Python ranked as the most used programming language among professional developers for the third consecutive year. The PYPL Index (June 2025) shows Python holding over 30% of the global language popularity share, roughly five times its nearest competitor.
Naming Rules, Type Hints and Constants
Getting variable names right is partly syntax and partly professionalism. Python will reject some names outright and silently allow others that will cause you pain later. Every time you python declare variable names in a team project, naming discipline directly affects code review outcomes.
Python Variable Naming Rules
- Names must start with a letter or underscore.
_scoreis valid;1scoreis not. - Only letters, digits and underscores are allowed. No hyphens, no spaces.
- Names are case-sensitive.
Name,nameandNAMEare three different variables. - Reserved keywords like
if,for,classandreturncannot be used as names. - PEP 8 (Python’s official style guide) mandates
snake_casefor variable and function names:student_marks, notstudentMarks.
student_name = "Priya" # PEP 8 compliant
rollNumber = 42 # valid but not Pythonic
2nd_attempt = True # SyntaxError -- starts with a digit
Adding Type Hints Without Losing Dynamic Typing
PEP 484, introduced in Python 3.5, gave us optional type hints. They do not change runtime behaviour at all. They are annotations for humans and tools like mypy to catch type mismatches before the code runs.
score: int = 95
name: str = "Arjun"
is_enrolled: bool = True
Type hints matter more as your codebase grows. In a team environment or production system, they are close to essential. For a solo learning project, they are good practice but not blocking.
How to Create a Constant in Python
Python has no const keyword. The convention, documented in PEP 8, is to write constants in ALL_CAPS at the top of a module. Nothing stops another developer from reassigning them, so this is purely a signal.
MAX_RETRIES = 5
PI = 3.14159
DATABASE_URL = "postgresql://localhost/mydb"
If you need genuine immutability, you can use a tuple or look at third-party libraries like pydantic for settings management. For most beginner and intermediate work, the ALL_CAPS convention is enough.
How to Declare a Variable in Python: Scope, NameError and Common Bugs
Scope is where beginners spend a disproportionate amount of debugging time. Python resolves names using the LEGB rule: Local, Enclosing, Global, Built-in. If it cannot find the name in any of those scopes, you get a NameError.
NameError: What Causes It
The most common cause is using a variable before assigning it. Typos are the second most common cause, and Python’s error message will tell you the exact name it could not find.
print(total) # NameError: name 'total' is not defined
total = 100
Fix it by ensuring assignment happens before use. Python executes top-to-bottom, so order matters.
UnboundLocalError: The Sneaky One
UnboundLocalError is a subclass of NameError and it is trickier. Python decides at compile time whether a variable in a function is local or global. If you assign to a name anywhere inside a function, Python treats every reference to that name in the function as local, including lines before the assignment.
count = 10
def increment():
print(count) # UnboundLocalError here
count = count + 1
increment()
The fix is either to pass count as an argument or declare global count inside the function. The nonlocal keyword handles the enclosing-scope version of the same problem.
Local vs Global Scope: Quick Reference
| Scope | Where defined | Accessible from | Keyword to modify from inner scope |
|---|---|---|---|
| Local | Inside a function | That function only | N/A |
| Enclosing | Outer function (nested) | Inner function | nonlocal |
| Global | Module level | Anywhere in module | global |
| Built-in | Python interpreter | Everywhere | Not recommended to override |
Interviewers at product companies and GCCs (Global Capability Centres that have expanded rapidly across Bengaluru, Hyderabad and Pune) routinely probe scope and mutability in Python interviews. They are less interested in whether you know the syntax and more interested in whether you understand why a piece of code behaves unexpectedly.
Where Python Variables Fit in Your Career Path
Knowing how to python declare variable correctly is genuinely step one. From here, the path runs through data structures, functions, OOP and then into libraries. If data or AI is your target, the next practical milestone is getting comfortable with Pandas and NumPy, where you will use Python variables constantly to hold Series, DataFrames and arrays.
According to AmbitionBox (January 2025), entry-level Python developers in India earn between Rs 3.5 LPA and Rs 6.5 LPA, while data analysts with Python skills start around Rs 4 LPA and climb quickly with project experience. Naukri.com data from early 2025 shows over 80,000 active job listings in India requiring Python skills, spanning data engineering, machine learning, backend development and automation. Certifications like PCEP and PCAP from the Python Institute can signal foundational knowledge, but Indian hiring managers consistently say portfolio projects carry more weight than certificates alone.
Python appears in job descriptions across data engineering, machine learning, backend development, automation and security scripting. If you are mapping out a broader career move, the guide on how to become a data scientist and the breakdown of data science tools companies are using both give you a realistic picture of what the market actually wants.
At 3.0 University, Python is taught through applied projects, not isolated syntax drills. If you want to build real skills in AI and data science rather than memorise rules, explore the 3.0 University course catalogue and find a programme that gets you working with real data from week one.
Frequently Asked Questions
How do you declare a variable in Python?
Write the variable name, the = operator and a value: age = 25. Python creates the variable immediately. There is no keyword like var or int required. The type is inferred from the value you assign, so age = 25 creates an integer and age = "twenty-five" creates a string.
Do you need to declare variable types in Python?
No. Python is dynamically typed, so types are determined at runtime. You can optionally add type hints like score: int = 95 using the syntax from PEP 484, but they do not enforce anything at runtime. Tools like mypy use them for static analysis. For production code and team projects, type hints are strongly recommended practice.
What are Python variable naming rules?
Names must start with a letter or underscore, contain only letters, digits and underscores, and cannot be Python reserved keywords. Python is case-sensitive. PEP 8 recommends snake_case for variables and functions. Names starting with double underscores have special meaning in classes, so avoid those until you understand name mangling.
Can a Python variable name start with a number?
No. Python variable names must begin with a letter (a-z, A-Z) or an underscore (_). Starting with a digit like 2nd_attempt = True raises a SyntaxError immediately. This rule applies to all identifiers in Python, including function and class names.
How do you create a constant in Python?
Python has no built-in constant type. The PEP 8 convention is to write module-level constants in ALL_CAPS, like MAX_CONNECTIONS = 100. This signals to other developers that the value should not change, but Python will not stop anyone from reassigning it. For strict immutability, use a tuple or a settings management library like pydantic.
What is the difference between a local and global variable in Python?
A local variable is defined inside a function and is only accessible within that function. A global variable is defined at the module level and is accessible anywhere in the module. To modify a global variable from inside a function, you must declare it with the global keyword. For nested functions, use nonlocal to access the enclosing scope.
Why does Python raise NameError or UnboundLocalError?
NameError means Python could not find the variable name in any scope, usually because you used it before assigning it or made a typo. UnboundLocalError is a specific case inside functions: if you assign to a name anywhere in a function, Python treats it as local everywhere in that function, including lines before the assignment. Use global or nonlocal to fix scope issues.
Last updated: June 2025. Reviewed by the 3University editorial team.


