You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码仅输出最后提问,其余内容未打印的问题求助

问题分析与代码修正

问题根源

你的代码只输出最后一行提问,核心错误如下:

  • 定义的displayIntro()、chooseCavern()函数从未被调用,函数内部的介绍文本、游戏提问自然不会执行
  • random.choice()参数格式错误,需要传入列表而非单独数值
  • 嵌套定义的exit()函数未实际调用,无法触发退出逻辑
  • while循环后逻辑混乱,checkCavern()函数既未调用也未关联用户选择

修正后的代码

import sys
import random 

# 显示游戏介绍
def displayIntro():
    intro = "You are a fierce mercenary traveling through a land full of Cockatrices, dragons with rooster heads, who can kill you just by looking, touching, or breathing on you. You’ve heard that the Cockatrices all live in caverns with their large piles of collected treasure. According to legend, some Cockatrices are friendly and share their treasure, while other Cockatrices are filled with hate for humans, and take out all who enter their cavern. While traveling, you approach two caverns, one with a friendly Cockatrice and the other with an angry Cockatrice, but don't know which Cockatrice is in which cavern. You must choose between the two. Good luck."
    print(intro)
    
# 处理游戏选择逻辑
def chooseCavern():
    # 询问是否开始游戏
    play = input("Would you like to play a game? Type yes or no:").lower()
    if play != "yes":
        sys.exit()
    
    while True: 
        cavern = int(input("Which cavern do you choose to enter, cavern 1 or cavern 2? Type 1 or 2: "))
        # 生成随机结果并判断
        computer_action = random.choice([1, 2])
        if computer_action == cavern: 
            print("The cavern you entered had an unfriendly cockatrice inside. Even with all your armor and fighting power, you never stood a chance. The cockatrice opens it’s eyes from its slumber and stares you down, instantly turning you into ash.")
        else:
            print("The cavern you entered was inhabited by a friendly cockatrice. The giant, scaled dragon awakened from its slumber to tell you to take anything you desire. All it asked for in return was for you to never disturb it again. You obliged, living in immense wealth for the rest of your life.")
        
        # 询问是否再玩一次
        play_again = input("Would you like to play again? Type yes or no:").lower()
        if play_again != "yes":
            sys.exit()

# 调用核心函数启动游戏
displayIntro()
chooseCavern()

关键修改说明

  • 新增displayIntro()和chooseCavern()函数调用,触发完整游戏流程
  • 修复random.choice()参数为[1,2]的正确格式
  • 移除冗余嵌套exit()函数,直接用sys.exit()处理退出逻辑
  • 整合游戏逻辑,将结果判断放入循环内,同时把“再玩一次”的提问移到单局游戏结束后,符合正常流程
  • 对输入做lower()处理,兼容大小写输入(比如用户输入"Yes"也能识别)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:30:58