Variables - Python Basics
Variables are one of the first—and most important—concepts you learn when programming. In Python, variables are names that reference values stored in memory. But there’s more to variables than just storing numbers or text: learning naming rules, multiple assignment, scope (global vs local), output techniques, constants, type casting, and best practices will make your code clearer, safer, and easier to maintain.
global
and nonlocal
, output & formatting, constants, type conversion, mutability, scope-related bugs, practical examples, exercises, and an FAQ.
What is a variable? — The simple idea
A variable is a label you attach to a value. The label lets you refer to that value later in your code. In Python variables are dynamic: the same name can point to different types at different times.
# Create variables
name = "Asha"
age = 25
pi = 3.14159
is_student = True
Above, name
, age
, pi
, and is_student
are variable names referencing different types of values.
Variable naming rules (and style)
Python has syntactic rules that every variable name must follow, plus style conventions (PEP 8) that make code readable and consistent.
Legal rules (must-follow)
- Must start with a letter (
a–z
orA–Z
) or an underscore (_
). - Remaining characters may be letters, numbers, or underscores (
_
). - Cannot be a Python keyword (e.g.,
if
,for
,class
,def
). - Case-sensitive:
data
andData
are different.
Style conventions (strongly recommended)
- Use snake_case (lowercase with underscores) for variables:
user_name
,total_cost
. - Choose descriptive names: prefer
invoice_total
overit
. - Avoid single-letter names except for counters or short-lived loop variables (e.g.,
i
,j
). - Constants (by convention) are uppercase:
MAX_RETRIES
,PI
.
Assignment: creating and changing variables
Assigning is as simple as using the =
operator. Python infers the data type.
x = 10 # integer
x = "ten" # now x holds a string
price = 19.99 # float
items = ["a","b"] # list (mutable)
Because Python is dynamically typed, the same name can reference different types at different times. That flexibility is powerful but requires discipline.
total
is a number in one function and a string in another, you’ll get bugs.
Assigning multiple variables & tuple unpacking
Python allows compact and expressive assignment patterns that improve readability.
Parallel assignment
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
Parallel assignment is great for swapping and returning multiple values from functions.
Swapping variables
a = 5
b = 10
a, b = b, a # swap
print(a, b) # 10 5
Unpacking iterables
coords = (10, 20, 30)
x, y, z = coords
print(x, y, z) # 10 20 30
If the number of variables doesn’t match the iterable, use the star expression to collect extras:
*a, b = [1,2,3,4] # a=[1,2,3], b=4
Output variables: printing and returning values
“Output variables” usually refers to how you display or return the value stored in variables. There are several friendly ways to format outputs:
1) Comma separated in print
name = "Asha"
age = 25
print("Name:", name, "Age:", age)
2) String concatenation (explicit cast needed)
print("Age: " + str(age))
3) f-strings (recommended, Python 3.6+)
print(f"My name is {name} and I am {age} years old.")
For functions that produce values you want to use later, return them instead of printing:
def compute_area(radius):
return 3.14159 * radius * radius
area = compute_area(5)
print(f"Area: {area}")
return
when a function provides data for later use. Use print
for debugging or final display.
Scope: Local, Global, and Nonlocal variables
Scope defines where a variable name is visible and can be used. Misunderstanding scope causes many beginner bugs.
Local scope (inside functions)
def f():
x = 10 # x is local to f
print(x)
f()
# print(x) # would raise NameError: x is not defined
Global scope (module-level)
x = 100 # global
def show():
print(x) # reads global x
show()
Modifying globals: the global
keyword
If you want to modify a global variable inside a function, declare it with global
:
count = 0
def inc():
global count
count += 1
inc()
print(count) # 1
global
leads to code that is hard to reason about. Prefer returning values.
Nested functions & the nonlocal
keyword
When a nested (inner) function needs to modify a variable from its enclosing (but non-global) scope, use nonlocal
:
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
inner()
print(x) # "inner"
outer()
Mutable vs Immutable variables
Variables reference objects. In Python some objects are immutable (cannot change) and some are mutable (can be changed in place).
Immutable types
Examples: int
, float
, str
, tuple
. When you change a variable holding an immutable object, you create a new object.
a = 5
b = a
a = a + 1
print(a, b) # 6 5
Mutable types
Examples: list
, dict
, set
. Changing the object via one variable will be visible via another variable referencing the same object.
lst1 = [1,2,3]
lst2 = lst1
lst1.append(4)
print(lst1, lst2) # [1,2,3,4] [1,2,3,4]
list.copy()
, dict.copy()
, or the copy
module.
Type hints & annotations (optional, but useful)
Python supports type hints to document expected variable types. They don’t change runtime behavior but help tools and readers.
age: int = 25
names: list[str] = ["Asha", "Tom"]
def greet(name: str) -> str:
return f"Hello, {name}"
Use mypy
or an editor with type checking for extra safety in large projects.
Type conversion (casting)
Convert values between types using built-in functions: int()
, float()
, str()
, bool()
, and list()
.
s = "123"
n = int(s) # 123
f = float("3.14")
b = bool("") # False
int("abc")
→ ValueError
.
Constants: convention over language support
Python does not enforce constants. By convention, variables written in UPPERCASE are treated as constants.
PI = 3.14159
MAX_USERS = 100
Tools like linters (flake8
) can warn when constants are reassigned.
Common mistakes (and how to avoid them)
1) Mixing tabs and spaces
Python raises an IndentationError
when tabs and spaces are mixed. Configure your editor to insert 4 spaces on tab press.
2) Accidentally mutating shared objects
default = []
def add(x):
default.append(x) # shared state
Solution: create fresh objects inside functions or copy when needed.
3) Unintended shadowing
Giving a local variable the same name as a global can be confusing. Prefer distinct names or explicit global
if necessary.
4) Relying too heavily on global
Global variables increase coupling between parts of the code. Prefer returning values from functions.
5) Implicit type assumptions
Don’t assume input is the right type. Use try/except
to handle conversion errors gracefully.
Mini Project: A simple CLI user profile (uses variables well)
Build a small script that collects user details, stores them in appropriately named variables, validates input, and prints a formatted summary using f-strings.
def get_user_profile():
name = input("Enter your name: ").strip()
while True:
age_str = input("Enter your age: ").strip()
try:
age = int(age_str)
break
except ValueError:
print("Please enter a valid number for age.")
email = input("Enter your email: ").strip()
return name, age, email
name, age, email = get_user_profile()
print(f"User profile: {name} ({age}) — {email}")
This exercise covers multiple assignment, type casting, input validation, and output formatting.
Exercises — Try these (with answers below)
- Create variables
a, b
, swap them without using a temporary variable. - Write a function that returns two values: the sum and product of two numbers. Assign them to two variables.
- Write a function that counts how many times it has been called using a global variable. Then refactor to avoid using globals.
1)
a, b = b, a
2)
def f(x,y): return x+y, x*y
and s,p = f(2,3)
3) Global approach uses
global
. Better: keep a counter object or return the new count.
FAQ — Quick answers
Q: Are variables typed in Python?
A: Values have types. Variables are labels that reference typed objects. Python is dynamically typed.
Q: Can I make a constant real in Python?
A: The language has no enforced constants. Use naming conventions (UPPERCASE) and linters to enforce immutability in practice.
Q: When should I use nonlocal
?
A: Use nonlocal
inside nested functions when you must modify an enclosing function’s variable (not global).
Best practices summary
- Prefer descriptive names and snake_case.
- Limit use of global state; prefer function returns.
- Be explicit with type conversions; validate external input.
- Understand mutability before copying or sharing objects.
- Use type hints in large codebases for clarity and tooling support.
Suggestions:
- Python Programming: The Complete Beginner’s Guide
- What is Programming? A Complete Beginner’s Guide
- Problem Solving: Your Secret Superpower
Conclusion
Variables are simple in concept but powerful in practice. Learning naming rules, assignment patterns, scope, and mutability will make your Python code cleaner and less error-prone. Practice the mini-project and exercises above, follow the best practices, and you’ll avoid many common beginner pitfalls.
0 Comments