The Self-Taught Computer Scientist


Download 1.48 Mb.
Pdf ko'rish
bet62/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   58   59   60   61   62   63   64   65   ...   147
Bog'liq
books-library.net-11301817Az7X6

Chapter 6 Math
71
Even though you want to find the numbers from 1 to 100, it is best to pass in a number
n
, instead 
of hard- coding 100. Passing in 
n
makes your program flexible if you want to run your program with 
a different number. So, your function
fizzbuzz
, accepts 
n
as a parameter.
def fizzbuzz(n):
First, you use a 
for
loop to iterate through each number from 1 to 
n
+ 1.
for i in range(1, n + 1):
Then, you use a conditional statement with the modulo operator to determine if the number
i
, is 
divisible by both 3 and 5. If it is, you print “FizzBuzz.”
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
Next, you use another conditional statement to check if the number is divisible by 3. If it is, you 
print “Fizz.”
elif i % 3 == 0:
print('Fizz')
Then you use one more conditional statement to see if the number is divisible by 5. If it is, you 
print “Buzz.”
elif i % 5 == 0:
print('Buzz')
If the number is not divisible by 3, 5, or both, you print the number.
else:
print(i)
When you run your program, you will see that numbers that are divisible by 3, like 6 and 27, say 
“Fizz.” Numbers that are divisible by 5, like 10 and 85, say “Buzz,” and numbers divisible by both, 
like 15 and 30, say “FizzBuzz.”
>> 1 2 Fizz 4 Buzz Fizz 7 8...Buzz Fizz 97 98 Fizz Buzz
Your algorithm takes 
n
steps, which means it is linear. If you pass in 
100
, your algorithm will take 
100 steps, and if you pass in 
1000
, it will take 1,000 steps.
The modulo operator was the key to solving this problem. The modulo operator is not just useful 
in technical interviews, though. It is also useful when you are building real- world applications. For 
example, say you have a text file that is 50,000 lines long, and you can fit 49 lines on a page.



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   58   59   60   61   62   63   64   65   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling