Python:根据使用函数

时间:2017-02-08 16:46:31

标签: python

我正在编写一段代码,询问用户几个是/否问题;根据答案,应遵循不同的路径,某些路径可能会导致另一个问题,而其他路径则会导致答案。

我用Python编写了许多嵌入式if,elif和else语句,但我正在寻找一种使用函数的更有效的方法。

有没有人对如何使用函数有任何想法:

  • 提出问题
  • 检查答案是否为是/否
  • 根据要求提出另一个问题或给出答案。

干杯

1 个答案:

答案 0 :(得分:3)

您可以尝试在类似图形的数据结构中对问题/答案路径进行编码。

以下是我的意思(qa.py)示例:

#!/usr/bin/env python3

from abc import ABCMeta, abstractmethod


# I've made them strings for now but they can be anything you want
# For e.g. Django question models
questions = [
    'Question 1',
    'Question 2',
    'Question 3',
    'Question 4',
    'Question 5',
]


# Similarly these can be anything you want
answers = [
    'Answer 1',
    'Answer 2',
    'Answer 3',
    'Answer 4',
]


# The idea is to have a collection of questions and a collection of answers
# Then, we wire them up in a graph-like structure


class Node(metaclass=ABCMeta):
    @abstractmethod
    def run(self):
        pass

class QuestionNode(Node):
    def __init__(self, question, yes_node, no_node):
        self.question = question
        self.yes_node = yes_node
        self.no_node = no_node

    def run(self):
        print(self.question)

        # Basic prompt for illustration purposes only
        answer = None
        while answer not in ['y', 'yes', 'n', 'no']:
            answer = input('(y/n) > ').lower()

        if answer[0] == 'y':
            self.yes_node.run()
        else:
            self.no_node.run()


class AnswerNode(Node):
    def __init__(self, answer):
        self.answer = answer

    def run(self):
        print('Answer: ' + self.answer)


if __name__ == '__main__':
    answer_nodes = [AnswerNode(answer) for answer in answers]

    q4 = QuestionNode(questions[4], answer_nodes[1], answer_nodes[2])
    q3 = QuestionNode(questions[3], answer_nodes[0], q4)
    q2 = QuestionNode(questions[2], answer_nodes[2], answer_nodes[3])
    q1 = QuestionNode(questions[1], answer_nodes[0], q3)
    q0 = QuestionNode(questions[0], q1, q2)

    q0.run()

并且,这是此配置的输出(我已经说明了所有可能的路径):

$ ./qa.py 
Question 1
(y/n) > y
Question 2
(y/n) > y
Answer: Answer 1

$ ./qa.py 
Question 1
(y/n) > y
Question 2
(y/n) > n
Question 4
(y/n) > y
Answer: Answer 1

$ ./qa.py 
Question 1
(y/n) > y
Question 2
(y/n) > n
Question 4
(y/n) > n
Question 5
(y/n) > y
Answer: Answer 2

$ ./qa.py 
Question 1
(y/n) > y
Question 2
(y/n) > n
Question 4
(y/n) > n
Question 5
(y/n) > n
Answer: Answer 3

$ ./qa.py 
Question 1
(y/n) > n
Question 3
(y/n) > y
Answer: Answer 3

$ ./qa.py 
Question 1
(y/n) > n
Question 3
(y/n) > n
Answer: Answer 4

请注意,我将问题和答案从图表结构中分离出来。这是故意的,以便获得最大的灵活性。这意味着相同的问题/答案更容易出现多次,但沿图中的不同路径出现。

P.S。: 这让我想起了很久以前遇到的Jellyvision产品。