如何修改Python代码实现用户输入y后脚本从开头重新执行
Python脚本循环重启逻辑修改方案
你当前的代码重复编写了3次相同的主业务逻辑,直接调整结构即可实现需求,改动如下:
调整逻辑
- 删除重复的2份功能代码,仅保留1份核心的系统启动、功能选择交互逻辑
- 在所有代码最外层套一层无限循环,包裹全部业务逻辑
- 修改末尾的交互判断:
- 当用户输入
y时执行continue,直接触发外层循环重新运行,即可从头执行整个脚本 - 当用户输入其他内容时执行
break,退出整个脚本
- 当用户输入
修改后完整代码
import time # 外层无限循环,控制脚本重启逻辑 while True: print("Booting System (Alfa V1.2, Bugs Fixed, Loop added)") time.sleep(1) print("Hello, and welcome to Training OS") time.sleep(2) print("What would you like to do ?") time.sleep(1) txt = raw_input("1.File Explorer 2.System Info. ( 1 or 2 )") if txt=="1": print("Loading File Explorer") time.sleep(1) print(" _____ _____ \n / | / | \n | | | | \n |_____| |_____| \n File1 File2 ") time.sleep(0.5) file = raw_input("1.File1 2.File2 ( 1 or 2 )") if file=="1": print("\n\nFile1:" "\n_______________________________________" "\nTOP SECRET UPDATE INFO:" "\n Update Name . . . . 1.2" "\nEstimated Release Date . . . . 25.09.21" "\n(Official release date:. . . . 24.09.21)" "\n New Features . . . . Loop" "\n_______________________________________") else: print("\n\nFile2:" "\n----------------------------------------" "\n " "\n Error 404. " "\n File Missing " "\n " "\n----------------------------------------") else: print("\n\nSystem Info:" "\n--------------------------------------------------------------------------------------" "\n\nOs version: . . . . . 1.1 (New features: File Explorer)" "\n Founded: . . . . . 22.09.2021, Baku, Azerbaijan" "\n Products: . . . . . TOS" "\n\n***This OS is still being developed so some features are currently unaviable :(***" "\n--------------------------------------------------------------------------------------") # 末尾交互判断 cmd = raw_input('\nAnything else? Enter \'y\' to continue, other keys to exit: ') if cmd != 'y': break
注:如果你使用的是Python3版本,只需把代码中所有的
raw_input替换为input即可正常运行。
内容的提问来源于stack exchange,提问作者Manuel Pozzoni
相关产品推荐
相关产品推荐

