Python 如何让程序回到代码顶部而不是关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18791882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:51:26  来源:igfitidea点击:

How to make program go back to the top of the code instead of closing

pythonpython-3.3

提问by monkey334

I'm trying to figure out how to make Python go back to the top of the code. In SmallBasic, you do

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

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

But I can't figure out how you do that in Python :/ Any ideas anyone?

但我不知道你是如何在 Python 中做到这一点的:/任何人有任何想法吗?

The code I'm trying to loop is this

我试图循环的代码是这样的

#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()

So basically, when the user finishes their conversion, I want it to loop back to the top. I still can't put your loop examples into practise with this, as each time I use the def function to loop, it says that "op" is not defined.

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

采纳答案by River Tam

Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.

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

1. Loops

1. 循环

An example of how you could do exactly what your SmallBasic example does is as follows:

您可以如何准确地执行 SmallBasic 示例的示例如下:

while True :
    print "Poo"

It's that simple.

就这么简单。

2. Recursion

2. 递归

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

the_func()

Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!

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

Edited to Answer Question More Specifically

编辑以更具体地回答问题

#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()

回答by Martijn Pieters

Use an infinite loop:

使用无限循环:

while True:
    print('Hello world!')

This certainly can apply to your start()function as well; you can exit the loop with either break, or use returnto exit the function altogether, which also terminates the loop:

这当然也适用于您的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 you were to add an option to quit as well, that could be:

如果您还要添加退出选项,则可能是:

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

for example.

例如。

回答by A.J.

write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.

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

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

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

回答by Shashank

Python has control flow statements instead of gotostatements. One implementation of control flow is Python's whileloop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.

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

Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the process must be in the foreground for this to work.

如果您决定运行以下示例代码,请务必小心。如果您想终止进程,请在 shell 运行时按 Control+C。请注意,该进程必须在前台才能工作。

while True:
    # do stuff here
    pass

The line # do stuff hereis just a comment. It doesn't execute anything. passis just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."

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

Now let's say you want to repeatedly ask the user for input forever and ever, and only exit the program if the user inputs the character 'q' for quit.

现在假设您想永远重复地要求用户输入,并且只有在用户输入字符“q”退出时才退出程序。

You could do something like this:

你可以这样做:

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

cmdwill just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmdstores just the letter 'q', the code will forcefully breakout of its enclosing loop. The breakstatement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.

cmd将只存储用户输入的任何内容(用户将被提示输入内容并按回车键)。如果cmd只存储字母“q”,则代码将强制break退出其封闭循环。该break语句可让您转义任何类型的循环。甚至无限!如果您想对经常在无限循环中运行的用户应用程序进行编程,了解它是非常有用的。如果用户没有准确输入字母“q”,则用户将被反复无限地提示,直到进程被强行终止或用户决定他已经受够了这个烦人的程序而只想退出。

回答by Infamouslyuseless

You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.

您需要使用 while 循环。如果你做了一个while循环,循环后没有指令,它就会变成一个无限循环,直到你手动停止它才会停止。

回答by K DawG

You can easily do it with loops, there are two types of loops

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

ForLoops:

For循环:

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

WhileLoops:

虽然循环:

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

Each of these loops print "Hello World"five times

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

回答by ChipperChimp968

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