Python Variables and Constants Reference

Python Variables and Constants Reference

Welcome back, fellow Python enthusiast! Today we’re going to explore one of the most foundational concepts in programming: variables and constants. If you’re just starting out, this is where you begin building your understanding of how data is stored and used in Python. Let’s jump right in.

What Are Variables?

In Python, a variable is like a labeled container where you can store data. Think of it as a name that refers to a value. You can assign almost anything to a variable—numbers, text, lists, even functions. The great thing about variables is that they let you reuse and manipulate data throughout your code.

To create a variable, you simply choose a name and use the assignment operator = to give it a value. No need to declare its type beforehand—Python figures that out for you! This feature is called dynamic typing.

message = "Hello, Python!"
count = 42
pi_value = 3.14159

Here, message holds a string, count holds an integer, and pi_value holds a float. You can always reassign a variable to a new value, even of a different type.

x = 10
print(x)  # Output: 10

x = "Now I'm a string!"
print(x)  # Output: Now I'm a string!

Naming Variables

Python has some rules and conventions for naming variables:

  • Names can contain letters, numbers, and underscores.
  • They cannot start with a number.
  • They are case-sensitive (age, Age, and AGE are three different variables).
  • Avoid using Python keywords (like if, for, while) as variable names.

It’s good practice to use descriptive names that make your code readable. For multi-word names, underscores are commonly used (e.g., user_age, total_count).

# Good naming
user_name = "Alice"
item_count = 5

# Not so good
a = "Alice"
n = 5

Constants: A Convention, Not a Rule

Unlike some other programming languages, Python doesn’t have built-in constants. But we often use variables as constants by convention. A constant is a variable whose value is not meant to change during the program’s execution.

By convention, we write constant names in all uppercase letters with underscores separating words. This tells other programmers (and your future self) that the value should remain unchanged.

PI = 3.14159
MAX_CONNECTIONS = 100
API_KEY = "abc123"

Even though you can change these values, you shouldn’t. It’s all about writing clear and maintainable code.

Common Constant Examples Typical Values
PI 3.14159
SPEED_OF_LIGHT 299792458
MAX_USER_LIMIT 1000
DEFAULT_TIMEOUT 30

Data Types and Variables

Since Python is dynamically typed, a variable can hold values of different types over its lifetime. Here are some common data types you’ll assign to variables:

  • Integers: count = 10
  • Floats: average = 88.5
  • Strings: greeting = "Hello"
  • Booleans: is_valid = True
  • Lists: items = [1, 2, 3]
  • Dictionaries: user = {'name': 'Bob', 'age': 25}

You can check the type of any variable using the type() function.

x = 10
print(type(x))  # Output: <class 'int'>

x = "hello"
print(type(x))  # Output: <class 'str'>

Variable Assignment and Reassignment

You’ve already seen basic assignment. You can also assign multiple variables at once.

a, b, c = 1, 2, 3
print(a, b, c)  # Output: 1 2 3

Or assign the same value to multiple variables:

x = y = z = 0
print(x, y, z)  # Output: 0 0 0

Reassigning variables is straightforward. Just use the = operator again with a new value.

score = 95
print(score)  # Output: 95

score = 100
print(score)  # Output: 100

Variable Scope

Where you define a variable matters. Variables have scope, which determines where in your code they can be accessed.

  • Local scope: Variables defined inside a function. They are only accessible within that function.
  • Global scope: Variables defined outside all functions. They are accessible throughout your code.
global_var = "I'm global"

def my_function():
    local_var = "I'm local"
    print(global_var)  # This works
    print(local_var)   # This works too

my_function()
print(global_var)  # This works
print(local_var)   # This will cause an error

If you need to modify a global variable inside a function, use the global keyword.

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # Output: 1

But use global variables sparingly—they can make code harder to debug and maintain.

Operations with Variables

You can use variables in expressions just like literal values.

a = 5
b = 3
sum = a + b
print(sum)  # Output: 8

message = "Hello"
name = "Alice"
greeting = message + " " + name
print(greeting)  # Output: Hello Alice

You can also use compound assignment operators to modify variables concisely.

x = 10
x += 5   # Equivalent to x = x + 5
print(x) # Output: 15

x *= 2   # Equivalent to x = x * 2
print(x) # Output: 30

Best Practices

