一尘不染

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

python

我试图弄清楚如何使Python返回代码的顶部。在SmallBasic中,您可以

start:
    textwindow.writeline("Poo")
    goto start

但是我不知道您如何在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()

因此,基本上,当用户完成转换时,我希望它循环回到顶部。我仍然不能以此来实践您的循环示例,因为每次我使用def函数进行循环时,都表示未定义“ op”。


阅读 279

收藏
2021-01-20

共1个答案

一尘不染

像大多数现代编程语言一样,Python不支持“ goto”。而是必须使用控制功能。基本上有两种方法可以做到这一点。

1.循环

您可以如何完全按照SmallBasic示例进行操作的示例如下:

while True :
    print "Poo"

就这么简单。

2.递归

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

the_func()

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

编辑以更具体地回答问题

#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()
2021-01-20