Python Variables Explained: How to Store, Name and Use Data
Every app you've ever used — from Instagram to Google Maps — is constantly juggling data. A username here, a distance there, a price, a temperature, a score. Without a way to temporarily hold that data while the program is running, none of it would be possible. Variables are the most fundamental building block of every program ever written, in every language that exists.
What a Variable Actually Is (And Why Python Makes Them Effortless)
In most older languages like C or Java, you have to tell the computer upfront exactly what kind of data you're planning to store — a number, a word, a decimal — before you can even create the variable. Python throws that ceremony out the window. You just pick a name, use the equals sign, and put your value on the right. Python figures out the type automatically. That equals sign is called the assignment operator. It doesn't mean 'equal to' the way it does in maths — it means 'take the value on the right and store it under the name on the left'. So when you write player_score = 0, you're telling Python: create a box, label it player_score, and put the number 0 inside it. From that line forward, every time Python sees player_score, it looks inside that box and uses whatever's in there. This simplicity is intentional. Python's creator, Guido van Rossum, wanted the language to read almost like plain English, and variable assignment is the clearest example of that philosophy in action.
# ── Creating variables ────────────────────────────────────────── # On the left: the label (variable name) # On the right: the value you want to store # The = sign means ASSIGN, not 'is equal to' player_name = "Alex" # Storing a piece of text (called a string) player_score = 0 # Storing a whole number (called an integer) health_percentage = 100.0 # Storing a decimal number (called a float) is_game_over = False # Storing True or False (called a boolean) # ── Reading variables ──────────────────────────────────────────── # Use print() to display the value stored inside any variable print(player_name) # Python looks inside the box labelled player_name print(player_score) print(health_percentage) print(is_game_over) # ── Updating a variable ────────────────────────────────────────── # You can replace the value inside the box at any time player_score = 50 # The old value (0) is gone; now it holds 50 print(player_score) # Prints the NEW value
0
100.0
False
50
The Rules and Best Practices for Naming Python Variables
Python gives you a lot of freedom with variable names, but there are hard rules you cannot break and soft rules (conventions) that every professional follows. Breaking the hard rules causes an immediate crash. Breaking the conventions means your colleagues will quietly judge you. Hard rules: variable names can only contain letters, numbers, and underscores. They cannot start with a number. They cannot contain spaces. They cannot be one of Python's reserved keywords (like if, for, while, return — these mean something special to Python already). Case matters — age, Age, and AGE are three completely different variables in Python's eyes. The professional convention used across almost all Python code is called snake_case: all lowercase letters, with words separated by underscores. So instead of PlayerHealthPoints, you'd write player_health_points. This is defined in PEP 8 — Python's official style guide — and every serious Python codebase follows it. Good names are the cheapest form of documentation that exists. A variable named d tells you nothing. A variable named days_until_deadline tells you everything.
# ── VALID variable names ───────────────────────────────────────── user_age = 28 # snake_case — the Python standard city_of_birth = "Lagos" # descriptive and readable max_login_attempts = 5 # immediately clear what this stores order_total_usd = 149.99 # units in the name — no ambiguity _internal_counter = 0 # leading underscore = convention for internal use # ── INVALID variable names (these will crash your program) ─────── # 2fast = True # WRONG: cannot START with a number # user-age = 28 # WRONG: hyphens are not allowed # user age = 28 # WRONG: spaces are not allowed # for = 5 # WRONG: 'for' is a reserved Python keyword # ── Case sensitivity demo ──────────────────────────────────────── temperature = 36.6 # This is one variable... Temperature = 100.0 # ...and this is a COMPLETELY different variable TEMPERATURE = -273.15 # ...and so is this — Python treats them separately print(temperature) # 36.6 print(Temperature) # 100.0 print(TEMPERATURE) # -273.15 # ── Name quality comparison ────────────────────────────────────── d = 7 # BAD — what is d? Days? Dollars? Distance? days_until_expiry = 7 # GOOD — crystal clear, zero guessing required
100.0
-273.15
Multiple Assignment, Swapping Values, and Checking Types
Python has a few elegant shortcuts for working with variables that feel almost like magic when you first see them. Multiple assignment lets you create several variables on a single line. You can also assign the same value to multiple variables at once — useful when initialising a group of counters to zero. Then there's the crown jewel: swapping two variables. In most other languages, swapping the values of two variables requires a third temporary variable to act as a middleman. In Python, you do it in one line. Under the hood Python is still using a temporary location, but it hides that complexity from you entirely. Finally, Python gives you the type() function, which tells you exactly what kind of data a variable is currently holding. This is especially useful when you're debugging and something isn't behaving the way you expect — checking the type is often the fastest way to spot the problem.
# ── Assigning multiple variables in one line ──────────────────── # Each name on the left pairs up with the matching value on the right first_name, last_name, age = "Maria", "Santos", 31 print(first_name) # Maria print(last_name) # Santos print(age) # 31 # ── Assigning the same value to multiple variables at once ─────── red_lives = blue_lives = green_lives = 3 # All three teams start with 3 lives print(red_lives, blue_lives, green_lives) # 3 3 3 # ── Swapping two variables — the Python way ────────────────────── team_a_score = 45 team_b_score = 72 print(f"Before swap — Team A: {team_a_score}, Team B: {team_b_score}") # In one line, Python swaps the values with no temporary variable needed team_a_score, team_b_score = team_b_score, team_a_score print(f"After swap — Team A: {team_a_score}, Team B: {team_b_score}") # ── Checking what type of data a variable holds ────────────────── product_name = "Wireless Keyboard" # text product_price = 49.99 # decimal units_in_stock = 200 # whole number is_available = True # boolean print(type(product_name)) # what type is this variable? print(type(product_price)) print(type(units_in_stock)) print(type(is_available))
Santos
31
3 3 3
Before swap — Team A: 45, Team B: 72
After swap — Team A: 72, Team B: 45
<class 'str'>
<class 'float'>
<class 'int'>
<class 'bool'>
| Aspect | Python Variables | Variables in Java / C++ |
|---|---|---|
| Type declaration required? | No — Python infers it automatically | Yes — you must write int age or String name |
| Can the type change after assignment? | Yes — assign a new type freely | No — the type is locked at declaration |
| Syntax to create a variable | age = 25 | int age = 25; |
| Semicolon at end of line? | Never needed | Required in Java/C++ |
| Check variable type at runtime? | type(variable_name) | Not straightforwardly possible |
| Swap two variables elegantly? | a, b = b, a (one line) | Requires a temporary third variable |
🎯 Key Takeaways
- A Python variable is a named label pointing to a value in memory — not a fixed container. The label can be pointed at a completely different value (even a different type) at any time.
- Python's single equals sign = means assignment (store this value), not equality. Use == when you want to compare two values.
- Naming matters more than you think — player_score communicates intent instantly; p does not. Every variable name is a micro-comment about what the code does.
- type() is your debugging best friend — when a variable isn't behaving as expected, call type() on it immediately. Nine times out of ten it's storing '42' (a string) instead of 42 (an integer).
⚠ Common Mistakes to Avoid
- ✕Mistake 1: Using a variable before assigning a value to it — Python throws a NameError: name 'total_price' is not defined — Fix: Always assign a value before you try to use a variable. If you don't know the final value yet, initialise it to a sensible default like 0, 0.0, '', or False.
- ✕Mistake 2: Confusing = (assignment) with == (comparison) — Writing if user_age = 18 instead of if user_age == 18 causes a SyntaxError immediately — Fix: Remember the rule — one equals sign stores a value, two equals signs compares two values. Read = as 'becomes' and == as 'is the same as'.
- ✕Mistake 3: Shadowing a built-in by naming your variable input, list, print, or type — Python does NOT warn you, but the built-in stops working for the rest of the file — Fix: Never use Python's built-in names as variable names. If you're unsure whether a name is reserved, type it in your editor; most editors will highlight it in a different colour to warn you.
Interview Questions on This Topic
- QWhat is the difference between a variable and a value in Python? Can you give a concrete example?
- QPython is described as dynamically typed. What does that mean, and how does it differ from statically typed languages like Java?
- QWhat happens in memory when you reassign a Python variable — for example, you write score = 10 and then score = 20 on the next line? Where does the original value 10 go?
Frequently Asked Questions
Do I need to declare the type of a variable in Python?
No — Python figures out the type automatically from the value you assign. If you write temperature = 36.6, Python knows it's a decimal (float) without you having to say so. This is called dynamic typing and it's one of the features that makes Python so quick to write.
Can a Python variable change its type after it's been created?
Yes, completely. You can write score = 10, and on the very next line write score = 'ten', and Python won't complain. The variable now holds a string instead of an integer. Whether you should do this is a style question — in most cases it's clearer to use a new variable name if the data is conceptually different.
What is the difference between a local variable and a global variable in Python?
A local variable is created inside a function and only exists while that function is running — once the function finishes, the variable disappears. A global variable is created at the top level of your script and exists for the entire life of the program. As a beginner, most of your variables will be local, which is actually the safer and cleaner approach.
Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.