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