Variables
A variable is a named reference to a value stored in memory. In Python you create a variable simply by assigning a value to a name: x = 10. There is no nee...
What is a Variable?
A variable is a named reference to a value stored in memory. In Python you create a variable simply by assigning a value to a name: x = 10. There is no need to declare the type in advance. Python figures out the type based on the value assigned. Variable names must start with a letter or underscore, can contain letters, digits, and underscores, and are case-sensitive (age, Age, and AGE are three different variables).
Dynamic Typing
Python is dynamically typed, meaning a variable can hold different types at different points during execution. x = 5 makes x an integer; later x = "hello" makes the same name reference a string. The variable does not have a fixed type — the object it points to does. You can check what type an object is with type(x), which returns something like <class 'int'>. This flexibility is powerful but requires care to avoid type-related bugs.
Naming Conventions
Python's style guide (PEP 8) defines naming conventions that professional developers follow. Regular variables and function names use snake_case (my_variable, calculate_total). Constants are written in UPPER_SNAKE_CASE (MAX_SIZE, PI). Class names use PascalCase (MyClass, BankAccount). Names starting with a single underscore (_private) signal internal use. Names starting with double underscore (__mangled) trigger name mangling in classes. Following these conventions makes code readable and professional.
Multiple Assignment
Python allows multiple variables to be assigned in a single line. To assign the same value to several names: a = b = c = 0. To assign different values: x, y, z = 1, 2, 3. This is called tuple unpacking and works with any iterable on the right side. You can swap two variables without a temporary variable: a, b = b, a. This elegant swap is often highlighted as a Python feature in interviews.
Variable Scope Preview
Where a variable is accessible depends on where it is defined. A variable created inside a function is local to that function and cannot be accessed outside it. A variable created at the top level of a module is global. Python uses the LEGB rule to resolve names: Local, then Enclosing, then Global, then Built-in. This scope model is covered in depth in the Functions section, but understanding that scope exists is important from the very beginning.
Exam Tip
A common exam trap: the statement x = x + 1 inside a function raises an UnboundLocalError if x was defined globally but not declared global inside the function. Python sees the assignment and treats x as local, but x is not yet defined locally when the right side is evaluated. The fix is to add global x at the top of the function. Another frequent question: what does id(x) return? It returns the memory address of the object x refers to.