【问题标题】:python - how would I put an if else statement in a function for abstraction?python - 我如何将 if else 语句放在抽象函数中?
【发布时间】:2018-07-27 04:31:13
【问题描述】:

我正在制作一个 Dichotomous Key 程序,它通过提问来确定所讨论的生物的名称。这是它现在的样子:

step = 0
yes = ["y", "yes"]
no = ["n", "no"]
while step == 0:
    q1 = input("Are the wings covered by an exoskeleton? (Y/N) ")
    q1 = q1.lower()
    if q1 in yes:
        step += 1
    elif q1 in no:
        step += 2
    else:
        print("Huh?")

我如何将 if 和 else 语句放入一个函数中,以便我可以在提出的每个问题中重复使用它并更改 step 变量?

-谢谢

【问题讨论】:

标签: python-3.x function global-variables


【解决方案1】:

这是一个工作示例:

    step = 0

    def update_step(q): 
        yes = ["y", "yes"]
        no = ["n", "no"]
        global step
        if q in yes:
            step += 1
        elif q in no:
            step += 2
        else:
            print("Huh?")


    while step == 0:
        q = input("Are the wings covered by an exoskeleton? (Y/N)")
        update_step(q.lower())

    print(step)

但我认为这不是解决问题的好方法

更新: 我喜欢简单,这就是为什么我尽可能地摆脱状态。例如,我会这样写:

    total_steps = 0

    def is_yes(answer):
        return answer in ["y", "yes"]

    def is_no(answer):
        return answer in ["n", "no"]

    def get_steps(answer):
        if is_yes(answer):
            return 1
        elif is_no(answer):
            return 2
        return 0

    while True:
        answer = input('question? ')
        steps = get_steps(answer.lower())
        if steps == 0:
            continue
        total_steps += steps
        break

    print(total_steps)

您可以使用更先进的技术使其变得更好,但让我们保持简单:)

【讨论】:

  • 感谢您的回答。但只是好奇,为什么你认为这不是解决问题的好方法?
猜你喜欢
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多