如何让程序回到代码的顶部而不是关闭[重复]

问题描述 投票:0回答:7

我在想办法让 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”未定义。

python python-3.3
7个回答
19
投票

使用无限循环:

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

例如。


10
投票

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 False
    start()

3
投票

你可以很容易地用循环来做,有两种类型的循环

For循环:

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

While循环:

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

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


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
将只存储用户输入的任何内容(系统将提示用户输入内容并按回车键)。如果
cmd
只存储字母“q”,代码将强制
break
跳出它的封闭循环。
break
语句可以让你跳出任何类型的循环。甚至无限!如果您想编写经常在无限循环中运行的用户应用程序,那么了解它非常有用。如果用户没有准确键入字母“q”,系统将不断重复提示用户,直到进程被强行终止,或者用户决定他已经受够了这个烦人的程序,只想退出。


1
投票

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

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


1
投票

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


-1
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.