Arithmetic Operations
Python can also calculate. For the basic arithmetic operations, it uses these operators (symbols for operations):
+addition-subtraction*multiplication (an asterisk, because there is no × on the keyboard)/division (a slash instead of ÷)
When you put a calculation in print(), it prints the result:
print(10 + 1)
print(7 * 6)
print(10 - 5 / 5)This prints:
11
42
9.0Why is the last result 9 and not 1? Just like in math, multiplication and division are done before addition and subtraction. So Python first calculates 5 / 5, which is 1, and then 10 - 1, which is 9. Operations of the same level, such as + and -, are done from left to right. If you want a different order, use parentheses, again as in math:
print((10 - 5) / 5)This prints 1.0: first 10 - 5 in the parentheses, then 5 / 5.
And why 9.0 and 1.0, and not 9 and 1? Division with / always gives a decimal number, even when the result is whole: 6 / 2 is 3.0. Python prints a decimal number with a decimal point, so you see .0 at the end. The value is the same, it's only a different kind of number.
The spaces around the operators don't change the result. We write them because they make the code easier to read.
Careful with quotes: anything in quotes is text, and text is printed exactly as it is written, without calculating anything:
print("10 - 5 / 5")This prints:
10 - 5 / 5You can also print several values at once: separate them with commas inside the parentheses. print() prints them on one line, with a space between them. This is handy for printing a calculation together with its result:
print("10 - 5 / 5 =", 10 - 5 / 5)This prints:
10 - 5 / 5 = 9.0The first value is text, so it is printed as it is written. The second one is a calculation, so its result is printed.
Instructions
- 1
Print the result of
2 + 3 * 4. Before you click Run, guess what it will print. - 2
On the next line, print the result of the same calculation, but with parentheses that make the addition come first:
(2 + 3) * 4. - 3
On the next line, print the calculation and its result on one line, like this:
(2 + 3) * 4 = 20Write the calculation in quotes as the first value, then a comma, and then the calculation itself, without quotes.