##### Matching variable to a list index
 Matching variable to a list index Gilush Silly Frenchman Posts: 47 Threads: 16 Joined: Jun 2020 Reputation: Nov-28-2020, 01:28 AM (This post was last modified: Nov-28-2020, 03:12 AM by Gilush.) 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: 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: Thanks for your time. again, this is not homework or any must assignment, this is just for me to stay in shape. Reply bowlofred Da Bishop Posts: 1,523 Threads: 3 Joined: Mar 2020 Reputation: Nov-28-2020, 01:46 AM What is main()? Your code as posted can't be run. Reply Gilush Silly Frenchman Posts: 47 Threads: 16 Joined: Jun 2020 Reputation: Nov-28-2020, 01:51 AM 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: 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 Larz60+ aetate et sapientia Posts: 11,549 Threads: 445 Joined: Sep 2016 Reputation: Nov-28-2020, 02:04 AM 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 Gilush Silly Frenchman Posts: 47 Threads: 16 Joined: Jun 2020 Reputation: Nov-28-2020, 02:10 AM (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 bowlofred Da Bishop Posts: 1,523 Threads: 3 Joined: Mar 2020 Reputation: Nov-28-2020, 02:13 AM 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 Gilush Silly Frenchman Posts: 47 Threads: 16 Joined: Jun 2020 Reputation: Nov-28-2020, 02:29 AM (This post was last modified: Nov-28-2020, 02:29 AM by Gilush.) (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 bowlofred Da Bishop Posts: 1,523 Threads: 3 Joined: Mar 2020 Reputation: Nov-28-2020, 04:00 AM 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: 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 Gilush Silly Frenchman Posts: 47 Threads: 16 Joined: Jun 2020 Reputation: Nov-28-2020, 11:05 AM (This post was last modified: Nov-28-2020, 11:05 AM by Gilush.) (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: 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 even if the answer sits on index. 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 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 perfringo Posts: 1,898 Threads: 8 Joined: Jun 2018 Reputation: Nov-28-2020, 11:31 AM 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 IndexError: list index out of range dolac 4 651 Jul-25-2022, 03:42 PM Last Post: deanhystad IndexError: list index out of range Anldra12 2 817 May-03-2022, 01:39 PM Last Post: Anldra12 IndexError: list index out of range rf_kartal 6 1,609 Sep-07-2021, 02:36 PM Last Post: Larz60+ Python Error List Index Out of Range abhi1vaishnav 3 1,304 Sep-03-2021, 08:40 PM Last Post: abhi1vaishnav An IF statement with a List variable dedesssse 3 1,804 Jul-08-2021, 05:58 PM Last Post: perfringo IndexError: list index out of range Laplace12 1 1,640 Jun-22-2021, 10:47 AM Last Post: Yoriz IndexError: list index out of range brunolelli 11 4,018 Mar-25-2021, 11:36 PM Last Post: brunolelli Changing Index of 2 List in python giddyhead 0 1,222 Mar-05-2021, 05:45 PM Last Post: giddyhead Create variable and list dynamically quest_ 12 2,778 Jan-26-2021, 07:14 PM Last Post: quest_ IndexError: list index out of range ramu4651 2 2,588 Jan-24-2021, 01:45 PM Last Post: buran

Forum Jump:

### User Panel Messages ##### Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020