python - Goto 的替代品,Python 中的标签?

标签 python goto

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

你会怎么做?

最佳答案

有很多方法可以做到这一点,但通常您会想要使用循环,并且您可能想要探索 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。)

关于python - Goto 的替代品,Python 中的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494761/

相关文章:

python - 通过 bash 激活现有的 virtualenv

python - django rest 单线程/阻塞 View

c++ - goto 和析构函数兼容吗?

c++ - 我应该避免在这里使用 goto 吗?如果是这样,怎么做?

javascript - 在 JavaScript 中使用相同的代码两次

Python 检查对象是 ListProxy 还是 DictProxy

python - 如何在不指定文件扩展名的情况下运行 python 脚本(跨平台解决方案)?

python - 索引错误: list index out of range CSV parser

php - PHP 中 goto 的有效用例是什么?

java - 重构 (C) 伪代码以删除 goto