Home > other >  Loop is not working and it stops on the first input
Loop is not working and it stops on the first input

Time:07-11

I have this exercise where:

a) Receives an integer or real number (float) #but actually it doesnt matter if it's an int or float

b) If the number is > 193, print Goal Achieved and exit the loop. Otherwise, print Insufficient and return to step 1 (reading a new number n). You must read a maximum of 5 numbers

And that's the problem.. i'm missing the way to make the code return to the top and read another input

My code:

while True:
    number = int(input())  #this sould be in float but doesnt make any difference in the exercise itself
    if number > 193:
        print ("Goal Achived")
        break
    if number < 193:
        print ("Insuficient")
        break

Why it's not looping? I'm missing something pretty basic

CodePudding user response:

It's not continuing to loop because you have added a break statement inside both if statements, whereas only the first one should contain one.

Also, in order to loop a maximum of 5 times, use for _ in range(5), not while True (otherwise, it will loop forever until you enter a number greater than 193).

Here is the code:

for _ in range(5):
    number = float(input())
    if number > 193:
        print ("Goal Achived")
        break
    else:
        print ("Insuficient")

CodePudding user response:

You are breaking if number < 193. This will exit the loop.

Use this. It declares a variable i so it can only iterate 5 times

i = 0
while i < 5:
    number = int(input()) # or float(input()) if you want
    if number > 193:
        print("Goal Achived")
        break
    else:
        print("Insufficient")
        i  = 1

CodePudding user response:

replace the break with continue


    while True:
        number = int(input())  #this sould be in float but doesnt make any difference in the exercise itself
        if number > 193:
            print ("Goal Achived")
            break
        if number < 193:
            print ("Insuficient")
            continue

CodePudding user response:

Remove the last break. It will exit the loop, unintended i presume.

In addition,

1 - I suggest adding a <= test, so it won't ignore a 193 input.

2 - The last if statement is unnecessary. insert an else statement instead.

while True:
number = int(input())  #this sould be in float but doesnt make any difference in the exercise itself
if number > 193:
    print ("Goal Achived")
    break
else:
    print ("Insuficient")

CodePudding user response:

for i in range(5):
    num = int(input("Enter number "   str(i 1)  " "))
    if(num <= 193):
        print("Insufficient")
    else:
        print("Goal Achived")
  • Related