Imagine you are moving to a new house. You have boxes, and you label them: "Kitchen", "Books", "Clothes". In Python, variables are like those labels (or boxes). They store information that you can reference later.
Concept Explanation
A variable is essentially a named location in the computer's memory where you can store data. Rather than having to remember specific memory addresses, the computer allows you to assign a human-readable name (like age or username) to that data. When the program runs, it can look inside that specific "box" and retrieve the value inside of it, or even change the value entirely.
Because Python is "dynamically typed", you do not have to announce ahead of time what kind of data is going to be stored in the box. In rigid languages like Java, you must declare int score = 10; to lock the box to integers only. Python simplifies this down to just score = 10.
Syntax or Core Structure
Creating a Variable
You don't need to declare a type (like "this box is only for books"). Python figures it out.
Code Example #1 (Basic)
score = 10 # integer
name = "Alex" # string
price = 19.99 # float
print(name) # Will output: Alex
print(score) # Will output: 10
Code Example #2 (Intermediate)
Variables can be assigned to the results of complex mathematical operations, or they can even be updated continuously as the program runs.
base_price = 50.00
tax_rate = 0.08
final_price = base_price + (base_price * tax_rate)
print("The final total is:")
print(final_price) # Outputs 54.0
# Reassigning variables (updating the box's contents)
lives_remaining = 3
lives_remaining = lives_remaining - 1 # Player loses a life
print("Lives left:", lives_remaining) # Outputs 2
Data Types
Although Python is dynamically typed, data still has a type.
- Integers (
int): Whole numbers (e.g.,5,-10,42). - Floating Point (
float): Decimals (e.g.,3.14,0.001). - Strings (
str): Text (e.g.,"Hello"). - Booleans (
bool): Logic values (TrueorFalse).
Checking Types
You can check the type of any variable using type().
x = 100
print(type(x))
# Output: <class 'int'>
Naming Rules & Conventions
To keep your code clean, follow these rules:
- Snake Case: Use underscores for multi-word variables.
- ✅
user_name - ✅
total_score - ❌
userName(CamelCase is usually for Classes)
- Case Sensitive:
age,Age, andAGEare three different variables.
- No Numbers at Start:
- ✅
player1 - ❌
1player(Syntax Error)
Type Casting
Sometimes you need to treat a number like text (string) or vice versa. This is called Casting.
Scenario: Concatenating Text and Numbers
This will cause an error:
age = 25
print("I am " + age + " years old")
# TypeError: can only concatenate str (not "int") to str
The Fix: Convert to String
print("I am " + str(age) + " years old")
Common Casting Functions
int("10")->10float(5)->5.0str(100)->"100"
Real World Example
In a banking application, you frequently need to manage customer balances, usernames, and transaction logic.
# Banking User Profile Profile
customer_name = "Sarah Jenkins"
is_premium_member = True
account_balance = 1250.75
print("Welcome, " + customer_name)
print("Are you a premium member?")
print(is_premium_member)
# Simulating a deposit
account_balance = account_balance + 200.00
print("New Balance: $" + str(account_balance))
Common Mistakes
- Using Reserved Keywords: You cannot name your variable a word that Python already uses for its syntax. Naming a variable
print = 5orTrue = 10will break your program. - Forgetting to Cast: Trying to add a number to a string, like
"User" + 3. Python doesn't know if you want the string"User3"or if you're trying to do mathematical addition, so it throws aTypeError. - Misspelling Variables: Variables are case-sensitive. If you declare
maxHealth = 100, and then try to lower it withmaxhealth = maxhealth - 10, the code will crash becausemaxhealthis undefined.
Best Practices
- Descriptive Naming: Always name variables after what they actually represent.
user_age = 25is vastly superior tox = 25. It makes your code self-documenting. - Avoid Single Letter Variables: Unless you are creating a quick mathematical loop (like
xandycoordinates), avoid single letter names. You will forget whataorbstood for two weeks from now.
Practice Exercises
- Declare Variables: Create three variables: a
stringcontaining your favorite color, anintegerwith your birth year, and afloatrepresenting the exact price of a cup of coffee. Print all three. - Math with Variables: Create a variable called
lengthand set it to 10. Createwidthand set it to 5. Calculate the area (length * width) and store it in a new variable, then print the result. - Type Checking: Assign the value
"42"(with quotes) to a variable. Use thetype()function to print its current type, then cast it to an integer and print the mathematical result of adding 10 to it. - Fix the Naming: The variable
1st_player_score = 100is invalid. Fix the name so it follows the correct snake_case and numbering rules, then print it. - The Casting Fix: Try to print
"I have " + 5 + " apples."Python will throw an error. Use casting to fix the code and make it run successfully.