LPTHW – Exercise 3: Numbers and Math
Outline
- LEARN PYTHON THE HARD WAY Study Drills – 3
- 1. Above each line, use the # to write a comment to yourself explaining what the line does.
- 2. Remember in Exercise 0 when you started Python? Start Python this way again and, using the above characters and what you know, use Python as a calculator.
- 3. Find something you need to calculate and write a new .py file that does it.
- 4. Notice the math seems “wrong”? There are no fractions, only whole numbers. Find out why by researching what a “floating point” number is.
- 5. Rewrite ex3.py to use floating point numbers so it’s more accurate (hint: 20.0 is a floating point).
LEARN PYTHON THE HARD WAY Study Drills – 3
This was the first tricky one, and probably deliberately so.
For the first example: *
and %
take precedence over -
, so we first evaluate 25 * 3 % 4
. *
and %
have the same priority and associativity from left to right, so we evaluate from left to right, starting with.25 * 3
This yields 75
. Now we evaluate 75 % 4
, yielding.3
Finally, 100 - 3
is 97
.
print("I will now count my chickens:") print("Hens", 25 + 30 / 6) # % and * have identical priority so do from left to right. - is lower priority so... # 3 * 25 = 75 >>> 75 % 4 = 3 >>> 100 - 3 = 97 print("Roosters", 100 - 25 * 3 % 4) print("I will now count the eggs:") # 4 % 2 = 0 and 1 / 4 = 0 too because without a decimal place it's a non-floating point # number so it only deals in whole numbers... # 6 - 5 + 0 - 0 + 6 = 7 print(3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4.0 + 6) print("Is it true that 3 + 2 < 5 - 7?") print(3 + 2 < 5 - 7) print("What is 3 + 2?", 3 + 2) print("What is 5 - 7?", 5 - 7) print("Oh, that's why it's False.") print("How about some more.") print("Is it greater?", 5 > -2) print("Is it greater than or equal?", 5 >= -2) print("Is it less or equal?", 5 <= -2)
1. Above each line, use the # to write a comment to yourself explaining what the line does.
Done for the difficult maths entries. The print statements otherwise are very obvious.
2. Remember in Exercise 0 when you started Python? Start Python this way again and, using
the above characters and what you know, use Python as a calculator.
Its works
3. Find something you need to calculate and write a new .py file that does it.
This was too redundant. You can add calculations to this file or do study drill 2. There’s a limit to useful repetition
4. Notice the math seems “wrong”? There are no fractions, only whole numbers. Find out
why by researching what a “floating point” number is.
Great, what about the 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
one?
Well, this one breaks down to:
(3 + 2 + 1) - 5 + (4 % 2) - (1/4) + 6
then
6 - 5 + 0 - 0 + 6
So…
1 + 6 = 7
But why does 1/4 = 0
?
Simple answer, floating point numbers. Here’s a great video on floating point numbers, but the basic answer is if you try again using 1.0
and 4.0
, you’ll get the answer 0.25
, which would lead to:
1 - 0.25 + 6 = 6.75