Python Variables: Declare, Assign and Redeclare
Python creates a variable the moment you assign a value to it. Covers naming rules, four assignment patterns, redeclaration across types, scope, and PEP 8 conventions.
Python creates a variable the moment you assign a value to it, with no type declaration required before or after.
This is different from C, Java, and many other languages where you declare a variable’s type before using it. In Python, the name binds to an object, and the object carries the type. Reassign the name later and it points to a new object instead. That single design decision removes entire categories of boilerplate code.
Variable Naming Rules in Python
Every Python variable name follows four rules. Break any one of them and Python raises a SyntaxError or NameError at runtime.
The rules in plain terms:
- A name must start with a letter (a–z, A–Z) or
_. Numbers cannot come first. - After the first character, the name can contain letters, digits, and
_. No spaces, hyphens, or special characters like@,$, or#. - Python keywords (
for,while,if,class,return,True,False,None, and others) are reserved and cannot be used as names. - Names are case-sensitive.
score,Score, andSCOREare three completely different variables.
A quick reference:
| Example name | Valid? | Reason |
|---|---|---|
user_name | Yes | Letters and _ only |
count2 | Yes | Digit allowed after first character |
_temp | Yes | _ is a valid first character |
2count | No | Starts with a digit |
user-id | No | Hyphen is not allowed |
for | No | Reserved keyword |
The standard naming style in Python is snake_case: all lowercase with words joined by _. This matches the PEP 8 naming guidelines, which every placement interview panel in India’s service-sector companies expects CSE and IT candidates to follow.
Assigning Variables in Python
The Python Language Reference defines assignment as binding a name to a value in the current namespace. Four patterns cover the cases that appear in placement coding rounds and academic exercises.
Single value to one variable
x = 9
print(x + 5)
Output:
14
The integer 9 binds to the name x. When Python evaluates x + 5, it retrieves the object 9 through the name x and adds 5, giving 14.
Same value to multiple variables
x = y = z = 9
print(x + y + z)
Output:
27
Python evaluates the right side once and binds all three names to the same object. For immutable types like integers, this is safe and common for zero-initialising multiple counters at once.
Multiple values to multiple variables
x, y, z = 9, 8.3, "Python"
print(x)
print(y)
print(z)
Output:
9
8.3
Python
The right side is a tuple. Python unpacks it left to right. The three names bind to an integer, a float, and a string respectively, all in a single assignment line. The count of names on the left must match the count of values on the right, or Python raises a ValueError.
Reassigning to a new value
x = 9
x = 10
x = 1
print(x + 5)
Output:
6
Only the last assigned value is active at print time. The earlier assignments (x = 9, x = 10) are overwritten in sequence. This is expected behaviour, not a bug. Understanding this is the first step toward debugging logic errors in longer programs.
For more practice with programs that use variable assignment as a foundation, see Python basic programs.
Redeclaring Variables with a New Type
Python is dynamically typed. A name is not locked to a type at the point of first assignment. You can rebind it to a value of any type at any point in the program without any special syntax.
x = "Python is useful"
print(type(x)) # <class 'str'>
x = 10
print(type(x)) # <class 'int'>
x = 3.14
print(type(x)) # <class 'float'>
Each reassignment binds x to a new object. Python’s built-in type() function returns the class of whatever object a name currently points to. Use it during debugging to confirm what a variable actually holds at a given point.
The contrast with statically typed languages makes this clearer:
// Java — type is fixed at declaration
int score = 95;
score = "Pass"; // compile error: incompatible types
# Python — type follows the value
score = 95
score = "Pass" # no error
print(score) # Pass
In a placement technical interview, dynamic typing is a common topic. The expected explanation is: Python resolves the type of a variable at runtime, not at compile time, because Python variables are references to objects, not typed memory slots. The object carries the type; the name does not.
Variables that store running results and switch between types appear in almost every program. A calculator program in Python is a practical example: the result variable may need to hold an integer for addition and a float for division.
Variable Scope: Local and Global
Where you assign a variable determines where it is visible. Two scopes come up consistently in placement questions and coding rounds.
A variable assigned inside a function exists only within that function. It is local to that function’s execution frame and is not accessible from outside.
def greet():
message = "Hello"
print(message)
greet()
# print(message) # NameError — message is not defined here
A variable assigned at the top level of a script is globally accessible throughout that file. To read or modify it from inside a function, use the global keyword.
count = 0
def increment():
global count
count = count + 1
increment()
increment()
print(count) # 2
Without the global declaration inside increment(), Python treats count inside the function as a new local variable. The line count = count + 1 would then raise an UnboundLocalError because the local count has no value before the addition. This is a common bug in placement coding submissions, and naming it by its error type scores well in technical interviews.
Variables that hold comparison targets follow the same scoping logic. See greatest of three numbers in Python for a worked example where three variables hold the candidates and a conditional determines the largest.
Naming Conventions for Readable Code
Python does not enforce naming style beyond the technical rules above. Placement reviewers and technical interviewers, though, assess readability as a signal of professional practice. The standard is PEP 8.
Three naming patterns that apply directly to variables:
- Regular variables:
lowercase_with_underscores. Examples:student_name,total_score,is_valid. This is snake_case and is the dominant Python convention. - Constants:
ALL_CAPS_WITH_UNDERSCORES. Examples:MAX_RETRIES,DEFAULT_TIMEOUT. Python cannot enforce immutability on these names, but the uppercase convention signals to every reader that the value is not meant to change. - Private-by-convention: a leading
_(as in_cache,_internal_counter) signals that the name is internal to a module or class and should not be accessed from outside.
The practical difference in placement submissions is visible. A grader comparing x = int(input()) against student_age = int(input()) will mark the second higher for readability, even when both produce identical output. After years of grading submissions from CSE students across Tier-2 and Tier-3 colleges, FACE Prep’s trainers see the same pattern: better variable names correlate with fewer logic bugs in longer programs, not just better style scores.
Dynamic typing, where score = 95 can become score = "Pass" in the next line without any runtime complaint, is one reason Python is the default language for LLM integrations. If you want to see that in practice, TinkerLLM is a Python-first environment to build and run LLM-powered scripts, starting at ₹299.
Primary sources
Frequently asked questions
Does Python require variable type declarations?
No. Python creates a variable the moment you assign a value to it. The type is inferred from the value and can change on the next assignment.
What are valid Python variable names?
A name can contain letters, digits, and underscores. It must start with a letter or underscore, never a digit. Python keywords like for, while, and if are reserved and cannot be used as variable names.
Can I assign the same value to multiple variables in one line?
Yes. Writing x = y = z = 0 assigns zero to all three variables in a single statement. Python evaluates the right side once and binds all three names to that object.
What happens when I redeclare a variable with a different type?
Python simply rebinds the name to the new value. The old value is garbage-collected if no other name references it. There is no type conflict because Python variables hold references, not typed memory slots.
What is the difference between local and global variables in Python?
A variable assigned inside a function is local by default and is not visible outside it. Use the global keyword inside the function to read and modify a variable defined at module level.
What naming style does PEP 8 recommend for variables?
Lowercase words separated by underscores, known as snake_case. For example, user_name instead of userName or UserName. Constants use all-uppercase with underscores: MAX_RETRIES.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)