Python Variable Basics
What is a Variable?
In Python, a variable is a named storage location used to hold data that can be modified during program execution. Think of variables as containers that store different types of information, such as numbers, text, or more complex data structures.
Basic Variable Creation
To create a variable in Python, you simply use the assignment operator =:
## Integer variable
age = 25
## String variable
name = "LabEx Student"
## Floating-point variable
height = 1.75
Variable Scope and Behavior
Python variables have different scopes depending on where they are defined:
graph TD
A[Global Scope] --> B[Defined outside any function]
A --> C[Accessible everywhere in the script]
D[Local Scope] --> E[Defined inside a function]
D --> F[Only accessible within that function]
Memory Management
Python automatically manages memory for variables through its dynamic typing system:
| Type |
Example |
Memory Allocation |
| Integer |
x = 10 |
Automatic |
| String |
name = "Python" |
Dynamic |
| List |
items = [1, 2, 3] |
Flexible |
Key Characteristics
- Python uses dynamic typing
- Variables can change type during runtime
- No explicit declaration is required
- Memory is automatically managed by Python's interpreter
Simple Example
## Demonstrating variable flexibility
x = 10 ## x is an integer
x = "Hello" ## Now x is a string
x = [1, 2, 3] ## Now x is a list
By understanding these basics, LabEx learners can start working with variables effectively in their Python programming journey.