Python中的替代Goto Label的方法是什么?

4
我知道不能使用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"`

你会怎么做?

如果你使用的是Python 2.x,请将int(raw_input(改为input(。至于标签,你的代码剩下的部分是什么?你想调用一个函数吗? - cwahls
1
实际上,你可以在Python中使用goto123)。我也不明白为什么它从来都不是答案 - Anton Shepelev
3个回答

8

有很多方法可以做到这一点,但通常您需要使用循环,并且可能需要探索 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语句则终止整个循环。

(请注意,我在int(raw_input(...))内部添加了try/except语句来处理用户未输入整数的情况。如果没有这样的代码,输入非整数会导致异常。我还将randint方法中的0改为1,因为根据你打印的文本,你想要选择1到100之间的数字,而不是0到100之间的数字。)


1

Python不支持goto或任何等效物。

你应该考虑如何使用Python提供的工具来构建程序结构。似乎你需要使用循环来实现所需的逻辑。你可以查看控制流页面获取更多信息。

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语句的逻辑。

0
你可以使用无限循环,如果需要的话还可以使用显式的中断。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接