-4

I need the solution for a function that prints numbers from 1 to 100. For multiples of three print “Foo” instead of the number and for the multiples of five print “Bar”. For numbers which are multiples of both three and five print “FooBar”. For the remaining numbers just print this number.

i = 0
while I < 100:
     i += 1
     print(i)
     if i == 3:
       print("Foo")
  • What have you tried so far? [Stack Overflow expects that you make a reasonable attempt to solve an issue on your own](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), and the community generally won't do your homework for you. You should [edit] your question to include anything at all that you've tried so far to solve this. – Hoppeduppeanut Feb 11 '19 at 03:10
  • Possible duplicate of [Python FizzBuzz](https://stackoverflow.com/questions/22743860/python-fizzbuzz) – Hoppeduppeanut Feb 11 '19 at 03:23

3 Answers3

0
i = 0
while i < 100:
    i += 1
    if i%15 == 0:
        print('FooBar')
    elif i%3 == 0:
        print('Foo')
    elif i%5 == 0:
        print('Bar')
    else:
        print(i)

Apply if and else statement to decide which is the situation during the while loop. Also, % could return the remainder. 3 and 5 both are prime numbers, so a number which % (3*5) == 0 indicates itself is a multiples of 3 and 5.

Zihan Yang
  • 31
  • 3
0

You will have to use mod (%) to check the remainder of a division. See if i % 3 is equal to 0. If this is true, then print FOO. If i % 5 equal 0, print Bar; and so on.

RDKaizhar
  • 58
  • 1
  • 1
  • 6
0

I would recommend using an if else statement in your while loop after the index counter. Something like...

i = 0
while i <= 100:
    i += 1
    if i % 15 == 0:
        print("foobar")
    elif i % 3 == 0;
        print("foo")
    elif i % 5 == 0:
        print("bar")
    else:
        print(i)

Using % returns the remainder and if that returns a remainder of 0 then you know that it is evenly divisible by that number.

eNgE
  • 16
  • 2