Introduction π
Variables are one of the most fundamental concepts in Python. They act as containers for storing data β numbers, text, lists, and more. Python makes working with variables simple and flexible because it doesn't require you to declare data types explicitly.
Note
1. What Is a Variable? π€
A variable is a name that refers to a value stored in memory. Think of it like labeling a box β the label (variable name) helps you find the item inside (the value).
basic_variable.py
name = "Sathish"
age = 25
height = 5.9
is_active = True
print(name, age, height, is_active)2. Variable Naming Rules βοΈ
- Must start with a letter (aβz, AβZ) or underscore (_)
- Cannot start with a number
- Can include letters, numbers, and underscores
- Case-sensitive: Name and name are different
- Cannot use Python keywords (like if, class, for)
3. Good Variable Naming Practices π§
- Use descriptive names like total_price instead of tp
- Follow snake_case style: user_name, max_speed
- Avoid overly long names
Note
4. Dynamic Typing in Python π
Python is dynamically typed. This means the variable type is determined by the value you assign, not by explicitly declaring it.
dynamic_typing.py
x = 10 # int
x = "Hello" # now a string
x = 3.14 # now a float
print(x)Note
5. Multiple Assignments β‘
Assigning multiple variables in one line
multiple_assign.py
a, b, c = 1, 2, 3
print(a, b, c)Assigning one value to multiple variables
same_value.py
x = y = z = "Python"
print(x, y, z)6. Types of Values You Can Store π
| Type | Example | Description |
|---|---|---|
| String | "hello" | Text values |
| Integer | 42 | Whole numbers |
| Float | 3.14 | Decimal numbers |
| Boolean | True / False | Logical values |
| List | [1, 2, 3] | Ordered collection |
| Tuple | (1, 2, 3) | Immutable sequence |
| Dictionary | {"name": "Sathish"} | Key-value pairs |
7. Checking Variable Type π§ͺ
Use the type() function to check what type a variable holds.
check_type.py
x = 100
print(type(x))
y = "Python"
print(type(y))8. Constants in Python (Convention) π
Python does not have true constants, but developers use UPPERCASE names to indicate that a variable should not change.
constant.py
PI = 3.14
MAX_USERS = 100Note
9. Variable Scope π―
Scope refers to where a variable can be accessed within your code. Python has two main scopes:
- Local Scope β variables inside a function
- Global Scope β variables outside functions
scope_example.py
x = 10 # global variable
def show():
y = 5 # local variable
print(x, y)
show()
print(x)Note
Conclusion π
Now that you understand variables, you're ready to explore deeper topics like data types, operators, and expressions. Just ask for the next tutorial! π