如何在Python分步检查清单代码中跳转到指定步骤执行
问题
我正在编写一个制作事项检查清单的Python代码,代码基本结构如下:
a0=int(input(f'do step one, then enter 1 to cont') a1=int(input(f'do step two, then enter 1 to cont')
请问如何跳转到a4(或任意a(n))步骤并从该步骤继续执行?
我的思路是定义每个步骤并将变量存入列表,再用while循环从指定位置开始执行,但具体实现遇到了困难。我尝试将字符串转换为变量名来实现,相关代码如下:
ail=len(ai) #where ai=[a0,a1,a2..] a=0 #i would input a as any val. while a in range (0,ail): b=(f'a{a}') #this line would determine the "instruction line" to start from. exec("%s = %d" % (b,b)) #this is the line that names a var from a string b0=int(input(f'{b}'))
解决方案
别用字符串生成变量名的写法,既不安全又难维护。直接把每个步骤的逻辑存入列表,通过索引就能轻松控制从任意步骤开始执行:
1. 基础版:用列表存步骤提示
如果只是需要提示用户完成步骤,把每个步骤的提示文本放进列表即可:
# 定义所有步骤的提示信息 steps = [ "完成步骤一,输入1继续", "完成步骤二,输入1继续", "完成步骤三,输入1继续", "完成步骤四,输入1继续", "完成步骤五,输入1继续" ] # 获取用户指定的起始步骤(注意:步骤四对应索引4) start_idx = int(input("请输入要开始的步骤索引(比如步骤四输入4):")) # 先校验索引合法性 if start_idx < 0 or start_idx >= len(steps): print("输入的步骤索引无效,请重新运行程序") else: # 从指定步骤开始循环执行 for idx in range(start_idx, len(steps)): # 循环等待用户正确输入确认 while True: try: confirm = int(input(f"{steps[idx]}:")) if confirm == 1: print(f"已完成步骤{idx+1}") break else: print("请输入1确认完成") except ValueError: print("输入无效,请输入数字1")
2. 进阶版:用列表存步骤函数
如果每个步骤有独立的操作逻辑(比如要执行特定代码),可以把步骤封装成函数存入列表:
# 定义每个步骤的具体逻辑 def step_one(): print("正在执行步骤一的操作...") return input("完成步骤一,输入1继续:") def step_two(): print("正在执行步骤二的操作...") return input("完成步骤二,输入1继续:") def step_three(): print("正在执行步骤三的操作...") return input("完成步骤三,输入1继续:") def step_four(): print("正在执行步骤四的操作...") return input("完成步骤四,输入1继续:") # 把步骤函数存入列表 step_funcs = [step_one, step_two, step_three, step_four] # 获取起始步骤索引(步骤四对应索引3) start_idx = int(input("请输入要开始的步骤索引(比如步骤四输入3):")) if 0 <= start_idx < len(step_funcs): # 从指定步骤开始执行 for func in step_funcs[start_idx:]: while True: res = func() if res == "1": break print("请输入1确认完成") else: print("步骤索引无效,请重新运行程序")
这种写法比用exec安全可靠,代码可读性和可维护性都高,完全能实现任意步骤跳转并继续执行的需求。
内容的提问来源于stack exchange,提问作者Marlon D. Alessandra
相关产品推荐
相关产品推荐

