Python Programming Exercises, Gently Explained
18
3
or 5 before checking if it’s divisible by 3
and 5. You’ll want to check if a number is divisible by 3 and
5 first, because these numbers are also divisible by 3 and 5. But you want to be sure to display
'FizzBuzz'
rather than 'Fizz' or 'Buzz'.
Another way to determine if a number is divisible by 3 and 5 is to check if it is divisible by 15.
This is because 15 is the least common multiple (LCM) of 3 and 5. You can either write the condition
as number % 3 == 0 and number % 5 == 0 or write the condition as number % 15 == 0.
The range() function tells for loops to go up to
but not including their argument. The code for
i in range(10):
sets i to 0 through 9, not 0 through 10. You can specify two arguments to tell
range()
to start at a number besides 0. The code for i in range(1, 10): sets i to 1 to 9. In
our exercise, you want to include the number in upTo, so add 1 to it: range(1, upTo + 1)
Python’s list() function can take a range object returned from range() to produce a list of
integers. For example, if you need a list of integers 1 to 10, you can call list(range(1, 11)). If
you need every even number between 150 up to and including 200, you can call
list(range(150, 202, 2))
:
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(150, 202, 2))
[150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180,
182, 184, 186, 188, 190, 192, 194, 196, 198, 200]
Now try to write a solution based on the information in the previous sections. If you still have
trouble solving this exercise, read the
Solution Template section for additional hints.
Dostları ilə paylaş: