Variables & Data Types
Variables & Data Types
Section titled “Variables & Data Types”Python is dynamically typed — you don’t declare a type, the interpreter infers it at runtime.
Declaring Variables
Section titled “Declaring Variables”name = "Alice"age = 30price = 9.99is_active = Truenothing = NoneBuilt-in Data Types
Section titled “Built-in Data Types”| Category | Types |
|---|---|
| Text | str |
| Numeric | int, float, complex |
| Boolean | bool |
| Sequence | list, tuple, range |
| Mapping | dict |
| Set | set, frozenset |
| Binary | bytes, bytearray, memoryview |
| None | NoneType |
Type Checking
Section titled “Type Checking”x = 42print(type(x)) # <class 'int'>print(isinstance(x, int)) # TrueType Conversion (Casting)
Section titled “Type Conversion (Casting)”# Implicitresult = 5 + 2.0 # float: 7.0
# Explicitn = int("42") # 42f = float("3.14") # 3.14s = str(100) # "100"b = bool(0) # Falselst = list("abc") # ['a', 'b', 'c']Multiple Assignment
Section titled “Multiple Assignment”a = b = c = 0x, y, z = 1, 2, 3first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]Constants (Convention)
Section titled “Constants (Convention)”Python has no const keyword. Use ALL_CAPS by convention:
MAX_SIZE = 100PI = 3.14159Variable Scope Preview
Section titled “Variable Scope Preview”- Variables defined inside a function are local.
- Variables defined at module level are global.
- Use
globalkeyword to modify a global inside a function.
count = 0
def increment(): global count count += 1Common Pitfalls
Section titled “Common Pitfalls”# Mutable default — avoid thisdef append_item(item, lst=[]): # BAD: lst shared across calls lst.append(item) return lst
# Safe versiondef append_item(item, lst=None): if lst is None: lst = [] lst.append(item) return lst