如何阻止Python脚本运行后立即关闭?添加input仍失效
解决Python脚本运行后窗口自动关闭的问题
你的问题出在Replay函数里的exit()调用——当用户输入quit时,程序会直接终止,完全跳过了脚本末尾的input()语句,导致窗口立刻关闭。
修改方案
可以通过两种方式修复这个问题:
方案一:移除exit(),让程序自然执行到末尾的input()
修改Replay函数:
def Replay(): print ('Do you have another question? Type Y if yes, and quit if you want to quit ') reply = input() if reply == 'Y': Magic8Ball() elif reply == 'quit': print('Goodbye ' + name) # 去掉exit(),程序会回到主流程执行最后的input() return else: print('I apologies, I did not catch that. Please repeat.') Replay()
方案二:在退出前添加等待输入的语句
如果一定要保留exit(),可以在退出前让用户确认:
elif reply == 'quit': print('Goodbye ' + name) input("按回车键关闭窗口...") exit()
额外优化提示
你的代码使用递归调用Magic8Ball()和Replay(),如果用户反复提问多次,可能触发Python的递归深度限制。可以改用循环替代递归,更稳定:
import random answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes – definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook is good', 'yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Dont count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful'] print(''' __ __ _____ _____ _____ ___ ____ __ __ __ | \/ | /\ / ____|_ _/ ____| / _ \ | | /\ | | | | | | | \ / | / \ | | __ | || | | (_) | | || / / \ | | | | | | | |\/| | / /\ \| | |_ | | || | > _ < | \ / /\ \ | | | | |__| | | | |/ ____ \ |__| |_| || |____ | (_) | | || |/ ___ \ | |___ | |___ __ |_| |_/_/ \\_\_____|_____\_____| \___/ |____/_/ \\_|______||______| |__| ''') print('Hello World, I am the Magic 8 Ball an omnipotent being, What is your name?') name = input() print('hello ' + name) def Magic8Ball(): while True: print('Ask me a question.') input() print(answers[random.randint(0, len(answers)-1)]) print('I hope that helped!') print ('Do you have another question? Type Y if yes, and quit if you want to quit ') reply = input() if reply == 'quit': print('Goodbye ' + name) input("按回车键关闭窗口...") break elif reply != 'Y': print('I apologies, I did not catch that. Please repeat.') Magic8Ball()
内容的提问来源于stack exchange,提问作者Ethyn Berndt
相关产品推荐
相关产品推荐

