Variables vs Constants in Python – A Beginner’s Guide

Illustration comparing a changeable Python variable (score on whiteboard) with an unchanging constant (pi engraved in stone)

Table of Contents

Imagine a game scoreboard: the score can change with every point scored, but the number of players on each team is fixed. In programming terms, the score is like a variable (it can change), and the number of players is like a constant (it stays the same).

In this beginner-friendly guide, we’ll compare variables and constants in Python (latest version) using real-world analogies, simple code snippets, and even a peek at how other languages like Java and C++ handle constants. By the end, you’ll understand the key differences in syntax, behavior, and best practices for using variables and constants in your code.

What Are Variables in Python?

In math class, a variable might be a symbol x that can take on different values. In programming, a variable is essentially a name that refers to a value stored in memory, and that value can change over time. You create a variable in Python by assigning a value to a name using the = sign. There’s no need to specify a type – Python figures it out on the fly (this is called dynamic typing, meaning the same variable can hold different types of data over its lifetime)​

In plain terms, think of a variable as a labeled box or a whiteboard: you can write something on it, erase it, and write something new later. For example, you might have a variable for the score in a game, and as the game progresses, you update this variable.

# Python variable example
score = 0              # create a variable 'score' and assign 0
print(score)           # Output: 0

score = 7              # change the value of 'score'
print(score)           # Output: 7

score = score + 3      # variables can be used in expressions
print(score)           # Output: 10

In this code, we first set score to 0, then later change it to 7, and then update it to 10. Python has no issue with us changing the value of score – that’s exactly what variables are for. You don’t even have to declare the variable type; just doing score = 0 is enough to create it. (If you’re coming from or curious about other languages like Java, note that in Java you’d have to declare the type, e.g., int score = 0;, but in Python that’s not needed​.)

A variable in Python can even refer to different types of data over its life. For instance, you could set score = 10 (an integer) and later do score = “Game Over” (a string) – Python won’t complain. This flexibility is part of Python’s design, but it also means it’s up to you to keep track of what type of data a variable is supposed to hold at any given time.

What Are Constants in Python?

Now, what about constants? In everyday life, a constant might be something like the number of minutes in an hour (always 60) or the value of π (pi) ~3.14. These values don’t change. In programming, a constant is meant to be a name that should not change its value during the program’s execution. The key difference from a variable is just that – once a constant is set, we treat it as a fixed value.

Here’s an important thing to know: Python, by design, does not have true constants. Unlike some languages, Python doesn’t have a keyword (like const or final) to make a variable unchangeable. In Python, constants are mostly a matter of convention and programmer discipline. By convention, we use all UPPERCASE letters (often with underscores) to name constants. This signals to anyone reading the code (including your future self) that “this value should not be changed once set.” For example, you might see a constant for maximum connection attempts written as MAX_RETRIES = 5. The name being uppercase is a big hint that you shouldn’t reassign it elsewhere in the code.

Let’s look at a Python constant example:

# Python constant example (by convention, not truly enforced by the language)
MAX_SPEED_KM_PER_HR = 300   # suppose this is the max speed of a vehicle in km/h
print(MAX_SPEED_KM_PER_HR)  # Output: 300

# ... later in the code ...
MAX_SPEED_KM_PER_HR = 500   # Python will **allow** this reassignment (not a true constant!)
print(MAX_SPEED_KM_PER_HR)  # Output: 500

We defined MAX_SPEED_KM_PER_HR as 300. Ideally, because it’s a constant by convention, we expect it to stay 300. However, Python won’t stop us from doing MAX_SPEED_KM_PER_HR = 500 later. When we run this code, it will actually print 500. This shows that in Python, the idea of a constant is not enforced by the language – it’s a promise or a guideline we follow.

You might be wondering, “If Python doesn’t stop me from changing a constant, why bother with constants at all?” The answer is readability and maintainability. Constants make your code clearer and help prevent errors. For example, if you see MAX_SPEED_KM_PER_HR in code, it’s much more descriptive than seeing a raw number like 300 scattered around. It communicates intent: 300 what? Oh, 300 km/h max speed.

Similarly, seeing PI is clearer than seeing 3.14159 everywhere – it’s obvious we’re referring to the mathematical constant π. Using well-named constants means that if the value needs to change (say, we switch to miles per hour, or need more precision for π), we change it in one place where the constant is defined, instead of hunting down every occurrence of the number in our code. This reduces the chance of mistakes and makes the code easier to update.

So, in Python, a constant is basically a variable that you treat as unchangeable – a bit like writing in all caps as a way of shouting “Don’t touch this value!” in the code. It relies on you and other developers to not modify it.

Variables vs Constants: Real-World Analogy

To really hammer home the difference, let’s use a real-world analogy. Think of your code as a journal:

  • A variable is like a whiteboard or notebook page – you can erase or scratch out the old value and write a new one as things change. For instance, imagine a sign in a library that shows the “Number of visitors today.” In the morning it might say 5, by noon it’s 47, by evening it’s 120. That number changes throughout the day, so it’s a variable.
  • constant is like a permanent plaque or engraved stone – once written, it shouldn’t be altered. For example, the library might have a plaque that says “Library founded in 1950.” That year is a constant; it doesn’t change no matter what day it is. In code, a constant could be something like FOUNDATION_YEAR = 1950. You wouldn’t expect to rewrite history by changing that value during runtime.

