【问题标题】:Nested functions [duplicate]嵌套函数 [重复]
【发布时间】: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


【解决方案1】:

试试这样的:

for guess in range(4):
    print "Guess", guess + 1

# Put your game function here

    if guess == 3:
        print "Game Over!"

【讨论】:

  • 喜欢吗?对于范围内的猜测(4):打印“猜测”,猜测+ 1 def play_game(问题,答案):
  • @SheperdsonBrown - 是的,类似的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2023-04-03
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多