Python Forum
Matching variable to a list index - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Matching variable to a list index (/thread-31206.html)

Pages: 1 2


Matching variable to a list index - Gilush - Nov-28-2020

Hi! :)

I'm exercising with lists and dictionary by creating a test maker.
The point of the program is to be as dynamic as possible, meaning, the user can choose how many answers each question will have.
When I print the results I get the wrong answers near the question numbers.

What am I missing with the list/dictionary indexing? Is there more efficient way to get the right results?

code snippet:

def get_answers():

    global answer
    choice_number = 0

    try:
        choice_number = int(input("Number of answers? "))
        if choice_number > 4 or choice_number < 2:
            print("Please select [2-4]")
            choice_number = 0
            get_answers()

    except ValueError:
        print("Please select [2-4]")
        get_answers()

    for ans in range(choice_number):
        answer = input(f"Answer {ans + 1}: ")
        if len(answer) == 0:
            print("No empty answers.")
            get_answers()

        question_answers.append(answer)

    answers.append(choice_number)
    print(f"Number of answers: {answers}")
    print(question_answers)
    q_answers.append(answer)
    question_answers.clear()


def get_right_answer():

    right_answer = 0

    try:
        right_answer = int(input("Right Answer: "))

    except ValueError:
        print("Value Error!")
        get_right_answer()

        if 0 < right_answer <= answers[0]:
            sure = input("Are you sure? [Y/n]: ")
            if sure.lower() == "n":
                get_right_answer()

            elif sure.lower() == "y":
                question_right_answer[right_answer] = answer
                print(f"Questions: {question_list}")
                print(f"Right Answers: {question_right_answer}")
                print(f"Total Score: {sum(scores)}")

            else:
                print("Please Select [Y/n]")
                get_right_answer()

        else:
            print(f"Please select 1-{answers}")
            get_right_answer()
def finish():

    question_num = len(question_list)
    ask_continue = input("Do you wish to continue? [Y/n]: ")
    if ask_continue.lower() == "y":
        answers.pop()
        main()
        finish()

    elif ask_continue.lower() == "n":
        print("\n\n==============RESULTS==============\n")
        print("#\t Question\t Answer\t Score")
        for i in range(question_num):
            print(f"{i+1}\t {question_list[i]}\t\t {answer}\t\t {scores[i]}")
            i += 1

    else:
        print("Please select [Y/n]")
        finish()


if __name__ == "__main__":

    global answer

    scores = []
    question_list = []
    q_answers = []
    answers = []
    question_answers = []
    question_right_answer = {}
    question = input("Enter your question: ")
    score = int(input("Enter question score: "))

    main()
    finish()
here's a screenshot of the entire output:
[Image: 5VCTs.png]

Thanks for your time.
again, this is not homework or any must assignment, this is just for me to stay in shape.


RE: Matching variable to a list index - bowlofred - Nov-28-2020

What is main()? Your code as posted can't be run.


RE: Matching variable to a list index - Gilush - Nov-28-2020

I was told it's better to just post the relevant code but here's the full code.
This one will run.

def get_questions():

    try:
        if sum(scores + [score]) > 100:
            print("Score average is higher than 100")
            if len(question_list) > 0:
                question_list.pop(-1)
            if len(scores) > 0:
                scores.pop()

            get_questions()

    except ValueError:
        print("Use Numbers.")
        get_questions()

    question_list.append(question)
    scores.append(score)


def get_answers():

    global answer
    choice_number = 0

    try:
        choice_number = int(input("Number of answers? "))
        if choice_number > 4 or choice_number < 2:
            print("Please select [2-4]")
            choice_number = 0
            get_answers()

    except ValueError:
        print("Please select [2-4]")
        get_answers()

    for ans in range(choice_number):
        answer = input(f"Answer {ans + 1}: ")
        if len(answer) == 0:
            print("No empty answers.")
            get_answers()

        question_answers.append(answer)

    answers.append(choice_number)
    print(f"Number of answers: {answers}")
    print(question_answers)
    q_answers.append(answer)
    question_answers.clear()


def get_right_answer():

    right_answer = 0

    try:
        right_answer = int(input("Right Answer: "))

    except ValueError:
        print("Value Error!")
        get_right_answer()

        if 0 < right_answer <= answers[0]:
            sure = input("Are you sure? [Y/n]: ")
            if sure.lower() == "n":
                get_right_answer()

            elif sure.lower() == "y":
                question_right_answer[right_answer] = answer
                print(f"Questions: {question_list}")
                print(f"Right Answers: {question_right_answer}")
                print(f"Total Score: {sum(scores)}")

            else:
                print("Please Select [Y/n]")
                get_right_answer()

        else:
            print(f"Please select 1-{answers}")
            get_right_answer()


def main():

    get_questions()
    get_answers()
    get_right_answer()


def finish():

    question_num = len(question_list)
    ask_continue = input("Do you wish to continue? [Y/n]: ")
    if ask_continue.lower() == "y":
        answers.pop()
        main()
        finish()

    elif ask_continue.lower() == "n":
        print("\n\n==============RESULTS==============\n")
        print("#\t Question\t Answer\t Score")
        for i in range(question_num):
            print(f"{i+1}\t {question_list[i]}\t\t {answer}\t\t {scores[i]}")
            i += 1

    else:
        print("Please select [Y/n]")
        finish()


if __name__ == "__main__":

    global answer

    scores = []
    question_list = []
    q_answers = []
    answers = []
    question_answers = []
    question_right_answer = {}
    question = input("Enter your question: ")
    score = int(input("Enter question score: "))

    main()
    finish()



