如何使程序回到代码的顶部而不是关闭

mon*_*334 9 python python-3.3

我试图弄清楚如何让Python回到代码的顶部.在SmallBasic中,你做到了

start:
    textwindow.writeline("Poo")
    goto start
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚你是如何用Python做到的:/任何人的想法?

我试图循环的代码就是这个

#Alan's Toolkit for conversions

def start() :
    print ("Welcome to the converter toolkit made by Alan.")
    op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

if op == "1":
    f1 = input ("Please enter your fahrenheit temperature: ")
    f1 = int(f1)

    a1 = (f1 - 32) / 1.8
    a1 = str(a1)

    print (a1+" celsius") 

elif op == "2":
    m1 = input ("Please input your the amount of meters you wish to convert: ")
    m1 = int(m1)
    m2 = (m1 * 100)

    m2 = str(m2)
    print (m2+" m")


if op == "3":
    mb1 = input ("Please input the amount of megabytes you want to convert")
    mb1 = int(mb1)
    mb2 = (mb1 / 1024)
    mb3 = (mb2 / 1024)

    mb3 = str(mb3)

    print (mb3+" GB")

else:
    print ("Sorry, that was an invalid command!")

start()
Run Code Online (Sandbox Code Playgroud)

所以基本上,当用户完成转换时,我希望它循环回到顶部.我仍然无法将循环示例付诸实践,因为每次我使用def函数循环时,它都表示"op"未定义.

Mar*_*ers 16

使用无限循环:

while True:
    print('Hello world!')
Run Code Online (Sandbox Code Playgroud)

这当然也适用于你的start()功能; 您可以使用其中一个退出循环break,或者使用return完全退出该函数,这也会终止循环:

def start():
    print ("Welcome to the converter toolkit made by Alan.")

    while True:
        op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

        if op == "1":
            f1 = input ("Please enter your fahrenheit temperature: ")
            f1 = int(f1)

            a1 = (f1 - 32) / 1.8
            a1 = str(a1)

            print (a1+" celsius") 

        elif op == "2":
            m1 = input ("Please input your the amount of meters you wish to convert: ")
            m1 = int(m1)
            m2 = (m1 * 100)

            m2 = str(m2)
            print (m2+" m")

        if op == "3":
            mb1 = input ("Please input the amount of megabytes you want to convert")
            mb1 = int(mb1)
            mb2 = (mb1 / 1024)
            mb3 = (mb2 / 1024)

            mb3 = str(mb3)

            print (mb3+" GB")

        else:
            print ("Sorry, that was an invalid command!")
Run Code Online (Sandbox Code Playgroud)

如果你要添加一个退出选项,那可能是:

if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return
Run Code Online (Sandbox Code Playgroud)

例如.

  • @ user2756717:我没有指责任何人.:-)我只是很感激反馈,有人认为它值得一个downvote,如果他们分享*为什么*那​​么我可以解决他们看到的问题.更好的答案帮助大家! (2认同)

Riv*_*Tam 5

与大多数现代编程语言一样,Python不支持"goto".相反,您必须使用控制功能.基本上有两种方法可以做到这一点.

1.循环

您可以如何完成SmallBasic示例的操作示例如下:

while True :
    print "Poo"
Run Code Online (Sandbox Code Playgroud)

就这么简单.

2.递归

def the_func() :
   print "Poo"
   the_func()

the_func()
Run Code Online (Sandbox Code Playgroud)

关于递归的注意事项:只有在您想要返回到开头的特定次数时才执行此操作(在这种情况下,在递归应该停止时添加一个案例).像我上面定义的那样进行无限递归是一个坏主意,因为你最终会耗尽内存!

编辑更具体地回答问题

#Alan's Toolkit for conversions

invalid_input = True
def start() :
    print ("Welcome to the converter toolkit made by Alan.")
    op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
    if op == "1":
        #stuff
        invalid_input = False # Set to False because input was valid


    elif op == "2":
        #stuff
        invalid_input = False # Set to False because input was valid
    elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
        #stuff
        invalid_input = False # Set to False because input was valid
    else:
        print ("Sorry, that was an invalid command!")

while invalid_input : # this will loop until invalid_input is set to be True
    start()
Run Code Online (Sandbox Code Playgroud)

  • 递归有达到递归限制的风险。所以这将是错误的方法。在 Python 中,递归最适合用于分治式算法,而不是作为通用循环构造。 (3认同)