-2
c = random.randint(0,5)
guess =int(input("="))
while True:
    if guess > c:
      print("you failed the test")
    elif guess <c: 
      print("you messed up")
    else:
      print("you are the one" + x)
      break  
kichik
  • 33,220
  • 7
  • 94
  • 114
jeff
  • 17
  • 1
  • 7

2 Answers2

2

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("="))
while True:
    if guess > c:
      print("you failed the test")
      break
    elif guess <c: 
      print("you messed up")
      break
    else:
      print("you are the one" + x)
      break

This 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)
while True:
    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)
      break
kichik
  • 33,220
  • 7
  • 94
  • 114
0

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 break statement. The else part works fine since it has a break statement.

What should you do?

  • Add break statement in if and elif too so that the control moves out when condition is met.
Mathews Mathai
  • 1,707
  • 13
  • 31