loopswhile-looppython-3.8

My while true loop which is supposed to count to 100 with breaks isn't working


I was supposed to create a while true loop. The program should be counting to 100, printing each number. However, instead of counting the multiples of 3, 5 and 3 and 5 the program has to print a sentence. The loop should exist after printing the number 100. But my program isn't running at all.

I would like for my program to print every number from 1-100, but for multiples of 3, 5 and 3 and 5 it should be pronting a different sentence. For example: multiple of 3 print x, Multiples of 5 print y and multiples of 3 and 5 print xy. It should break on 100 This is the code i have currently written:

count = 1
while True:
  if count % 3 == 0 and count % 5             == 0:
     print("hello there, you gorgeous")
     count = count + 1
     continue
  if count % 3 == 0:
     print("hello world")
     count = count + 1
     continue
  if count % 5 == 0:
     print("love yourself")
     count = count + 1
     continue
  if count > 100:
     break
     print(count)
     count = count + 1

Solution

  • There are a few issues:

    Here is your code with minimal corrections. Comments indicate where the above points were corrected:

    count = 1
    while True:
      if count > 100:  # this condition must be tested in each iteration
         break
      print(count)   # Always print the number
      if count % 3 == 0 and count % 5 == 0:
         print("hello there, you gorgeous")
         count = count + 1
         continue
      if count % 3 == 0:
         print("hello world")
         count = count + 1
         continue
      if count % 5 == 0:
         print("love yourself")
         count = count + 1
         continue
      count = count + 1  # indentation issue solved
    

    This solves the issues, but:

    count = 1
    while True:
        if count > 100:
            break
        print(count, end=" ")   # print phrase on the same line as number
        # use if-elif to avoid duplication
        if count % 15 == 0:  # avoid two modulo operations here
            print("hello there, you gorgeous")
        elif count % 3 == 0:
            print("hello world")
        elif count % 5 == 0:
            print("love yourself")
        else:
            print()
        count += 1
    

    Finally, although I understand you were asked to use while True, this is not the right practice for this scenario. This is the ideal candidate for a range based loop:

    for count in range(1, 101):
        print(count, end=" ")   # print phrase on the same line as number
        # use if-elif to avoid duplication
        if count % 15 == 0:  # avoid two modulo operations here
            print("hello there, you gorgeous")
        elif count % 3 == 0:
            print("hello world")
        elif count % 5 == 0:
            print("love yourself")
        else:
            print()
        count += 1