Skip to main content
 首页 » 编程设计

python之Goto 的替代品,Python 中的标签

2025年05月04日14fff_TT

我知道我不能使用 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 和 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 中以处理用户未输入整数的情况。在您的代码中,未输入一个整数只会导致异常。我也在 randint 调用中将 0 更改为 1,因为根据您正在打印的文本,您打算在 1 到 100 之间选择,而不是 0和 100。)