Another analogy: consider a calendar. The current day of the week is a variable (it changes every day: Monday, Tuesday, etc.), whereas the number of days in a week (7) is a constant. No matter when or where you are, a week has 7 days – that won’t suddenly become 8. If we were coding this, current_day would be a variable that updates each day, and DAYS_IN_WEEK = 7 would be a constant.

These analogies show why we treat some values as variables and others as constants. It depends on whether the concept can change. If it can change (score, today’s temperature, user input), use a variable. If it must not change (max values, fixed configurations, mathematical constants like π), define it as a constant (by convention in Python).

Key Differences Between Variables and Constants in Python

Let’s summarize the differences and behaviors in a few key points:

  • Mutability of Value: Variables can be reassigned to new values as your program runs. Constants are intended to stay at one value throughout the program. Once you set a constant (like MAX_USERS = 100), you should not change it, whereas a variable (like user_count) might increase or decrease as the program executes.
  • Syntax and Declaration: In Python, you create both variables and constants using the same name = value syntax. There’s no special keyword for defining a constant in Python. The difference is purely in naming style and how they are used. By convention, Python constants are written in UPPERCASE_WITH_UNDERSCORES (e.g., MAX_SPEED) to signal that they shouldn’t change, whereas regular variable names are usually in lowercase (e.g., speed or current_speed). In other languages, there are dedicated syntax keywords for constants (more on this shortly).
  • Enforcement: Python does not enforce the constancy. If you decide to reassign an ALL_CAPS “constant” variable, Python will do it without any error (it’s on you to avoid doing that). In contrast, many other languages will protect constants. For example, Java will throw a compile-time error if you try to change a final constant, and C++ will do the same if you try to change a const variable (the compiler literally complains about “assignment of read-only variable”). This means Python gives you more flexibility (or rope to hang yourself, depending on how you see it!), whereas other languages enforce immutability of constants strictly.
  • Use Cases: Use variables for things that inherently can vary: loop counters, inputs, interim calculations, states that change (like a character’s health in a game). Use constants for fixed configuration values and universal truths your program relies on. For instance, if your program uses a tax rate or a specific file path that shouldn’t change during execution, make it a constant (e.g., TAX_RATE = 0.18). This makes your intent clear and your code safer from accidental changes.
  • Lifespan & Scope: In Python, both variables and constants can be defined within functions or at the module (global) level. By PEP 8 convention, constants are usually defined at the module level (top of the file), not inside functions. This is because constants tend to be values that many parts of your program might need (like configuration settings). Variables, on the other hand, are often used within a limited scope (inside a function or loop) for some calculation or process. (You can have variables at module level too, but if they’re meant to change, we just call them global variables.)

Using Variables and Constants: Python vs Other Languages

To appreciate Python’s approach, let’s briefly compare how constants are handled in a couple of other popular languages, Java and C++:

Java:

In Java, if you want to make a constant, you use the final keyword when declaring a variable, and by convention use uppercase names. For example:

final int HOURS_IN_A_DAY = 24;
HOURS_IN_A_DAY = 25; // Compile error: cannot assign a value to final variable HOURS_IN_A_DAY

Here, final int HOURS_IN_A_DAY = 24; defines a constant (an integer that should always be 24). If a Java program later contains HOURS_IN_A_DAY = 25;, it will not even compile – the Java compiler will stop and complain that you’re trying to change a final constant. In Java, it’s also common to make constants static if they belong to a class (e.g., public static final int MAX_USERS = 100;) so that there’s only one copy of that constant shared by all instances of the class.

C++:

In C++, you achieve a similar result with the const keyword:

const int HOURS_IN_A_DAY = 24;
HOURS_IN_A_DAY = 25; // ❌ Compiler error: assignment of read-only variable 'HOURS_IN_A_DAY'

The line const int HOURS_IN_A_DAY = 24; makes HOURS_IN_A_DAY a constant integer. Attempting to change it later results in a compilation error (C++ literally calls it a “read-only variable” in the error message). This means you cannot compile and run the program until you remove that illegal reassignment.

Other Languages: 

Many languages have some notion of constants:

  • C#: has const (for compile-time constants) and readonly (for runtime-set but then immutable fields).
  • JavaScript: (being more dynamic like Python) introduced const to declare block-scoped constants (which cannot be reassigned).
  • Ruby: has constants by convention (written in uppercase like Python; Ruby will give a warning if you try to change one).

The key theme is that Python is an outlier in that it doesn’t enforce the constant behavior – it relies on us to follow the convention.

This comparison highlights that Python’s flexibility is a double-edged sword. On one hand, it’s simple – just assign values, no extra syntax for constants. On the other hand, the burden is on the developers to not change something that shouldn’t change. In a language like Java or C++, the language helps enforce that rule by refusing to let you do it wrong.

