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

时间:2013-09-13 17:20:37

标签: python python-3.3

我正在试图弄清楚如何让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”没有定义。

7 个答案:

答案 0 :(得分:16)

使用无限循环:

while True:
    print('Hello world!')

这当然也适用于您的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!")

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

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

例如。

答案 1 :(得分:5)

与大多数现代编程语言一样,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()

答案 2 :(得分:2)

Python具有控制流语句而不是goto语句。控制流的一个实现是Python的while循环。您可以给它一个布尔条件(在Python中布尔值为True或False),并且循环将重复执行,直到该条件变为false。如果你想永远循环,你所要做的就是开始一个无限循环。

如果您决定运行以下示例代码,请务必小心。如果您想杀死进程,请在shell运行时按下Control + C.请注意,该过程必须位于前台才能使其正常工作。

while True:
    # do stuff here
    pass

# do stuff here只是一个评论。它不会执行任何操作。 pass只是python中的占位符,基本上说“嗨,我是一行代码,但跳过我因为我什么也没做。”

现在让我们假设您要反复询问用户输入永远,并且只有在用户输入字符'q'退出时才退出程序。

你可以这样做:

while True:
    cmd = raw_input('Do you want to quit? Enter \'q\'!')
    if cmd == 'q':
        break

cmd将存储用户输入的任何内容(系统会提示用户键入内容并按Enter键)。如果cmd只存储字母'q',则代码将强制break退出其封闭循环。 break语句允许您转义任何类型的循环。即使是无限的!如果您想要编写通常在无限循环上运行的用户应用程序,那么了解它非常有用。如果用户没有完全输入字母'q',则会反复无限地提示用户,直到该过程被强制终止,或者用户认为他已经有足够的烦人程序并且只想退出。

答案 3 :(得分:2)

您可以使用循环轻松完成,有两种类型的循环

对于循环:

for i in range(0,5):
    print 'Hello World'

虽然循环:

count = 1
while count <= 5:
    print 'Hello World'
    count += 1

这些循环中的每一个都打印“Hello World”五次

答案 4 :(得分:0)

编写for或while循环并将所有代码放入其中?转到类型编程已成为过去。

https://wiki.python.org/moin/ForLoop

答案 5 :(得分:0)

您需要使用while循环。如果你做了一个while循环,并且在循环之后没有指令,它将变成一个无限循环,并且在你手动停止它之前不会停止。

答案 6 :(得分:0)

def start():

Offset = 5

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Please be sensible try just the lower case')

def getMessage():
    print('Enter your message wanted to :')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (Offset))
        key = int(input())
        if (key >= 1 and key <= Offset):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return