Python回到另一行代码

时间:2014-03-26 00:30:17

标签: python

是否有一种方法可以在不同路径上输入多个输入后,无论沿着什么路径,它都可以在另一行代码处继续? 例如:

    a = raw_input("1 or 2")
if a == "1" :
    a = raw_input("3 or 4")
    if a == "3" :
        *line of code that makes the script progress at line #14*
    if a == "4" :
        *line of code that makes the script progress at line #14*
if a = "2" :
    a = raw_input("5 or 6")
    if a == "5" :
        *line of code that makes the script progress at line #14*
    if a == "6" :
        *line of code that makes the script progress at line #14*
print ("chocolate")
(^line #14^)

2 个答案:

答案 0 :(得分:3)

您正在寻找的是 goto 声明。幸运的是*,Python 没有提供此功能。您可以尝试使用函数:

def print_chocolate():
    print("chocolate")

if a == "1" :
    a = raw_input("3 or 4")
    if a == "3" or a == "4" :
        print_chocolate()

if a == "2" :
    a = raw_input("5 or 6")
    if a == "5" or a == "6":
        print_chocolate()

注意:

您可以使用逻辑运算符(orand)保存一些代码行。

答案 1 :(得分:0)

想要使用goto通常表明您是否可以更好地构建代码:我同意具有良好控制结构的Joran Beasley's comment您不应该需要goto(关于此的许多讨论,请参阅{{ 3}})。

在我看来,您的计划应该反映您的意图并明确划分责任。我想这是一个玩具示例,但似乎还有两件事情:获取和解释用户输入和输出。我认为更清晰的程序,避免goto如下。

def UserInputDeservesChocolate():
    chocolate = False
    a = raw_input("1 or 2")
    if a == "1" :
        a = raw_input("3 or 4")
        chocolate = a == "3" or a == "4"
    if a == "2" :
        a = raw_input("5 or 6")
        chocolate = a == "5" or a == "6"
    return chocolate

if UserInputDeservesChocolate():
    print ("chocolate")