π Pythonπ
Day 2
Variables in Python
Create and use variables in Python. Dynamic typing, common types and assignment patterns.
π―
Learning objectives
- βCreate variables without declaring a type
- βRecognise the common built-in types
- βUse multiple and swap assignment
π‘ Key points
- Python is dynamically typed β the type is attached to the value, not the variable.
- A variable is created the first time you assign to it: no declaration needed.
- Common built-in types: int, float, str, bool, list, tuple, dict, set.
- Constants are conventional β write them in UPPER_CASE; Python has no true 'const'.
π» Code examples(3)
#1Basic assignments
pythonage = 21
price = 99.99
name = "Rohan"
is_active = True
PI = 3.14159 # convention: uppercase = constant
Type is inferred from the value. bool literals are True / False (capitalised).
#2Dynamic typing
pythonx = 10
print(type(x)) # <class 'int'>
x = "hello"
print(type(x)) # <class 'str'>
The same name can point to different types at different times. type() returns the current type of the value.
#3Multiple + swap assignment
pythona, b, c = 1, 2, 3 # multiple assignment
x = y = z = 0 # chained
a, b = b, a # swap without a temp variable
Tuple unpacking makes multi-assignment and swaps a one-liner.
π― Practice
Q1. What is the output: `x = 5; x = 'hello'; print(type(x))`?+
<class 'str'> β the name x now refers to a string.
Q2. Swap the values of a=10 and b=20 in one line.+
a, b = b, a
Q3. Does Python have a `const` keyword?+
No. UPPER_CASE naming is a convention to signal 'do not modify', but the value can still be reassigned.
π Notes
Common built-in types
| Type | Example | Notes |
|---|---|---|
| int | 42 | Arbitrary precision β no overflow |
| float | 3.14 | 64-bit IEEE 754 |
| str | "hello" or 'hi' | Immutable Unicode string |
| bool | True, False | Subclass of int (True == 1) |
| list | [1, 2, 3] | Mutable ordered sequence |
| tuple | (1, 2, 3) | Immutable ordered sequence |
| dict | {"a": 1} | Keyβvalue map |
| set | {1, 2, 3} | Unique, unordered |
Naming rules
- Start with a letter or
_; then letters, digits or_. - Case-sensitive:
nameandNameare different. - Cannot be a Python keyword.
- Convention:
snake_casefor variables and functions.