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

如何实现elif/else语句循环回到输入且重复输入时输出不同内容?

问题描述

我是脚本编程课的新手,这本来不是我的本职内容,但为了拿学位必须修这门课。期末作业是做一款游戏(目前只需要这部分的帮助,细节暂时不说)。我已经写完了初始代码,现在想实现:当用户输入investigate或者未定义的命令时,循环回到输入环节;如果再次输入相同内容,循环时要输出不同的提示信息。需要循环的是处理investigate的分支和无效命令的分支,以下是我目前的代码:

print("You awaken in a room in an unfamiliar cabin.  As you make your way to your feet you see outside the window is a mass of black tentacles \n and a voice echoes from below the house.  'Hah, mortal! Thou art no match for the powers of the abyss.  Thou shalt feel the depths of misery and despair' ")
print()
print("After this a soft whisper graces your ear and a different voice, one soft like a child's whispers 'Valiant hero, save us and we shall lend you \n  our power to vanquish the horror below' ")
print()
print("And so your journey begins.  Make haste and rescue the elements in order to save yourself.  Good luck!")
print()
print("You are currently on the main floor.  Please enter a direction you would like to go.  You can enter north, south, east, or west to go in the \n desired direction.  You may also investigate rooms with the investigate command")


user_input = input()

directions = ['north', 'east', 'south', 'west']
investigate = ['investigate']

if user_input == directions[0]:
    print("You have ascended the staircase to the second floor.  You stand in a bedroom with a door leading to the balcony to your side and the \n staircase behind you.  Beside the bed the lamp on the table seems dim... \n Please enter your direction or investigate.")
elif user_input == directions[3]:
    print("You have entered the bathroom.  The sound of water dripping seems to echo throughout the room as if it were the only sound being made. \n Please enter a direction or investigate")
elif user_input == directions[2]:
    print("You Find your way down the stairs leading you to the cellar below.  The scent of earth all around you.  To the East you can hear chanting in an inhumane \n voice that sends a shiver up your spine.  \n Please chose a direction or investigate.")
elif user_input == directions[1]:
    print("You find yourself in the kitchen.  The room seems much warmer than the others and the stove appears to be on.  To the north is a door leading \n to the pantry.  \n Please enter a direction or investigate")
elif user_input == investigate[0]:
    print("You look around the room and hear the withering of the tendrils sliding closer to the cabin... \n Please input a direction or investigate before it's too late!")
else:
    print("You look around in confusion at an unrecognized command.  Please enter a direction or investigate.")
解决方案

要实现你需要的功能,我们可以通过while循环持续接收用户输入,同时记录输入的类型和重复次数,根据次数切换提示文本。以下是修改后的中文版本代码:

print("你在一间陌生小屋的房间里醒来。当你站起身时,透过窗户看到外面布满黑色触手,一个声音从屋子下方传来:“哈哈,凡人!你根本不是深渊力量的对手。你将体会到痛苦与绝望的深渊!”")
print()
print("紧接着,一个轻柔如孩童低语的声音在你耳边响起:“英勇的英雄,请拯救我们,我们会借给你力量来消灭下方的恐怖!”")
print()
print("你的旅程就此开始。赶快去拯救元素之力,拯救自己吧。祝你好运!")
print()
print("你现在在一楼。请输入你想去的方向,你可以输入north(北)、south(南)、east(东)、west(西)前往对应方向,也可以输入investigate调查房间。")

# 记录上次输入的类型:'investigate'、'invalid' 或 None
last_input_type = None
# 记录同一类型输入的重复次数
repeat_count = 0

directions = ['north', 'east', 'south', 'west']
investigate_cmd = 'investigate'

while True:
    user_input = input().strip().lower()
    
    if user_input in directions:
        # 处理有效方向输入,根据方向输出对应场景
        if user_input == directions[0]:
            print("你走上楼梯来到二楼,站在一间卧室里。身旁有一扇通往阳台的门,身后是楼梯。床边桌上的台灯看起来很暗……\n请输入方向或进行调查。")
        elif user_input == directions[3]:
            print("你走进了浴室。滴水声在房间里回荡,仿佛是唯一的声响。\n请输入方向或进行调查。")
        elif user_input == directions[2]:
            print("你走下楼梯来到地窖。周围弥漫着泥土的气息。东边传来非人的吟唱声,让你脊背发凉。\n请选择方向或进行调查。")
        elif user_input == directions[1]:
            print("你来到厨房。这个房间比其他房间暖和得多,炉子似乎还开着。北边有一扇通往储藏室的门。\n请输入方向或进行调查。")
        
        # 输入有效方向后,重置输入状态,避免影响后续场景
        last_input_type = None
        repeat_count = 0
        # 如果需要在新场景继续循环,可移除break,这里暂时用break结束示例循环
        break
    
    elif user_input == investigate_cmd:
        # 更新重复次数和输入类型
        if last_input_type == 'investigate':
            repeat_count += 1
        else:
            repeat_count = 1
            last_input_type = 'investigate'
        
        # 根据重复次数输出不同提示
        if repeat_count == 1:
            print("你环顾房间,听到触手正在向小屋蠕动的窸窣声……\n趁还来得及,输入方向或调查!")
        elif repeat_count == 2:
            print("你再次仔细查看房间,触手的声音越来越近,地板都在微微震动……\n别再磨蹭了,选个方向或者继续调查!")
        else:
            print("触手已经快碰到窗户了!你必须立刻做出选择——要么移动,要么再最后调查一次!")
    
    else:
        # 更新无效命令的重复次数和输入类型
        if last_input_type == 'invalid':
            repeat_count += 1
        else:
            repeat_count = 1
            last_input_type = 'invalid'
        
        # 根据重复次数输出不同提示
        if repeat_count == 1:
            print("你一脸困惑,不知道这个命令是什么意思。请输入方向或进行调查。")
        elif repeat_count == 2:
            print("这个命令不对哦!再试一次,输入north、south、east、west或者investigate。")
        else:
            print("别乱输入了!有效的命令是方向(north/south/east/west)或者investigate!")

关键逻辑说明

  • 使用while True实现无限循环,直到用户输入有效方向(你可以根据游戏后续逻辑调整是否保留循环)
  • last_input_type和repeat_count用来跟踪用户输入的类型和重复次数,以此切换不同的提示文本
  • 输入有效方向后,重置状态变量,确保新场景的提示不受之前输入的影响
  • 对用户输入做了.strip().lower()处理,避免大小写和空格导致的识别错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:07:33