Python 中 Goto 标签的替代方案?

问题描述 投票:0回答:3

我知道我不能使用 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 goto
3个回答
8
投票

有很多方法可以做到这一点,但通常您会想要使用循环,并且您可能想要探索

break
continue
。这是一种可能的解决方案:

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 中以处理用户未输入整数的情况。在您的代码中,不输入整数只会导致异常。我将 0 更改为 a 1 在
randint
调用中,因为根据您正在打印的文本,您打算在 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
© www.soinside.com 2019 - 2024. All rights reserved.