Python Variables
Variables are named storage locations that hold data. They act as containers for values, making your code reusable and more structured.
1. Variable Assignment:
Assign a value to a variable using the =
operator.
name = "Laeeque" # Assigns the string "Laeeque" to the variable 'name'
age = 19 # Assigns the integer 19 to the variable 'age'
2. Variable Names:
- Start with a letter (a-z, A-Z) or an underscore (_).
- Can contain letters, numbers, and underscores.
- Are case-sensitive (
myVariable
is different from myvariable
).
- Use descriptive variable names to improve the code maintainability/readability. If dealing with student ages then call it ages rather than something non-apparent without examination like lst or vals. Do not write for your short-term ease at expense of the future self and future programming team colleagues
3. Dynamic Typing:
In Python, unlike C++, or JAVA, no need to declare variable data types beforehand since handled by framework on-demand once variable populated at instantiation rather than compile-time where fixed. Improves dynamic capacity by decoupling such needs where fixed types create needless complexity in comparison. A single variable can hold different types of values (strings, numbers, objects), making Python much less rigid/clunky and thereby relatively much easier in coding where types relevant they appear when called to give meaning and not declared separately at an unrelated prior step within process flow
x = 10 # x is an integer
x = "ten" # Now x is a string
4. Multiple Assignment
Assign values to multiple variables on one line if structure useful for that sequence where no dependency means can execute steps simultaneously and not care about order for this reason unlike multi-step procedures
x, y, z = "Orange", "Banana", "Cherry"
a = b = c= "Apple" # All three now assigned "Apple"
5. Variable Scope and Lifetime
A variable’s scope determines the region of the program where it is visible or accessible. Here's more details:
- Global variables declared outside function/class definitions are accessible across entire program if explicitly designated where intended as global and not purely localized outside of code block such as for instance a function or method where default behaviour absent this specification confines usage
- Local variables: Inside code block like function exist within confined scope for ease of tracing/testing A change made locally won't reflect globally unless a parameter is passed. Local values of the same variable name don't clash with globals unless that name used in the global context too
global_var = 10 # Global
def my_function():
local_var = 5 # Local
print(global_var) # Accessing the global variable inside
my_function()
6. Reassigning Variables
Change a variable’s value, any type if suitable (dynamic typing applies here too):
x = 5 # initially
x = "Python" # reassigned