如何停止本程序Python

问题描述 投票:1回答:1

当我在IDLE中运行它并且我为响应键入0时,它会打印消息,但它不会停止程序。我认为设置keepGoing to False会阻止它,但我不知道最近发生了什么。请帮忙

""" crypto.py
Implements a simple substitution cypher
"""

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def main():
  keepGoing = True
  while keepGoing:
    response = menu()
    if response == "1":
      plain = input("text to be encoded: ")
      print(encode(plain))
    elif response == "2":
      coded = input("code to be decyphered: ")
      print (decode(coded))
    elif response == "0":
      print ("Thanks for doing secret spy stuff with me.")
      keepGoing = False
    else:
      print ("I don't know what you want to do...")
    return main()

def menu():
    print("Secret decoder menu")
    print("0) Quit")
    print("1) Encode")
    print("2) Decode")
    print("What do you want to do?")
    response = input()
    return response

def encode(plain):
    plain = plain.upper()
    new = ""
    for i in range(len(plain)):
        y = alpha.index(plain[i])
        new += key[y]
    return new

def decode(coded):
    coded = coded.upper()
    x = ""
    for i in range(len(coded)):
        z = key.index(coded[i])
        x += alpha[z]
    return x

main()
python while-loop exit
1个回答
-1
投票

在退出while循环之前,再次调用main(),然后重新启动程序:

def main():
    keepGoing = True
    while keepGoing:
        response = menu()
        if response == "1":
            plain = input("text to be encoded: ")
            print(encode(plain))
        elif response == "2":
            coded = input("code to be decyphered: ")
            print (decode(coded))
        elif response == "0":
            print ("Thanks for doing secret spy stuff with me.")
            keepGoing = False
        else:
            print ("I don't know what you want to do...")
#      return main()  # <-- delete this line

正如@Barmar所建议的那样,更好的设计是使用while True循环,并在达到某个条件时退出break语句:

def main():
    while True:
        response = menu()
        if response == "1":
            plain = input("text to be encoded: ")
            print(encode(plain))
        elif response == "2":
            coded = input("code to be decyphered: ")
            print (decode(coded))
        elif response == "0":
            print ("Thanks for doing secret spy stuff with me.")
            break
        else:
            print ("I don't know what you want to do...")
© www.soinside.com 2019 - 2024. All rights reserved.