Python Forum
Matching variable to a list index
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Matching variable to a list index
#1
Question 
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.
Reply
#2
What is main()? Your code as posted can't be run.
Reply
#3
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()
Reply
#4
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.
Reply
#5
(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)
Reply
#6
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.
Reply
#7
(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!
Reply
#8
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..
Reply
#9
(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.
Reply
#10
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).
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable for the value element in the index function?? Learner1 8 545 Jan-20-2024, 09:20 PM
Last Post: Learner1
Thumbs Down I hate "List index out of range" Melen 20 3,157 May-14-2023, 06:43 AM
Last Post: deanhystad
  IndexError: list index out of range dolac 4 1,843 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  Split string using variable found in a list japo85 2 1,236 Jul-11-2022, 08:52 AM
Last Post: japo85
  IndexError: list index out of range Anldra12 2 1,408 May-03-2022, 01:39 PM
Last Post: Anldra12
  IndexError: list index out of range rf_kartal 6 2,761 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,236 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  An IF statement with a List variable dedesssse 3 7,948 Jul-08-2021, 05:58 PM
Last Post: perfringo
  IndexError: list index out of range Laplace12 1 2,186 Jun-22-2021, 10:47 AM
Last Post: Yoriz
  IndexError: list index out of range brunolelli 11 6,346 Mar-25-2021, 11:36 PM
Last Post: brunolelli

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020