Now, we step into the realm of variables. Variables are like containers that allow us to store and manipulate data within our programs. They provide a means to reference objects and work with values efficiently. Once an object is assigned to a variable, you can refer to the object by that name. The data of the object can be accessed or modified using the variable. Variables are fundamental to programming as they enable us to write flexible and dynamic code.
If you haven’t already, I recommend following along in your own Python interpreter or text editor to practice these concepts.
Assignment statements
An assignment statement is used to assign a value to a variable. This is done using the assignment operator, which is the equals sign (=
). Assignment statements are straightforward yet powerful, as they allow you to initialize and update the values that variables hold.
Here, the variable x
is assigned the value 5
.
In this case, x
is assigned the value 5
, and y
is assigned the value 10
.
Here, x
, y
, and z
are all assigned the value 0
.
After this operation, x
will be 6
Note: You cannot assign to an expression in Python. For instance, 5 = x or (x + y) = z
are invalid and will result in an error.
Using variables
Naming conventions
Using reserved words can lead to errors or unexpected behavior in your code.
Types of variables
There are two types of variables: local variables and global variables. Local variables are declared inside a function and are only accessible within that function. Global variables are declared outside any function and are accessible anywhere in the code.
Example of a local variable
my_function() # Output: This is a local variable
In this example, local_var
is a local variable and can only be accessed within my_function
.
Example of a global variable
my_function() # Output: This is a global variable
In this example, global_var
is a global variable and can be accessed both inside and outside the function.
Variable scope
The scope of a variable is the area of the code where it is accessible. The scope is determined by where the variable is declared. Variables in the global scope are accessible anywhere in the code, whereas local variables are confined to their respective functions. Understanding scope is crucial for writing clean and error-free code.
For example:
outer_function()
Quiz Question
Hint:
The correct answer is B) To assign a value to a variable.
Quiz Question
Hint: Consider the conventions and rules for naming variables in Python. What are the commonly accepted practices for naming variables in Python code?
The correct answer is D) Variable names should typically be in snake_case.