Division and Remainder
You already know that division with / always gives a decimal number, even when the result is whole:
print(7 / 2)
print(6 / 2)This prints:
3.5
3.0Decimal numbers are written with a dot: 1.5, never with a decimal comma (1,5), which is used in some countries. In Python, a comma separates values, so print(1,5) doesn't print one and a half, but two numbers: 1 5.
Sometimes the last digit of a decimal result is a little off: print(0.1 + 0.2) prints 0.30000000000000004. Computers store decimal numbers with a tiny inaccuracy. It's not a mistake in your program, so don't let it surprise you.
Often, you need to divide whole numbers the way you learned in elementary school: how many times does one number go into another, and what is left over? Python has two operators for that:
//(two slashes) is whole-number division: it says how many times one number goes into another, and drops what is left over.%(the percent sign) gives the remainder: what is left over. Programmers call this operation modulo.
print(7 // 3)
print(7 % 3)This prints:
2
13 goes into 7 twice (2 × 3 = 6), and 1 is left over: 7 = 2 × 3 + 1. So 7 // 3 is 2 and 7 % 3 is 1. When a number divides evenly, nothing is left over: 10 % 5 is 0.
% is often used to tell even and odd numbers apart. An even number divided by 2 leaves nothing, an odd number leaves 1:
print(8 % 2)
print(9 % 2)This prints:
0
1So a number is even when its remainder after dividing by 2 is 0. This will come in handy in the next lessons, when your programs start making decisions.
Instructions
- 1
Print the price of half a chocolate bar:
chocolate_pricedivided by2. - 2
How many chocolate bars can you buy with the money in
wallet? Create a variablebarswith the result of dividingwalletbychocolate_pricewith//. - 3
How much money will you have left? Create a variable
money_leftwith the remainder after dividingwalletbychocolate_price. Use%. - 4
Print both values, like this:
Bars: 2 Money left: 10 - 5
Is the price of a chocolate bar even or odd? Print the remainder after dividing
chocolate_priceby2.