Python Veriable
Python Veriable
Variables in Python are used to store data values. Unlike some other programming
languages, Python is **dynamically typed**, meaning you don’t need to declare a
variable’s type explicitly.
---
### **Example:**
```python
x = 10 # Integer
name = "Alice" # String
is_active = True # Boolean
```
---
❌ **Not Allowed:**
- Start with a digit (`1var` ❌)
- Special characters (`@var` ❌)
- Python keywords (`if`, `for`, `while` ❌)
### **Examples:**
```python
age = 25 # Valid
user_name = "Bob" # Valid
1st_name = "Tom" # ❌ Invalid (starts with a digit)
```
---
| Type | Example |
|------|---------|
| `int` | `x = 10` |
| `float` | `y = 3.14` |
| `str` | `name = "Alice"` |
| `bool` | `is_valid = True` |
| `list` | `nums = [1, 2, 3]` |
| `tuple` | `point = (4, 5)` |
| `dict` | `person = {"name": "Bob"}` |
### **Example:**
```python
x = 5
print(type(x)) # Output: <class 'int'>
x = "Hello"
print(type(x)) # Output: <class 'str'> (type changed dynamically)
```
---
### **Example:**
```python
a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
---
```python
PI = 3.14159
MAX_USERS = 100
```
---
### **Example:**
```python
z = 100 # Global variable
def my_func():
z = 50 # Local variable (shadows global z)
print(z)
```python
count = 0
def increment():
global count
count += 1
increment()
print(count) # Output: 1
```
---
```python
x = 10
print(x) # Output: 10
del x
print(x) # ❌ Error: name 'x' is not defined
```
---
### **Example:**
```python
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # Output: "local"
inner()
print(x) # Output: "enclosing"
outer()
print(x) # Output: "global"
```
---
---
## **Summary Table**
| Concept | Example |
|---------|---------|
| **Declare** | `x = 10` |
| **Type** | `type(x)` → `<class 'int'>` |
| **Multiple Assign** | `a, b = 1, 2` |
| **Global** | `global var` |
| **Delete** | `del x` |
| **Constant** | `PI = 3.14` |
---