x = 4
y = 9Variables in Python
Fundamentals: Variables in Python
In computer programming, variables are used to store, process, and manipulate data.
Let’s say we want to store 4 in the variable x, and 9 in the variable y. This is what we would do:
Both x and y are now variables. When we print a variable, we will see the value that is stored in it.
print(x)4
We can perform arithmetic operations with variables as well. Take a look at the following example: \[y = f(x) = a \cdot x + b\] with \[\begin{cases} a=2 \\ b=3 \end{cases}\] We want to know the value of \(y\) when \(x = 4\), i.e. \(f(4)\).
We use \(f(x)\) to better understand what parameters are used.
a = 2
b = 3
x = 4
y = a * x + b
print(y)11
However, in order to operate with variables, we need to make sure that they are defined first. If we try to use a variable that has not been defined, we will get an error.
q = 8
p = q * t # Will fail because t is not defined
print(p)If you are working on a notebook, Python will keep in memory the variables you have defined in previous cells. This means that you can use them in later cells without having to redefine them.
# This print will work if you have defined x in a previous cell
print(x)4
Given x = 1/2, compute:
\[y = \sqrt{\frac{3x - 1}{x^3}}\]
x = 0.5
y = ((3 * x - 1) / x ** 3) ** (1/2)
print(y)2.0
Homework and Review
When you feel ready, you can test your knowledge by working through the review exercises.
Then, work through the “Numeric Variables” homework exercises available here. To earn participation credit, you must complete the exercises highlighted in red.