Variables and assignment
In programming, a variable acts like a labeled container that holds data. It allows you to store values—such as numbers, text, or other data types—and reference them later in your code, making your programs more dynamic and easier to manage.
What are variables?
A variable is essentially a name that points to a value. For example, in Python, you can create a variable called age
to store the number 25
.
Think of a variable as a labeled box where you can place your data. Whenever you need the data, you refer to the box by its label (the variable's name).
Assigning values to variables
In Python, assigning a value to a variable is simple: use the =
operator.
Syntax:
variable_name = value
Examples:
# Assigning an integer
age = 25
# Assigning a string
name = "Alice"
# Assigning a float
height = 1.75
# Assigning a boolean
is_active = True
After assignment, you can use the variable in your code as many times as needed. For example:
print(name, "is", age, "years old.")
# Output: Alice is 25 years old.
Rules for naming variables
To avoid errors, follow these rules when naming variables in Python:
-
Start with a letter or an underscore (_).
- ✅
age = 25
- ✅
_score = 95
- ❌
1st_place = "Gold"
(Invalid: starts with a number) -
Only use letters, numbers, and underscores.
- ✅
first_name = "Alice"
- ❌
first-name = "Alice"
(Invalid: contains a hyphen)
- ✅
-
Avoid reserved keywords.
- ❌
if = 10
(Invalid:if
is a Python keyword)
- ❌
-
Case-sensitive names.
Age
,AGE
, andage
are all different variables.
Examples of variable assignments
Here are a few practical examples to demonstrate variable usage:
# Integer assignment
counter = 10
print(counter) # Output: 10
# String assignment
username = "PythonLearner"
print(username) # Output: PythonLearner
# Float assignment
height = 1.75
print(height) # Output: 1.75
# Boolean assignment
is_active = True
print(is_active) # Output: True
You can even update the value of a variable later:
score = 50
print(score) # Output: 50
score = 75
print(score) # Output: 75
Common pitfalls to avoid
-
Using invalid names:
1name = "John" # Error: Cannot start with a number
-
Overwriting Python keywords:
print = 5 # Error:
print is a reserved keyword -
Case-sensitivity confusion:
age = 25 print(Age) # Error:
Age is not defined
Why use variables?
Variables make your programs dynamic and flexible. Imagine a calculator app where you need to update values or a game that tracks a player’s score.
Without variables, you’d have to manually update the values everywhere in your code, which is inefficient and error-prone.
Conclusion
Variables are the foundation of Python programming. They store data and make your code reusable and easy to manage.
By following the naming rules and best practices, you’ll avoid errors and write cleaner, more readable code.
Practice assigning values to variables and experiment with different data types to solidify your understanding.