How Do I Stop The Infinite Loop For The If And Elif Part?
c = random.randint(0,5) guess =int(input('=')) while True: if guess > c: print('you failed the test') elif guess
Solution 1:
You can use break in more than one place in the loop. It doesn't have to be in else block or anywhere in particular. This will still work:
c = random.randint(0,5)
guess =int(input("="))
whileTrue:
if guess > c:
print("you failed the test")
breakelif guess <c:
print("you messed up")
breakelse:
print("you are the one" + x)
breakThis code doesn't make much sense though as the loop will never run a second time. You probably want to ask for input every time the loop runs. So you should move the input() call into the loop as well. It seems like you're looking for:
c = random.randint(0,5)
whileTrue:
guess =int(input("="))
if guess > c:
print("you failed the test")
elif guess <c:
print("you messed up")
else:
print("you are the one" + x)
breakSolution 2:
What do you think will happen when while(true) is present?
- The condition is always true and so the loop will never stop running unless it encounters a
breakstatement. Theelsepart works fine since it has abreakstatement.
What should you do?
- Add break statement in
ifandeliftoo so that the control moves out when condition is met.
Post a Comment for "How Do I Stop The Infinite Loop For The If And Elif Part?"