【发布时间】:2016-07-22 14:38:17
【问题描述】:
我正在学习 Python,我目前有一个冗长且有些重复的函数。请参见下文:目标:将功能分解为多个部分,以便我了解此过程如何更好地工作。
def play_game(questions,answers):
'''Begins checking user input to answers /
fills in the blanks with correct answer /
prompts user with same question if answer is Wrong
:param questions: feeds .split() list to find __1__
:param answers: searches for answer and replaces blank __1__
:return: replaces correct answer in questions param.
'''
print questions
user_input = raw_input("Fill in the blank: ")
if user_input == answers[0]:
questions = questions.replace('__1__', answers[0])
if user_input != answers[0]:
user_input = raw_input("Wrong answer, you have 4 guesses left. ")
print questions
user_input = raw_input("\n Please answer second question: ")
if user_input == answers[1]:
questions += questions.replace('__2__', answers[1])
if user_input != answers[1]:
user_input = raw_input("\n Incorrect, you have 3 guesses left. ")
print questions
此过程将继续进行 5 次猜测。我想强调的是,如果用户猜错了,同样的问题会再次被问到,他们的猜测也会从 5 减少到 4,等等。我应该在这里使用循环来自动化吗?
print questions
#for answer in answers:
# process answer
user_input = raw_input("Fill in the blank: ")
if user_input == answers[0]:
【问题讨论】:
-
是的,使用循环。这与嵌套函数有什么关系?
-
另外,您应该使用
else。而不是if a==b: do_this()if a!=b:do_that()你应该这样做if a==b: do_this()else: do_that() -
@PM 2Ring 那还会检查答案是否不在列表中吗?
-
也很抱歉重复,任何理解都非常感谢。
-
@SheperdsonBrown 如果你想让它执行检查你可以做
if a==b: do_this()然后elif a!=b:do_that()但是a!=b & a==b在很多情况下不应该是True
标签: python python-2.7 data-analysis