如何阻止if和elif部分的无限循环? [英] How do i stop the infinite loop for the if and elif part?

查看:362
本文介绍了如何阻止if和elif部分的无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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  


推荐答案

您可以在循环中的多个位置使用 break 。它不必在 else 块中或特别是在任何地方。这仍然有效:

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

这个代码没有多大意义,因为循环永远不会再次运行。您可能希望每次循环运行时都要求输入。所以你应该将 input()调用也移动到循环中。看起来你正在寻找:

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

这篇关于如何阻止if和elif部分的无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