Let’s summarize some best practices for working with variables and constants:

  • Use meaningful and descriptive names.
  • Follow naming conventions: lowercase with underscores for variables, uppercase for constants.
  • Initialize variables before using them.
  • Avoid using global variables unless necessary.
  • Use constants for values that should not change.
Naming Convention Example Usage
Variable user_name Changing values
Constant MAX_SIZE Fixed values
Function calculate_total Actions
Class DataProcessor Blueprints

Common Pitfalls

Even experienced developers can stumble. Here are some common mistakes to avoid:

  • Forgetting to initialize a variable before use.
  • Misspelling a variable name (remember, Python is case-sensitive!).
  • Accidentally changing a constant.
  • Using a keyword as a variable name.
# This will cause an error because 'if' is a keyword
if = 5

# This is fine
if_condition = 5

Dynamic Typing in Action

Let’s see dynamic typing with a more complex example.

value = 10
print(type(value))  # Output: <class 'int'>

value = "Ten"
print(type(value))  # Output: <class 'str'>

value = [1, 2, 3]
print(type(value))  # Output: <class 'list'>

This flexibility is powerful but requires attention—make sure you know what type your variable holds at any given time!

Constants in Practice

While Python doesn’t enforce constants, you can use classes or modules to create read-only values. Here’s a simple way using a class:

class Constants:
    PI = 3.14159
    GRAVITY = 9.8

print(Constants.PI)  # Output: 3.14159

You can also place constants in a separate module (a .py file) and import them.

constants.py:

PI = 3.14159
MAX_USERS = 100

main.py:

import constants

print(constants.PI)       # Output: 3.14159
print(constants.MAX_USERS) # Output: 100

This keeps your constants organized and accessible across multiple files.

Variable Interpolation in Strings

You’ll often need to include variables in strings. Python offers several ways:

Using f-strings (Python 3.6+):

name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)  # Output: My name is Alice and I am 30 years old.

Using .format():

message = "My name is {} and I am {} years old.".format(name, age)

Using % formatting (older style):

message = "My name is %s and I am %d years old." % (name, age)

F-strings are generally preferred for their readability and efficiency.

Memory and Variables

It’s helpful to understand that variables in Python are references to objects in memory. When you assign a variable, you’re creating a reference to an object, not copying the object itself (unless you explicitly do so).

For immutable objects (like integers, strings, tuples), this usually doesn’t cause issues. But for mutable objects (like lists, dictionaries), you need to be cautious.

list1 = [1, 2, 3]
list2 = list1   # Both variables reference the same list

list2.append(4)
print(list1)  # Output: [1, 2, 3, 4] — list1 is also changed!

To create an independent copy, use the copy method or slicing.

list1 = [1, 2, 3]
list2 = list1.copy()   # Or list2 = list1[:]

list2.append(4)
print(list1)  # Output: [1, 2, 3] — unchanged
print(list2)  # Output: [1, 2, 3, 4]

Deleting Variables

You can delete a variable using the del statement. This removes the reference to the object.

x = 100
print(x)  # Output: 100

del x
print(x)  # NameError: name 'x' is not defined

This is rarely needed in everyday coding but can be useful for freeing up memory or cleaning up namespaces.

Variable Annotations (Type Hints)

Since Python 3.5, you can add type annotations to variables. This doesn’t change how Python works—it’s still dynamically typed—but it helps with code clarity and can be used by tools for type checking.

name: str = "Alice"
age: int = 30
scores: list[int] = [90, 85, 95]

You can use tools like mypy to check your code for type consistency.

Practice Examples

Let’s reinforce with a few practical examples.

Calculate area of a circle:

PI = 3.14159
radius = 5
area = PI * radius ** 2
print(area)  # Output: 78.53975

User input and variable use:

name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old.")

Swapping two variables:

a = 5
b = 10
a, b = b, a
print(a, b)  # Output: 10 5

Summary of Key Points

  • Variables store data and can be reassigned.
  • Use descriptive names and follow naming conventions.
  • Constants are variables meant to be unchanged, written in uppercase.
  • Python uses dynamic typing—variables can hold values of any type.
  • Be mindful of variable scope (local vs. global).
  • Use f-strings for string interpolation.
  • Understand that variables are references to objects in memory.

You’re now equipped with a solid understanding of variables and constants in Python. Remember, practice is key—try writing your own code examples to reinforce these concepts. Happy coding