Python游戏;为什么我不能重新调用我的输入和if/else函数?
问题描述:
我还在学习Python,但是我的朋友在Python中编程之前说过这应该可以正常工作,但它不会?Python游戏;为什么我不能重新调用我的输入和if/else函数?
在此之前的所有代码是这个基本的“逃出房间”的游戏我正在开始的故事。代码直到这里才起作用(描述游戏的基本打印功能)。
我给玩家,他们在一个房间里是该方案,他们可以做两件事情之一:
def intro_room_input():
intro_action = input("What would you like to do? (Please enter either: 1 or 2) ")
return intro_action;
这两个功能是当他们选择1或2,接下来,如果/ ELIF功能如果他们选择1运行这些功能 :
def intro_room_result1():
print(
"""
(Story stuff for the result of option 1. Not important to the code)
""")
return;
此功能将发挥出来,如果他们选择2
def intro_room_result2():
print(
"""
(Story stuff for the result of option 2. Not important to the code)
""")
return;
这将用于接收玩家的输入并从那里继续故事。
def intro_action_if(string):
if string == "1":
intro_room_result1()
elif string == "2":
intro_room_result2()
else:
print("I'm sorry, that wasn't one of the options that was available..."+'\n'+
"For this action, the options must be either '1' or '2'"+'\n'+
"Let me ask again...")
intro_room_input()
intro_action_if(string)
return;
去年intro_room_input运行正常
,它重新运行先前的输入,但是当你真正进入1或2,它并没有对他们什么。它不想重新运行if/elif/else函数来给出结果。
最后我有一个主运行一切:
def main():
string = intro_room_input()
intro_action_if(string)
return;
main()
请帮帮忙,我不知道什么是错,此代码!?
答
问题出在您的intro_action_if()
。当您调用函数以再次获取值时,您忘记更改string
值。
即
#intro_room_input() #wrong
string = intro_room_input() #right
intro_action_if(string)
正如你可以看到,即使在你的代码你问用户input
和returned
它,你忘了重新分配string
与返回的值。因此,它保持您之前给出的相同输入并将该旧值传递给intro_action_if()
。
+0
非常感谢! :)重新分配它在我的功能工作就像我想要的。 –
这是我所看到的:在else语句你是不是分配的'intro_action_if'到'string',因此呼叫将再次做同样的事情的结果。 –