Python Variables

Python Variables

When you start learning Python, one of the first things you’ll encounter is the concept of variables. Think of a variable as a container or label that stores a value. Just like you might write a name on a box to remember what’s inside, Python uses variables to store data so you can use it later in your program.

We can create a Python variable by assigning a value to a label, using the assignment operator =.

In the example below, we assign a string with the value “Paul” to the name label.

name = "Paul"

Here’s an example with a number:

age = 25

A variable name can be composed by numbers, characters or string, the underscore character.

What is a Variable in Python?

A variable is a symbolic name that refers to a value stored in the computer’s memory.

  • In Python, you don’t need to declare variables with a specific type.
  • You assign a value to a variable using the = operator.

For Example:

name = "Alice"               # String variable
age = 25                     # Integer variable
is_student = True            # Boolean variable

print(name, age, is_student)

Output:

Alice 25 True

Python has some rules for naming variables. For example, you can’t start a variable name with a number or underscore character.

  • The following are valid variable names
my_var = 10             
_age = 20              
number2 = 30          
firstName = "John"    
total_count = 100      
  • These are invalid variable names
2num = 100         # Cannot start with a number
my-var = 50       # Cannot use hyphens
class = 5          # Cannot use Python keywords
my var = 10       # Cannot contain spaces
special@char = 20       # Cannot use special characters (@, !, $, etc.)

Python has built-in keywords that cannot be used as variable names. For example, there are some keywords like for, while, if, import and many more. Common keywords that cannot be used or cause errors are:

False, None, True, and, as, assert, async, await, break, 
class, continue, def, del, elif, else, except, finally, 
for, from, global, if, import, in, is, lambda, nonlocal, 
not, or, pass, raise, return, try, while, with, yield

There is no need to memorize these keywords, as Python will alert you if you use one of those as a variable name.

Naming Conventions in Python

We should use snake_case with underscore in lowercase when declaring a variable name. For Example;

# Use snake_case (all lowercase with underscores)
user_name = "Alice"
total_score = 100
calculate_average()  # Functions also use snake_case

Use UPPERCASE with underscores for constants in Python. Examples below:

# Use UPPERCASE with underscores for constants
MAX_USERS = 100
PI = 3.14159
API_KEY = "secret123"

When declaring Classes in Python, use PascalCase (make sure to CapitalizeEachWord). For example:

# Use PascalCase (CapitalizeEachWord)
class UserProfile:
    pass

class DatabaseConnection:
    pass
Programming Tips
  • Keep names descriptive for your variable, for example use score instead of s when naming a variable
  • Be consistent with your naming style
  • Avoid single letters for variable names except for loop counters (i, j)
  • Make names readable like ‘number_of_students’ and not something like ‘numstd’

Variable Types

Python is a dynamically typed language, which means you don’t need to specify variable types when declaring them. Python automatically detects the type from the value type at runtime.

# Python is a dynamically typed language. Variable types are inferred at runtime, so you can write:
x = 5        # x is an integer
x = "hello"  # x is now a string

Python has the following common data types for values:

  • Integer (int) - represents whole numbers (e.g., 5, -10, 0)
  • Float (float) - represents decimal numbers (e.g., 3.14, -0.5, 2.0)
  • String (str) - represents text inside quotes or enclosed in quotes (e.g., “hello”, ‘Python’)
  • Boolean (bool) - represents logical values (True or False)
  • Collections: - Include list, tuple, dict, and set for storing multiple items

Examples:

x = 10          # int
y = 3.14        # float
z = "Hello"     # str
is_ready = True # bool

You can check the type of a variable with type() function. As in:

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

Python provides different ways to assign values. To assign a single value:

a = 10

You can assign multiple values by:

x, y, z = 1, 2, 3

And for a chain assignment, use:

a = b = c = 0
Variable Scope

Scope defines the region of a program where a variable can be accessed. It determines where in your code a variable can be seen and used.

  • Local Variable is defined inside a function, accessible only within that same function, and cease to exist when the function finishes.
  • Global Variable is defined outside functions, accessible everywhere in your code, and exist throughout the entire program.

Example:

global_var = 10         # global variable which is accessible everywhere

def my_function():
    local_var = 5       # local variable - accessible only inside this function
    print("Inside function:", local_var) 
    
my_func()
print("Outside function:", global_var)

Output:

Inside function: 5
Outside function: 10

Note that:

  • Local variables are like private notes inside a function
  • Global variables are like public announcements everyone can hear
  • If a variable name is the same locally and globally, the local version wins inside the function.

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

Mutable vs Immutable Variables
  • Immutable variaables: Cannot be changed after creation (e.g., numbers, strings, tuples, intergers, floats, boolean).
  • Mutable variables: Can be modified after creation (e.g., lists, dictionaries, sets).

Example Demonstration:

# Immutable
s = "hello"
s = s.upper()
print(s)        # Output: HELLO (is a new string created)

# Mutable
lst = [1, 2, 3]
lst.append(4)
print(lst)      # Output: [1, 2, 3, 4] (same list updated)
Constants

Constants are variables meant to store values that should never change during program execution. While Python doesn’t have built-in constant enforcement, developers follow naming conventions to indicate that a variable should be treated as constant. By convention we write them in uppercase.

Example:

# Mathematical constants
PI = 3.14159
GRAVITY = 9.81
SPEED_OF_LIGHT = 299792458
Special Variables:

Special variables are built-in variables in Python that have specific meanings like __name__.

Example:

# __name__ tells us if this file is being run directly or imported
if __name__ == "__main__":
    print("This script is running directly!")
Memory and Identity

Every variable in Python is a reference to an object in memory. When you create a variable, you’re creating a “label” that points to where the actual data is stored. You can check its identity with id().

# Two variables pointing to the same object
x = [1, 2, 3]
y = x       # y references the SAME list as x

print("x id:", id(x))
print("y id:", id(y))
print("Same object?", x is y)     # Same id (small integers are reused in memory)

output:

x id: 1679998307072
y id: 1679998307072
Same object? True
FAQs about Python variables

Q1: What is a variable in Python in one line?

A variable is a named reference that stores a value in memory.

Q2: Can variable names start with numbers?

No, they must start with a letter or underscore.

Q3: What’s the difference between a variable and a constant?

A variable can change, while a constant should stay the same throughout the program (by convention, written in uppercase).

Q4: How are variables stored in memory?

They are references to objects stored in memory, not actual containers of values.

Python code example

Summary
  • Variables are names used to store data in Python.
  • Python supports dynamic typing (no need to declare type).
  • Variables can have different scopes and can be mutable or immutable.
  • Follow best practices for readability and maintainability.

Now that you understand Python variables, your next step is to learn about Python Data Types in detail.