What Is a Variable?
A variable is simply a name that points to an object in memory. Unlike many other languages, Python variables do not require explicit type declarations. When you assign a value to a variable, Python automatically infers its type.
# An integer variable
x = 10
# A floating-point variable
pi = 3.14
# A string variable
name = "Alice"
Here, x, pi, and name are variables that reference an integer, a float, and a string respectively.
2 .
Basic Assignment and Dynamic Typing
Python variables are dynamically typed, meaning you can reassign them to objects of different types over time. This flexibility helps you write concise code.
Example:
value = 100 # 'value' is an integer
print(value) # Output: 100
value = "Python is fun!"
print(value) # Now 'value' points to a string: Output: Python is fun!
Notice how the type of value changes automatically based on what you assign to it.
3. Variable Naming Conventions
When naming variables, keep these guidelines in mind:
A variable name must start with a letter (a–z, A–Z) or an underscore (_).
Subsequent characters can be letters, digits (0–9), or underscores.
Avoid using Python's reserved words (like if, for, class, etc.).
Example:
_valid = 1
valid_name = "Yes"
# 2nd_var = 10 # This would be invalid, because variable names cannot start with a number.
4 .
Multiple Assignment and Swapping
Python lets you assign values to multiple variables at once. You can also swap values in a single line without needing a temporary variable.
Multiple Assignment Example:
a, b = 5, 10
print(a, b) # Output: 5 10
# Using the same value for multiple variables
x = y = z = 0
print(x, y, z) # Output: 0 0 0
Swapping exmples
# Traditional swapping without a temporary variable using tuple-unpacking
a, b = 1, 2
a, b = b, a
print("a =", a, "b =", b) # Output: a = 2 b = 1
5. Mutable vs. Immutable Variables
Variables point to objects. Some objects in Python are mutable (their state can be changed), while others are immutable.
Immutable objects: e.g., integers, floats, strings, and tuples.
Mutable objects: e.g., lists, dictionaries, and sets.
Immutable Example:
a = 10
b = a # Both 'a' and 'b' reference the integer 10
a = 20 # 'a' now references a new integer 20
print(b) # 'b' still references 10 because integers are immutable.
Mutable examples:
list1 = [1, 2, 3]
list2 = list1 # Both variables reference the same list
list1.append(4)
print(list2) # Output: [1, 2, 3, 4] - changes to 'list1' reflect in 'list2'
6. Local vs. Global Variables
The scope of a variable refers to the region of your code where that variable is accessible.
Global variables: Defined outside of functions and are accessible anywhere in the module.
Local variables: Defined within a function and accessible only within that function.
Example:
global_var = "I am global" # Global variable
def display_variables():
local_var = "I am local" # Local variable
print(local_var) # Accessible inside the function
print(global_var) # Global variable accessible inside the function
display_variables()
# print(local_var) # This would raise an error because 'local_var' is not in the global scope.
Using nonlocal in Nested Functions
When dealing with nested functions, use the nonlocal keyword to modify a variable from an enclosing (but non-global) scope.
def outer():
message = "Hello"
def inner():
nonlocal message
message = "Hello, modified!"
print("Inner:", message)
inner()
print("Outer:", message)
outer()
This example shows how nonlocal works when you need to alter a variable defined in the outer function
Introspection with globals() and locals()
Python provides built-ins for introspecting the current namespace.
globals(): Returns a dictionary representing the global symbol table.
locals(): Returns a dictionary representing the current local symbol table.
Example:
x = 5
def my_function():
y = 10
print("Local namespace:", locals())
my_function()
print("Global namespace keys:", list(globals().keys()))
Deleting Variables ::
You can delete a variable using the del statement, which can be useful if you want to free up resources or remove an identifier from the namespace.
Example:
temp = "temporary value"
print(temp) # Output: temporary value
del temp
# print(temp) # This would raise a NameError since 'temp' is deleted.
Late Binding in Closures
A common pitfall in Python is the late binding behavior in closures, which can lead to unexpected results when creating functions in a loop.
Problematic Example:
funcs = [lambda: i for i in range(5)]
results = [f() for f in funcs]
print(results) # All functions will reference the final value of 'i', often resulting in [4, 4, 4, 4, 4]
Corrected Example:
python
funcs = [lambda i=i: i for i in range(5)]
results = [f() for f in funcs]
print(results) # Output: [0, 1, 2,3,4]
Using the id() Function for Memory Inspection
Since variables in Python are labels attached to objects, you can examine the identity (i.e., memory address) of the objects they reference using id().
Examples:
a = 1000
b = a
print("ID of a:", id(a))
print("ID of b:", id(b))
a = 2000 # Now 'a' points to a new object
print("After reassigning a:")
print("ID of a:", id(a))
print("ID of b (unchanged):", id(b))
Explanation:
This shows that when you reassign a variable, you are simply pointing the variable to a new object; the previous object may still exist if referenced by other variables
Datatypes: https://grasptechnology.blogspot.com/2025/06/python-datatypes.html
No comments:
Post a Comment