Python Variables
Declaring variables
It is easy to declare a variable in Python and assign a value or another variable to it. For example, to declare a variable m and assign the value 5 to m is as follows:
m = 10
If you have been programming in other programming languages such as C/C++or Java, you notice that a variable in Python does not require an associated data type like other do. Python variables can be set to any object. Let’s take a look at another example:
m = 10 # numeric type
print(m)
m = "this is a string" # string type
print(m)
First we defined a variable m and assign value 10 to it. And then we assign a string to m which is perfectly correct in Python. The rule here is the new assignment will override the old assignment. First m refers to integer object and then m refers to a string object.
Python provides del statement to delete a variable. If you are trying to get the value of a variable after it is deleted, you will get an error.
It is noted that the variable name in Python is case sensitive. Meaning variable m and M is different.
Variable scope
In python variable has it own scope. Let’s take a look at an example:
def f1():
n = 20
print(n)
s = 'hello'
In above example, variable n is a local variable. It only exists inside the function f1. Because the existence of variable n is only inside the function f1 therefore you cannot refer to it outside of the function. In the example above, variable s is global variable.