Python多函数游戏中如何复用用户名,避免重复询问并修复变量错误
Python游戏跨函数传递用户名问题解决
错误原因
你在select_showroom()中写name = input,这是将内置函数input本身赋值给了name变量,而非用户在greet()中输入的用户名。所以f-string输出时会显示函数对象的默认描述<built_in_function_input>,这个问题和while循环无关。
解决方案:传递参数
核心思路是把greet()中获取的用户名作为参数,传递给后续需要使用该名称的函数,这样所有函数都能直接调用用户名,无需重复询问。
修改后的完整代码示例
def greet(): # 修正原代码拼写错误:you → your name = input("what is your name?") print(f"hi there {name}") answer = input("do you want to play a stupid game?") # 用lower()兼容大小写输入,elif让逻辑更严谨 if answer.lower() == "yes": print("ok, let's play!") # 调用select_showroom时传入name参数 select_showroom(name) elif answer.lower() == "no": print("well you're not missing anything!") exit() else: print("Please answer with 'yes' or 'no'.") # 错误输入后重新调用greet greet() def select_showroom(name): # 接收name参数,直接在f-string中使用 print(f"""{name}, you're in the lobby of the design building, three showrooms are open today. which one would you like to enter, 1, 2 or 3?""") choice = input("< ") if choice == "1": # 如果showroom1也需要用户名,同样传递参数 showroom1(name) elif choice == "2": showroom2(name) elif choice == "3": showroom3(name) else: print("Invalid choice, try again.") # 错误输入后重新调用,保持传递name select_showroom(name) # 示例后续函数,同样接收name参数 def showroom1(name): print(f"Welcome to Showroom 1, {name}!") def showroom2(name): print(f"Welcome to Showroom 2, {name}!") def showroom3(name): print(f"Welcome to Showroom 3, {name}!") # 启动游戏 greet()
补充说明
- 所有需要使用用户名的后续函数(如
showroom1、showroom2等),都需要在定义时添加name参数,并在调用时传入该参数。 - 原代码中的拼写错误(
you→your)、逻辑漏洞(未处理yes/no以外的输入)也一并修正,提升游戏的健壮性。
内容的提问来源于stack exchange,提问作者Susan Young
相关产品推荐
相关产品推荐

