Python Variables 📦
What is a Variable?
Think of a variable as a label or a sticky note that you attach to a value. Unlike C++ or Java where a variable is a "box" that holds data, in Python, the variable points to where the data is stored in memory.
🤖 Analogy: The Sticky Note
x = 5
Imagine the number 5 is an object sitting on a shelf (memory).
The variable x is just a sticky note with "x" written on it, stuck onto that object.
If you say y = x, you are just putting another sticky note "y" on the same object!
✨ Creating Variables
x = 5 # x points to an integer object (5)
y = "John" # y points to a string object ("John")
print(x)
print(y)🔧 Under the Hood: Memory Addresses
You can see where an object lives in memory using the id() function.
x = 10
y = 10
print(id(x))
print(id(y))
# Output: Same number! Python optimizes small integers by reusing them.🔄 Dynamic Typing
Python is dynamically typed. This means you don't need to declare the type of a variable (like int x = 5). Variables can even change type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)🏷️ Variable Naming Rules (PEP 8)
A variable can have a short name (like x) or a descriptive name (age, total_volume).
- Must start with a letter or the underscore character.
- Cannot start with a number.
- Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- Case-sensitive (
age,AgeandAGEare different variables).
✨ Best Practice: Snake Case
Python developers use snake_case for variable names (all lowercase with underscores).
my_variable_name = "John" # ✅ Good (Pythonic)
myVariableName = "John" # ❌ Bad (CamelCase is for classes)🔗 Assign Multiple Values
Many Values to Multiple Variables
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)One Value to Multiple Variables
x = y = z = "Orange"
print(x)
print(y)
print(z)📦 Unpacking a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called Unpacking.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)💡 Did You Know? Constants
Python doesn't have built-in constant types. By convention, developers use ALL_CAPS to indicate a variable should be treated as a constant and not changed.
PI = 3.14159
MAX_CONNECTIONS = 100