In Python, you can use different keyboard symbols to perform mathematical functions within your program. Below is a small table, showing the Python equivalent is for some basic maths operators:
English: | Python: |
Addition (Plus) | + |
Subtraction (Minus) | – |
Multiplication (Times) | * |
Division (Divide) | / |
These ‘operators’ can be used anywhere you would usually use them in maths, between variables and numbers. You can print the outcome directly, or you can assign it to a variable, like this:
x = 1 + 3
y = x * 2
This will make x = 4, and y = 8 (x times 2).
You have learned in a previous lesson that you are able to add together pieces of text, but if you are trying to add numbers you need to make sure that the variables are in number form. Otherwise, your program may do something unexpected, or simply return an error message.
We do this using the int() function, which takes whatever is inside the brackets and converts it to a number. This might look like:
x = int("0")
Now, even though “0” is a string, x is stored as a numerical variable.
Your task for this section is to write a program that asks for two numbers as input, and then prints the product of the two numbers (multiply them together).