In Python, variables are names that map to particular pieces of data. They are fundamental to most programming languages and essential for effective programming.
Creation and Assignment
Declaration and Assignment: Variables in Python are created when you first assign a value to them. Python is dynamically typed, so you don’t need to explicitly declare variable types.
Example:
my_variable = 10
my_string = "Hello, Python!"
Dynamic Typing
Type: The type of a variable is determined at runtime. The same variable can store different data types at different times. An integer can later become a string, list, or any other object.
Example:
x = 4 # x is of type int
x = "Sally" # x is now of type str
Variable Names
Naming Rules: Variable names must start with a letter or underscore, followed by letters, digits, or underscores. They are case-sensitive, so age, Age, and AGE are three different variables.
Valid variable names:
myVariable = "John"
_myVariable = "John"
my_variable = "John"
MYVARIABLE = "John"
myvariable2 = "John"
Mutable vs Immutable Data Types
When you assign a value, you’re assigning a reference to an object. Objects can be either mutable (changeable) or immutable (unchangeable).
Immutable Types:
int,float,bool,str,tuple,frozenset. When modified, a new object is created.Mutable Types:
list,dict,set. These objects can be changed after creation.
Scope and Lifetime
Scope: The part of code where a variable is accessible. Python has local, global, and nonlocal scopes. Variables declared inside functions are local; those outside are global.
Lifetime: The period a variable exists in memory. Global variables exist until the program ends; local variables exist only within their function.
Reassignment and Garbage Collection
Python’s garbage collector automatically handles memory. When a variable is reassigned, the reference to its original object is replaced. If no references remain, the original object is garbage collected.
Understanding these aspects helps manage data effectively throughout a program’s lifecycle, making code more readable, maintainable, and efficient.