Python文本冒险游戏缩进错误求助:SyntaxError无效语法
解决Python文本冒险游戏的SyntaxError问题
错误原因分析
- 第50行的
input()语句未闭合引号和括号,直接导致语法中断 - 嵌套的
if answer == "a"缩进错误,且未正确闭合代码块 - 末尾存在多余的
else,没有对应的if语句匹配
修正后的完整代码
import random room = random.randrange(100,400) door = 0 closets = 0 inventorySlots = 0 # 修正拼写错误:invintory → inventory # Menu print(" --------DOORS--------") answer = input(" < Press enter to continue >") #intro print("You enter the hotel, it's storming outside") print("The receptionist, a girl with black hair and brown eyes says hi to you.") print("Her: Your reserved room is number", room) print(" ") answer = input("(A): Thanks! (B): You're cute (C): ...") if answer.lower() == "a": # 兼容大小写输入 print("You: Thanks!") print("Her: No problem!") elif answer.lower() == "b": print("You: You're cute.") print("Her: I'm not really into dating right now.. Thank you though!") elif answer.lower() == "c": print("Her: Not much of a talker eh?") print("You walk to your room") print("You enter but it's not your room. It's another room, with another door.") #main game door += 1 print("You enter door", door) if closets > 0: if random.randrange(1,3) == 2: # 原范围(1,2)只会生成1,调整后才能触发灯光闪烁 print("The lights flicker") answer = input("(A): Hide in the closet (B): go to the next door (C): look around") if answer.lower() == "a": print("You hide in a closet") elif answer.lower() == "b": door += 1 print("You enter door", door) elif answer.lower() == "c": print("You look around") if random.randrange(1,10) == 1: print("You found a lighter!") #Each item has a number ID if inventorySlots == 0: inventorySlots = 1 print("You got a lighter") else: print("Would you like to replace your current item with this one?") answer = input("(A): yes (B): no") # 补全闭合引号和括号 if answer.lower() == "a": print("You swapped your item for a lighter") else: print("You kept your original item") # 修正逻辑描述:不替换时保留原有物品 # 移除无匹配的多余else answer = input("(A): Go to the next door (B): say your name (C): ...")
关键修正点说明
- 引号闭合:修复了
input()语句缺失的闭合引号和括号,这是触发SyntaxError的直接原因 - 缩进与代码块:将嵌套的
if语句调整到正确缩进级别,确保代码块结构完整 - 移除多余分支:删除末尾无对应
if的else语句,解决语法不匹配问题 - 新手友好优化:
- 修正拼写错误,让变量名符合英文规范
- 使用
lower()处理输入,兼容大小写输入(比如"A"和"a"都能被识别) - 调整随机数范围,让灯光闪烁的逻辑能正常触发
- 修正物品替换的逻辑描述,避免语义矛盾
内容的提问来源于stack exchange,提问作者TurnipYossarian
相关产品推荐
相关产品推荐

