Python 中 Goto 标签的替代方案?

2024-05-03

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

你会怎么办?


有很多方法可以做到这一点,但通常您会想要使用循环,并且您可能想要探索break and 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 更改为 1randint也调用,因为根据您正在打印的文本,您打算在 1 到 100 之间选择,而不是 0 到 100。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中 Goto 标签的替代方案? 的相关文章