RE: Matching variable to a list index - Larz60+ - Nov-28-2020

Quote:I was told it's better to just post the relevant code
This is only true if the relevant code is runnable by itself.
Otherwise the entire code is fine.
More important that we are able to run what you have.


RE: Matching variable to a list index - Gilush - Nov-28-2020

(Nov-28-2020, 01:46 AM)bowlofred Wrote: What is main()? Your code as posted can't be run.

(Nov-28-2020, 02:04 AM)Larz60+ Wrote:
Quote:I was told it's better to just post the relevant code
This is only true if the relevant code is runnable by itself.
Otherwise the entire code is fine.
More important that we are able to run what you have.

Ok thanks for the info.
Let me know if you have problems running the full one (I don't see why it shouldn't work)


RE: Matching variable to a list index - bowlofred - Nov-28-2020

Lots of globals make it hard to keep track of everything.

Is the output supposed to be the "right answer"? I don't see where you store that. You use a function to ask for the right answer, but that function doesn't seem to store it anywhere.

There is also a lot of stuff in that function that is only inside the exception block. That may be incorrect, but doesn't change that nothing is storing the data. Also, on error you are calling the same function, Recursion here is a poor idea. You should be looping instead of making another call.


RE: Matching variable to a list index - Gilush - Nov-28-2020

(Nov-28-2020, 02:13 AM)bowlofred Wrote: Lots of globals make it hard to keep track of everything.

Is the output supposed to be the "right answer"? I don't see where you store that. You use a function to ask for the right answer, but that function doesn't seem to store it anywhere.

There is also a lot of stuff in that function that is only inside the exception block. That may be incorrect, but doesn't change that nothing is storing the data. Also, on error you are calling the same function, Recursion here is a poor idea. You should be looping instead of making another call.

Thanks for your reply,
That's the technique my professor tought me.
I'm trying to make it as dynamic as possible by letting the user decide how many answer's a question will have.
the "right" answer can, in fact, be anything. for me it's the answer's number that count.
Could you show me an example of looping that? or maybe a more efficient way to do it?

Thanks again!


RE: Matching variable to a list index - bowlofred - Nov-28-2020

I see, you have at least two problems with the shown code.

1) your exception check in get_right_answer() should only be a couple lines long, but the rest of the function (lines 63-80) is in that block, so it can't get executed if the answer is input properly.
2) Once you fix that, line 69 is question_right_answer[right_answer] = answer. You're assigning "answer", not "right_answer". That seems wrong to me.
3) your printout from line 103 is print(f"{i+1}\t {question_list[i]}\t\t {answer}\t\t {scores[i]}"). Note all the columns depend on i except for the third. That one is just the bare answer, so it will be the same for every line.


An example of looping until you get a valid response:

valid = "no"
while not valid.startswith(("y", "Y")):
    right_answer = int(input("Right Answer: "))
    if 0 < right_answer <= answers[0]:
        valid = input("Are you sure? [Y/n]")
        valid = valid or "Y"
    else:
        print(f"Please select 1-{answers}")

# We don't pass this point until user affirms answer is okay.  This
# separates the input code from the other tasks.
#  print the right answer to the screen for the user to see
#  store the right answer for later use..



RE: Matching variable to a list index - Gilush - Nov-28-2020

(Nov-28-2020, 04:00 AM)bowlofred Wrote: I see, you have at least two problems with the shown code.

1) your exception check in get_right_answer() should only be a couple lines long, but the rest of the function (lines 63-80) is in that block, so it can't get executed if the answer is input properly.
2) Once you fix that, line 69 is question_right_answer[right_answer] = answer. You're assigning "answer", not "right_answer". That seems wrong to me.
3) your printout from line 103 is print(f"{i+1}\t {question_list[i]}\t\t {answer}\t\t {scores[i]}"). Note all the columns depend on i except for the third. That one is just the bare answer, so it will be the same for every line.


An example of looping until you get a valid response:

valid = "no"
while not valid.startswith(("y", "Y")):
    right_answer = int(input("Right Answer: "))
    if 0 < right_answer <= answers[0]:
        valid = input("Are you sure? [Y/n]")
        valid = valid or "Y"
    else:
        print(f"Please select 1-{answers}")

# We don't pass this point until user affirms answer is okay.  This
# separates the input code from the other tasks.
#  print the right answer to the screen for the user to see
#  store the right answer for later use..

Thank you for answering.
The thing is that the user knows the right answer but when he chooses answer #1 then the program goes for index[0] even if the answer sits on index[1].

I definetly have missed something in the middle but I break my head trying to figure it out.
I've manage to 'filter' the answer by using the index function

if answer in question_right_answer.index(answer):
and I got this error:
Quote:Traceback (most recent call last):
File "G:\School\Python - Homework\Projects\Test Maker\main2.0.py", line 124, in <module>
main()
File "G:\School\Python - Homework\Projects\Test Maker\main2.0.py", line 87, in main
get_right_answer()
File "G:\School\Python - Homework\Projects\Test Maker\main2.0.py", line 63, in get_right_answer
if answer in question_right_answer.index(answer):
ValueError: 'wrong' is not in list

so i'm now looing for a way to compare the string answer to the answer's number.


RE: Matching variable to a list index - perfringo - Nov-28-2020

Can you describe in spoken language what you are trying to do/achieve?

Without a plan it’s hard to judge have you reached your destination or not (or are you moving in right direction with optimal path).