替代Goto,用Python标记?

2024-03-28 10:40:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我不能用Goto,我知道Goto不是答案。我读过类似的问题,但我就是想不出解决问题的办法。

所以,我在写一个程序,你必须猜一个数字。这是我有问题的部分的摘录:

x = random.randint(0,100)    

#I want to put a label here

y = int(raw_input("Guess the number between 1 and 100: "))

if isinstance( y, int ):
    while y != x:
        if y > x:
            y = int(raw_input("Wrong! Try a LOWER number: "))
        else:
            y = int(raw_input("Wrong! Try a HIGHER number "))
else:
    print "Try using a integer number"
    #And Here I want to put a kind of "goto label"`

你会怎么做?


Tags: to答案numberinputrawifputelse
3条回答

Python不支持goto或任何等价的东西

您应该考虑如何使用python提供的工具构造程序。似乎需要使用循环来完成所需的逻辑。您应该查看control flow page了解更多信息。

x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "

while not correct:

  y = int(raw_input(prompt))
  if isinstance(y, int):
    if y == x:
      correct = True
    elif y > x:
      prompt = "Wrong! Try a LOWER number: "
    elif y < x:
      prompt = "Wrong! Try a HIGHER number "
  else:
    print "Try using a integer number"

在许多其他情况下,您将希望使用function来处理要使用goto语句的逻辑。

有很多方法可以做到这一点,但通常您需要使用循环,您可能需要探索breakcontinue。以下是一个可能的解决方案:

import random

x = random.randint(1, 100)

prompt = "Guess the number between 1 and 100: "

while True:
    try:
        y = int(raw_input(prompt))
    except ValueError:
        print "Please enter an integer."
        continue

    if y > x:
        prompt = "Wrong! Try a LOWER number: "
    elif y < x:
        prompt = "Wrong! Try a HIGHER number: "
    else:
        print "Correct!"
        break

continue跳到循环的下一个迭代,并且break完全终止循环。

(还要注意,我在try/except中包装了int(raw_input(...)),以处理用户未输入整数的情况。在代码中,不输入整数只会导致异常。我也在randint调用中将0改为1,因为根据您正在打印的文本,您打算选择1到100,而不是0到100。)

可以使用无限循环,必要时还可以使用显式中断。

x = random.randint(0,100)

#I want to put a label here
while(True):
    y = int(raw_input("Guess the number between 1 and 100: "))

    if isinstance( y, int ):

    while y != x:
    if y > x:
        y = int(raw_input("Wrong! Try a LOWER number: "))
    else:
        y = int(raw_input("Wrong! Try a HIGHER number "))
    else:
      print "Try using a integer number"

     # can put a max_try limit and break

相关问题 更多 >