Variables & Data Types π¶
Mentor's Note: Variables are the "memory" of your program. Without them, your code would forget everything as soon as it happened! π‘
π The Scenario: The Warehouse π¦¶
Imagine you are managing a huge warehouse.
- The Logic: You have thousands of items. To stay organized, you put items into Boxes and stick a Label on them (like "Toys" or "Shoes"). π¦
- The Result: When you need the toys, you just look for the label "Toys." In Python, the Label is the Variable Name, and the Item inside is the Value. β
π Concept Explanation¶
1. Variables¶
A variable is a name that refers to a location in computer memory.
2. Rules for Naming Labels π·οΈ¶
- Must start with a letter or underscore
_. - Cannot start with a number.
- Can only contain
A-z,0-9, and_. - Case-sensitive (
priceis different fromPrice).
3. Dynamic Typing (The "Smart Box")¶
In Python, boxes are smart. You don't have to decide if a box is only for "Shoes" forever. Today it can hold a number 5, and tomorrow it can hold the word "Hello".
π¨ Visual Logic: The Data Type Tree¶
mindmap
root((Python Types))
Numeric
int
float
complex
Sequence
str
list
tuple
Mapping
dict
Set
set
Boolean
True
False
π» Implementation: Variable Lab¶
# π Scenario: Stocking the Warehouse
# π Action: Creating different types of data
# Integer (Whole number) π’
box_count = 100
# Float (Decimal) π²
price = 19.99
# String (Text) π
label = "Super Gadget"
# Boolean (True/False) β
is_in_stock = True
# List (Ordered items) ποΈ
colors = ["Red", "Blue", "Green"]
# Dictionary (Label: Value pairs) π
stats = {"weight": "2kg", "height": "10cm"}
print(f"Item: {label}, Total Boxes: {box_count}")
π Sample Dry Run¶
| Step | Instruction | Variable Name | Type | Value |
|---|---|---|---|---|
| 1 | age = 25 |
age |
int |
25 π¦ |
| 2 | age = "Old" |
age |
str |
"Old" π |
π Technical Analysis¶
- Memory: Python uses References. When you create
x = 5, Python creates an object5in memory and pointsxto it. - Mutability: Some types (like
list) can be changed inside their box. Others (liketupleorstr) cannotβyou have to replace the whole box!
π― Practice Lab π§ͺ¶
Task: Store Profile
Task: Create variables for a store: store_name, rating (decimal), and is_open. Print them all in a single sentence.
Hint: Use an f-string: f"Welcome to {store_name}!" π‘
π Best Practices¶
- Use Snake Case: Always name variables with underscores (e.g.,
user_account, notuserAccount). - Meaningful Names: Use
price_per_item, notp.
π‘ Pro Tip: "Before software can be reusable it first has to be usable." - Ralph Johnson