I was trying to solve the famous (infamous?) Fizzbuzz challenge the other day as a part of my Python learning program and I learnt a lot about Loops in Python! I know 'fizzBuzz' can sound like a cliche challenge for beginners, but hey, I am a beginner and here to learn. So I am trying to go over the points I learnt about loops in Python, and then I will get to the solution for FizzBuzz. Before you proceed, note that this is a post for beginners like me!
For Loops:
A for loop is used for iterating over a collection of items such as lists. Iteration (another word for repetition!) is the repetition of a process in order to generate an outcome. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration. We can use for loops to execute a set of statements, once for each item in a list:
names = ["John", "Jack", "Ava"]
for name in names:
print(name)
#will print out:
#John
#Jack
#Ava
The break Statement: If you want the loop to stop at one point without going through all the items, you should use ‘break’ in the following way:
names = ["John", "Jack", "Ava"]
for name in names:
print(name)
if name == "Jack":
break
#It gets to Jack and breaks the flow. will print out:
#John
#Jack
The continue Statement: If you want to skip an item during the loop, you should use the continue statement :
names = ["John", "Jack", "Ava"]
for name in names:
print(name)
if name == "Jack":
continue
# It gets to Jack then skips it and goes to the next. will print out
#John
#Ava
The range() Function: Using range() function allows us to loop through a set of instructions for a specified number of times. The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number:
for i in range(5):
print("John")
#will print out John five times
for i in range(1, 5):
print(i)
#will print out 1 to but NOT including 5
#1
#2
#3
#4
Now, let's get to the FizzBuzz challenge.
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
Since the sequence of conditions is important, we should check for a number which is divisible by both 3 and 5. Why? Imagine the loop gets to 15 and the first condition is 'if number % 3==0', then since 15 is divisible by 3, the code will print out 'fizz'.
#our range is from 1 to but not including 101
#if the number is divisible by both 3 & 5, then print 'fizzbuzz'
#if only divisible by 3, then 'fizz'
#if only divisible by 5, then 'buzz'
for number in range(1,101):
if number % 3==0 and number%5==0:
print("fizzbuz")
elif number%3==0:
print("fizz")
elif number%5==0:
print("buzz")
else:
print(number)