Assigning variables
At the end of the previous chapter, we ran a simple Python function for the sake of testing:
print('Hello world!')
Here, "Hello world" is an argument, that is, a data point used as an input for the function. In this particular case, we used a raw data value. However, this approach won't get us far—what if we need to change this value, or use it in some other code? This can be done by using variables!
Variables are one of the most basic and powerful concepts in programming. You can think of them as aliases, similar to variables in math equations. Variables are representations of the actual underlying data in the code, which allow us to write operations and describe relations without knowing the exact values the code will operate on. This allows us to write generalized code, which can be used multiple times and in different situations.
In order to assign any value to the variable, we use the equals sign (=), as shown in the following line of code:
<variable_name> = <value>
Take a look at these examples showing the equals sign used to assign any type of value to variables:
pi = 3.14159265359 # Decimal
name = ‘Philipp' # Text
age = 31 # Integer
sky_is_blue = True # Boolean
Once a variable is assigned, it is stored in the machine's memory for the entire session, until script execution is over or the notebook's kernel is shut down. Now we can use them in our code:
>>> print(pi)
3.14159265359
Sometimes, it is convenient to assign a few variables on the same line by using packing, which makes the code more readable:
>>> x, y = 10, 5
>>> print(x)
10
>>> print(y)
5
We can always reassign the variable by using the same process:
>>> pi = 'Philipp'
>>> print(pi)
Philipp
If a variable is not defined, then Python will raise an error. This is a classic Jupyter rookie mistake: people tend to skip cells with variable assignment in the notebooks. The following is an example code block for this:
>>> print(non_existent_variable)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-4e13ec8d6c49> in <module>()
----> 1 print(non_existent_variable)
NameError: name 'non_existent_variable' is not defined