1. Arithmetics and variables

1. Arithmetics and variables#

Arithmetics#

In its most basic form, Python can simply be used as a calculator. You can use it to, among others, add, subtract, multiply, and divide numbers.

The following cell shows you how to add two numbers in Python:

print(2 + 3)
5

To show any object within Python in your console, you can use the print(…) command, in which you can replace “…” with the object that you want to display. In this case, it is the answer of 2+2.

Other numeric calculations can be performed like this:

print(3 * 4)  # Multiplication
print(3 - 2)  # Subtraction
print(10 / 2)  # Division
print(10 ** 2)  # Exponentiation
print(10 % 3)  # Modulo
12
1
5.0
100
1

The “#” symbol is used to comment out code. This means that the code following the # symbol will not be executed. Comments are useful to explain what the code does.

Variables#

In Python, you can also store values in variables. This is useful when you want to use a value multiple times in your code. You can assign a value to a variable using the = operator. Variables can take any name. In a practical analysis, it is suggested to use meaningful names for your variables. This makes it easier for you and others to understand the code.

The following cell shows how to assign a value to a variable and then print it:

x = 5
print(x)
5

If you want to alter the variable, you can also do this using the “=” operator:

x = 5
print(x)
x = x + 5
print(x)
5
10

You can thus use variables as placeholders for objects. In this case, x is assigned to be an integer (a whole number). If we define another variable y to be an integer as well, we can perform calculations with these variables:

x = 5
x = x + 2
y = 10
z = x + y
print(z)
17

Exercise#

Now it is your turn! Solve the following exercise and click on the hidden code cell below to view the solution.

Exercise 1#

Calculate the sum of 5 and 7 and store the result in a variable called “var1”. Then multiply this variable with itself and store the result in a variable called “var2”. Finally, print the result of “var2”.

# Your code here
Hide code cell content
var1 = 5 + 7
var2 = var1 * var1
print(var2)
144

Exercise 2#

đź§  What is the correct syntax for multiplying 3 with 7, storing the result in a variable, and printing that variable?