A computer is a fast, exact calculator. Put a calculation inside print() without quotes and it prints the result, even for huge numbers:
print(278 + 422) print(3000 - 850) print(7 * 6) print(48 / 6) print(300000000000 * 200000000000)
700 2150 42 8.0 60000000000000000000000
Sometimes you don't want a decimal answer, but how many whole times a number fits and what is left over. For example: 17 sweets shared by 5 children.
print(17 / 5) print(17 // 5) print(17 % 5) print(2 ** 3)
3.4 3 2 8
| Operation | Symbol | Example | Result |
|---|---|---|---|
| Add | + | 278 + 422 | 700 |
| Subtract | - | 3000 - 850 | 2150 |
| Multiply | * | 7 * 6 | 42 |
| Divide | / | 17 / 5 | 3.4 |
| Whole division (no fraction) | // | 17 // 5 | 3 |
| Remainder | % | 17 % 5 | 2 |
| Power | ** | 2 ** 3 | 8 |
Order of operations
Just like in maths: power first, then multiply and divide, then add and subtract. Brackets come before everything:
print(2 + 3 * 4) print((2 + 3) * 4)
14 20
Numbers and text
Any value in quotes is text (str), even if it is digits. A whole number is an int and a decimal is a float. type() tells you the type:
print(type(100))
print(type("100"))
print(type(8.0))
print(10 + 5)
print("10" + "5")<class 'int'> <class 'str'> <class 'float'> 15 105
+ between two texts glues them. You cannot glue text to a number directly, so turn the number into text with str(). The other way round, int() turns digit text into a number:
print("2 bottles of juice " + str(200 * 2) + " pounds")
print(int("25") + 5)2 bottles of juice 400 pounds 30
juice400pounds.Practice
Make the computer calculate 3000 - 850 and print the result.
Press Run to see the result. Make the computer calculate 300000000000 × 200000000000 and print the result.
Press Run to see the result. A bottle of juice costs 200 pounds. Fill in the blank to print 2 bottles of juice 400 pounds, letting the computer calculate 200 × 2.
print("2 bottles of juice " + ___ + " pounds")Press Run to see the result. The program prints The answer is 2 * 5. Change it to print The answer is 10., with the computer calculating 2 × 5.
print("The answer is 2 * 5.")Press Run to see the result. Print the data type of the value "100" (with the quotes) using type().
Press Run to see the result. A film lasts 125 minutes. Print 2 h 5 min, letting the computer work out the hours with // and the leftover minutes with %.
Hint
An hour is 60 minutes.Press Run to see the result. Mariam bought 3 notebooks at 15 pounds each and a pen for 10 pounds. Print Total: 55 pounds, letting the computer calculate 3 × 15 + 10 in one line.
Press Run to see the result. Key points
- Operators:
+ - * /, plus//for whole division,%for remainder and**for power. - Multiply and divide before add and subtract; brackets before everything.
- Anything in quotes is text;
str()turns a number into text to join with+, andint()turns text into a number.