Loops and If Statements

As you can probably guess from now, yes you can place loops inside if statements and if statements inside loops.

An if statement inside a loop would (in most computer programming languages) take the generic form of:

FOR counter in range(n)
IF (boolean expression) THEN
Statements to be performed
ENDIF
END

or using While loops:

WHILE counter1 <= n :
IF (boolean expression) THEN
Statements to be performed
ENDIF
counter1 = counter1 + 1
END

Here is one of the most well-known examples of the exercises that you might be given as the opening question in a junior data scientist job interview.

The task is: Go through all the whole numbers up until 100. Print ‘fizz’ for every number that’s divisible by 3, print ‘buzz’ for every number divisible by 5, and print ‘fizzbuzz’ for every number divisible by 3 and by 5! If the number is not divisible either by 3 or 5, print a dash (‘-‘)!

In a flow chart it looks like:

Loops and If Statements

The following code snippet is the solution to the above problem: