Python Variables

1. Introduction
When you start learning Python, one of the first things you’ll encounter is the concept of variables.
A variable is simply a name that stores a value — think of it like a container or labeled box that holds something you want to keep and use later. For example, if you label a box “fruits” and put apples inside, you can open that box later whenever you need those apples.
In Python, you create this “label” by assigning a value to a name using the = operator.
1
fruits = "apples"
In simple terms, the = sign tells Python to store the value on the right (“apples”) inside the variable name on the left (fruits
). From that point on, whenever you use fruits in your code, Python knows you mean “apples”.
2. Creating a variable
1
name = "Paul"
In this example, we’ve assigned the text “Paul” to the variable called name. Now, whenever we use name in our code, Python will remember that it represents the string “Paul”.
You can check this by printing the variable:
1
print(name)
Output:
1
Paul
3. Changing a variable’s value
Variables are flexible — you can change what they store at any time by assigning a new value to them:
1
2
3
4
5
6
name = "Paul"
print(name) # Output: Paul
# Reassign a new value
name = "John"
print(name) # Output: John
Here, the variable name
first stored "Paul"
, but after we reassigned it, it now holds "John"
.
Python simply updates the label to point to the new value.
4. Working with Numbers
Variables can also store numbers, not just text. Here’s an example where we store a number and use it in a calculation:
1
2
age = 25
print(age)
Output:
1
25
Here, we created a variable called age and assigned it the number 25
. Unlike a string (which is written in quotes), numbers are written without quotes because they represent numeric values that Python can use in calculations.
5. Performing Calculations with Variables
Once a variable holds a number, you can use it in mathematical operations:
1
2
3
4
age = 25
next_year = age + 1
print(next_year)
Output:
1
26
In this example:
- age stores the number
25
. - We add 1 to it and store the result in another variable called next_year.
- When we print next_year, Python outputs
26
.
A variable name can be composed by numbers
, characters
or string
, the underscore character
.
6. Variable Naming Rules
Before using variables effectively, it’s important to understand how to name them properly in Python. Python has some rules for naming variables. A variable name can be composed by characters, numbers, the underscore character. It can’t start with a number.
1. What Makes a Valid Variable Name?
A variable name can include:
- Letters (A–Z, a–z)
- Numbers (0–9)
- The underscore (_) character
However:
- It cannot start with a number
- It cannot contain spaces or special characters
- It cannot use Python’s reserved keywords
Example of valid variable names:
1
2
3
4
5
my_var = 10
_age = 20
number2 = 30
user_name = "John"
total_count = 100
Invalid variable names:
1
2
3
4
5
2num = 100 # ❌ Cannot start with a number
my-var = 50 # ❌ Hyphens not allowed
class = 5 # ❌ 'class' is a reserved keyword
my var = 10 # ❌ No spaces allowed
special@char = 20 # ❌ No special characters
Note : Variable names are case-sensitive — Name and name are treated as different variables.
2. How Python Automatically Detects Variable Type
You don’t need to declare a variable type before assigning a value. Python automatically determines the type based on the value you assign.
Example:
1
2
3
name = "Alice" # a string value
age = 25 # an integer value
height = 5.7 # a float value
Here, Python automatically understands that:
name
is a string (because it’s enclosed in quotes)age
is an integerheight
is a floating-point number
1. Writing Readable Variable Names
Use clear, descriptive names for your variables. Good naming makes your code easier to read and understand - For example, use total_price
instead of just tp
.
For Example: It’s better to use:
1
2
total_price = 150
student_name = "Alice"
Avoid:
1
2
tp = 150
sn = "Alice"
Try It Yourself : Now that you understand how variables work, let’s practice by creating a few of your own.
- Create three variables:
- One to store your name
- One to store your age
- One to store your favorite color
Now, use the print()
function to display them.
Here’s an example:
1
2
3
4
5
6
7
8
9
# Creating variables
name = "Isaac"
age = 25
favorite_color = "Blue"
# Displaying variable values
print("My name is", name)
print("I am", age, "years old")
print("My favorite color is", favorite_color)
Output:
1
2
3
My name is Isaac
I am 25 years old
My favorite color is Blue
Or use an f-string (formatted strings) to make your print statements cleaner and easier to read:
1 print(f"My name is {name}, I am {age} years old, and my favorite color is {favorite_color}.")output:
1 My name is Isaac, I am 25 years old, and my favorite color is Blue.
Avoid Using Python Keywords
Python has built-in reserved words you cannot use as variable names, such as for, class, if, while, import, and return. Doing so will cause an error.
Example:
1
for = 10 # ❌ SyntaxError: invalid syntax
A few Python keywords include:
1
2
3
4
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
You don’t have to memorize them — Python will warn you if you accidentally use one.
Challenge :
- Change the values of your variables and rerun the code.
- Notice how Python instantly updates your output — that’s the beauty of dynamic typing!
7. Naming Conventions (PEP 8)
Python follows the PEP 8 style guide, which is a set of conventions that makes your code clean, consistent, and easy to read. When namining variables
1. Variables and Functions → use_snake_case
Use lowercase letters and separate words with underscores. This is called snake_case.
1
2
3
4
5
6
7
# Use snake_case (all lowercase with underscores)
# Good practice
user_name = "Alice"
total_score = 100
def calculate_average():
pass
Avoid styles like:
1
2
UserName = "Alice" # PascalCase (used for classes)
userName = "Alice" # camelCase (used in other languages)
2. Constants → USE UPPERCASE_WITH_UNDERSCORES
Constants are values that shouldn’t change while your program runs. By convention, they are written in all uppercase with underscores between words.
1
2
3
4
# Use UPPERCASE with underscores for constants
MAX_USERS = 100
PI = 3.14159
API_KEY = "secret123"
3. Classes → USE PascalCase
and (capitalize each word)
Classes represent data models or structures. Use PascalCase (capitalize each word) when naming classes
1
2
3
4
5
6
# Use PascalCase (CapitalizeEachWord)
class UserProfile:
pass
class DatabaseConnection:
pass
Following PEP 8 in Practice :
1
2
3
4
5
6
7
8
MAX_RETRIES = 3
def get_user_age():
user_age = 25
print(f"User age is {user_age}")
class StudentProfile:
pass
Output:
1
User age is 25
✨ Following PEP 8 ensures your code looks neat, consistent, and understandable to any Python developer.
Programming Tips
-
Keep names descriptive for your variable, for example use
score
instead ofs
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’.
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.
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 Variable Types in detail.