Home > Mobile >  How to while loop stop
How to while loop stop

Time:01-10

I input some thing from the list and when it done i stop the loop but it cannot stop. it is python

Here is my code

while True :
name= input ()
d = int(input())
for i in range(0, len(list), 2):
if list[i] != name:
print("Wrong")
else:
q = list[i 1]-d
print(q)
break

CodePudding user response:

It looks like you want to exit the loop if the input name is in the list. However, the break statement is indented within the for loop, so it only breaks out of the for loop and not the while loop.

To fix this, you can add a flag variable and use that to control the while loop.

Here is an example of how you can do this:

flag = False
while not flag:
    name = input()
    d = int(input())
    for i in range(0, len(list), 2):
        if list[i] != name:
            print("Wrong")
        else:
            q = list[i 1] - d
            print(q)
            flag = True
            break

This way, the while loop will be exited when the flag is set to True.

I hope it clarifies your confusion.

CodePudding user response:

This way you can check if the input name is in a list and exit loop if there is found...

list = ["Pepe", "Luis"]

while True:
   name = input ("Name? ")
   if name in list:
      break
  • Related