0

I am making a Dichotomous Key program where it asks questions to determine the name of the creature that is in question. Here is how it looks like right now:

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?")

How would I put the if and else statement into a function so that I can reuse it for every question asked and change the step variable?

-Thanks

Green Man
  • 3
  • 1
  • You are probably looking for [Basic explanation of python functions](https://stackoverflow.com/questions/32409802/basic-explanation-of-python-functions) – Kay Jul 26 '18 at 18:08
  • But how would I change a non-local variable from within a function? – Green Man Jul 26 '18 at 18:09

1 Answers1

0

This is a working example:

    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)

But i don't think it's a good way to solve the problem

UPDATE: I like simplicity, that's why I try to get rid of state whenever I can. For example, I would write it this way:

    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)

you can make it better using more advanced techniques, but let's keep it simple :)