You need to enable JavaScript to run this app. Python中如何根据用户输入返回此前的规则打印代码段重新执行
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何根据用户输入返回此前的规则打印代码段重新执行

问题修正与实现方案

要实现“用户给出否定答复时,重新完整打印所有游戏规则”的效果,不需要依赖Python本身不支持的goto式代码跳转,用条件循环包裹规则展示段即可实现,逻辑清晰也容易维护。

原代码存在的两个核心问题

  • 没有提前定义Accept_ans变量,运行时会直接触发NameError报错
  • else分支只输出了提示文本,没有触发规则重打印的逻辑,用户看到提示后程序会直接终止,根本达不到回看规则的效果

完整可运行代码

# 提前定义所有判定为“已理解规则”的合法输入集合,内容全部为小写,和后续输入的大小写转换逻辑匹配
Accept_ans = {"yes", "y", "sure", "ok", "ready", "understood", "yeah"}

# 用无限循环包裹整套规则展示、询问、判断流程
while True:
    # 每次循环触发,都会从头完整执行以下所有规则打印语句
    print("Ok, the rules of this 'game' are very simple; You are kind of doing a virtual house tour.")
    print("You will be inspecting the house for its condition and to see if it is 'sellable'.")
    print("You will be going from room to room and checking it out based on the room description I give.")
    print("You will be giving each room a number value of 0,1,2, or 3.  A 0 takes away from the value of the house.")
    print("A 1 doesn't change the value of the house.  A 2 or a 3 increase the value of the house.")
    print("If at any point in the tour you think the house is not 'sellable', you just have to say so and the game ends.")
    print("Your progress in the house will be tracked at all times.")

    ans2 = input("Understand? Are you ready?")
    if ans2.lower() in Accept_ans:
        print ("Ok, great!  Lets begin the tour.")
        # 用户给出有效肯定答复,跳出循环正式进入游戏流程
        break
    else:
        print("ok, read the instructions again")
        # 无需额外跳转代码,循环会自动回到开头重新执行所有规则打印操作

运行逻辑说明

  • 当用户输入的内容转小写后不在合法答复集合中,程序会先输出“请重新阅读规则”的提示,随后自动回到循环起始位置,完整打印全部7条游戏规则,再重新向用户确认是否理解
  • 后续正式的房屋参观游戏逻辑,直接写在break语句的下方即可,不会干扰规则循环的流程
  • 可根据实际需求随时增减Accept_ans集合里的合法答复内容,灵活匹配用户的输入情况

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.11 14:45:07