Q#30: Oh foo-ie!

Write a function that takes in an integer n, and prints out integers from 1 to n inclusive.

Additionally, if %3 == 0 then print “foo” in place of the integer, if %5 == 0 then print “ie” in place of the integer, and if both conditions are true then print “foo-ie” in place of the integer.

TRY IT YOURSELF

ANSWER

This question is rather straightforward and tests your ability to problem solve as well as write basic code. Any language works, but we will stick to Python as it is one of the most commonly used languages for Data Scientists.

The trick here is to organize your IF, ELIF and ELSE statements to be inclusive of the conditions asked for. First, lets define a function in python using the keyword def <function-name>, with one argument n. Then we need to iterate across all the integers from 1 to n using a FOR loop and the range() function with care to specify start as 1 and end as n+1 (because normal range, in Python, starts at 0 and is not inclusive of the final number). Next, we can design our IF statements such that the first condition (divisible by 3) is satisfied and inside this first conditional we can also check if it is divisible by 5. Then we can add an ELIF statement for only divisible by 5, finally followed by an Else statement that outputs the integer we are on in our for loop.

def foo_ie(n):
for i in range(1,n+1):
if i % 3 == 0:
if i % 5 == 0:
print("foo-ie")
else:
print("foo")
elif i % 5 == 0:
print("ie")
else:
print(i)

--

--