Variables
A variable is used to store data that will be used by the program. This data can be a number, a string, a Boolean, a list or some other data type. Every variable has a name which can consist of letters, numbers, and the underscore character _
.
The equal sign =
is used to assign a value to a variable. After the initial assignment is made, the value of a variable can be updated to new values as needed.
Plus Equals
Python offers a shorthand for updating variables. When you have a number saved in a variable and want to add to the current value of the variable, you can use the +=
(plus-equals) operator.
The plus-equals operator also can be used for string concatenation, like so:
The +=
operator allows adding more than just a single value at a time. Anything on the right-hand side of the +=
will be evaluated, and then it will be added to the variable which is then updated to that new value.
The Scope of Variables
In Python, a variable defined inside a function is called a local variable. It cannot be used outside of the scope of the function, and attempting to do so without defining the variable outside of the function will cause an error.
A variable that is defined outside of a function is called a global variable. It can be accessed inside the body of a function.
In the example, the variable a
is defined both inside and outside of the function. When the function f1()
is implemented, a
is printed as 2
because it is locally defined to be so. However, when printing a
outside of the function, a
is printed as 5
because it is implemented outside of the scope of the function.
Last updated
Was this helpful?