A Note on Python’s Final Type Hint: Since Python 3.8, there is a way to signal immutability to static type checking tools by using Final from the typing module. For example:

from typing import Final

MAX_SPEED: Final[int] = 300
MAX_SPEED = 450  # This will run, but type checkers like mypy will flag it as an error

By writing MAX_SPEED: Final[int] = 300, we’re telling tools (like mypy or other linters) that MAX_SPEED is intended to be a constant. If later in the code we assign a new value to MAX_SPEED, a static type checker can catch that and warn us (“Cannot assign to final name ‘MAX_SPEED’”). However, this is not enforced at runtime – Python will still execute the reassignment if you run the code normally.

So, Final is more of a developer tool to catch mistakes early, rather than a true constant mechanism. It’s good to be aware of, especially as you work on larger projects where such tools are used for improving code quality.

Best Practices for Variables and Constants in Python

To write clean and maintainable Python code, keep these best practices in mind:

  • Follow Naming Conventions: Name your constants in UPPER_CASE_WITH_UNDERSCORES as recommended by PEP 8 (the Python style guide). For example: MAX_CONNECTIONS = 100 or PI = 3.14159. This makes constants stand out. Regular variables should be in lowercase (e.g., countfile_name) so it’s clear what’s meant to change and what isn’t.
  • Define Constants at the Top: It’s common to define constants at the top of your Python file (module level) so they are easy to find and modify if needed. For instance, you might have a block of constants like:
API_URL = "https://example.com/api"
TIMEOUT_SECONDS = 30
MAX_RETRIES = 5

at the top of your script or module. This way, anyone reading the code (or yourself, months later) can quickly see the key configuration values in one place.

  • Use Constants for “Magic Numbers”: If you find yourself using a number or string in multiple places in your code and it has a specific meaning, consider turning it into a constant. For example, instead of sprinkling the number 60 around your code (which might represent seconds in a minute), define a constant SECONDS_IN_MINUTE = 60 and use that. This makes the code self-documenting and easier to change if needed. The term “magic number” refers to a literal value that appears in code without explanation – replacing those with named constants makes your code clearer.
  • Don’t Reassign Constants: This sounds obvious, but remember not to assign a new value to a name that’s meant to be a constant. If you absolutely need a different value, it might indicate that it shouldn’t have been a constant in the first place (or you might need a separate constant for that scenario). If you use tools like linters or type checkers, consider using Final for critical constants so you get a warning if you accidentally reassign one.
  • Use Variables for Changing States: For variables, use them freely for their purpose – to hold changing information. But give them meaningful names and keep their scope as limited as possible. For example, if a calculation is only relevant inside one function, use a local variable inside that function (don’t make it global unless necessary). This makes your code easier to understand and avoids unintended interactions between different parts of the program.
  • Immutable Data vs. Constant Name: Note that “constant” in this context means you shouldn’t rebind the name to a new value. It doesn’t automatically make the object it refers to immutable. For instance, if you have MY_LIST = [1, 2, 3] as a constant (by naming convention), you’re signaling you shouldn’t reassign MY_LIST to a different list. However, the list object itself is still mutable – you could do MY_LIST.append(4) and change its contents. Whether that’s a good idea depends on your use case. If you truly want a constant collection, you might use an immutable type (like a tuple for a sequence of fixed values). This nuance is more advanced, but it’s good to be aware that constant naming doesn’t freeze the data itself.

Conclusion

Variables and constants are fundamental concepts every new programmer must grasp. In Python, the difference between them comes down mostly to how we use and name them, rather than strict enforcement by the language. A variable is your go-to for values that change – it’s the flexible, reusable container of data. A constant is for values that should remain fixed – serving as self-explanatory references that make code easier to read and maintain.

While Python doesn’t enforce constants, sticking to the convention of not changing them will save you from many headaches and bugs. As you’ve seen, other languages take a more strict approach with keywords like final or const, literally preventing reassignment to constants. Python gives you the freedom, expecting you to use it wisely.

Keep these lessons in mind as you move forward in your coding journey. Use variables when you need flexibility and use constants (with all-caps names) for clarity and stability. By doing so, you’ll write Python code that’s not only correct, but also clean, readable, and friendly to anyone else (or yourself in the future) who reads it. Happy coding!

References: Variables and constants definitions and best practices were informed by Python’s official style guide and documentation, as well as community resources. Examples of how Java and C++ handle constants are provided to highlight the differences.

References

Python Docs – Using Variables
https://docs.python.org/3/tutorial/introduction.html#using-variables
PEP 8 – Style Guide for Python Code
https://peps.python.org/pep-0008/
W3Schools – Python Constants
https://www.w3schools.com/python/gloss_python_constant.asp
Java Docs – final Keyword
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/final.html
C++ Reference – const Keyword
https://en.cppreference.com/w/cpp/language/const

Python Docs – typing.Final Type Hint
https://docs.python.org/3/library/typing.html#typing.Final

Deadline approaching fast?

Stop stressing over bugs and syntax. Get a custom, plagiarism-free solution delivered to your inbox.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top