Youngn'
Youngn'

Reputation: 49

Ask user for index of list, Python

These dictionaries are killing me!

Here is my JSON(questions) containing a list of 2 dicts.

[
{
"wrong3": "Nope, also wrong",
"question": "Example Question 1",
"wrong1": "Incorrect answer",
"wrong2": "Another wrong one",
"answer": "Correct answer"
},
{
"wrong3": "0",
"question": "How many good Matrix movies are there?",
"wrong1": "2",
"wrong2": "3",
"answer": "1"
}
]

I am trying to allow the user to search for an index and then list the value of that index(if any). Currently I am prompting the user for input then finding the indexes of questions then checking if the input is equal to an index, right now it returns False, False even when the right index is inputted. Am I on the right track but semantically wrong? Or should I research another route?

import json


f = open('question.txt', 'r')
questions = json.load(f)
f.close()

value = inputSomething('Enter Index number: ')

for i in questions:
    if value == i:
        print("True")

    else:
        print("False")

Upvotes: 2

Views: 548

Answers (2)

m.wasowski
m.wasowski

Reputation: 6387

In Python it is best to not check beforehand, but try and deal with error if it occurs.

This is solution following this practice. Take your time to take a close look at logic here, it may help you in future:

import json
import sys

    # BTW: this is the 'pythonic' way of reading from file:
# with open('question.txt') as f:
#     questions = json.load(f)


questions = [
    {
        "question": "Example Question 1? ",
        "answer": "Correct answer",
    },
    {
        "question": "How many good Matrix movies are there? ",
        "answer": "1",
    }
]


try:
    value = int(input('Enter Index number: ')) # can raise ValueError
    question_item = questions[value] # can raise IndexError
except (ValueError, IndexError) as err:
    print('This question does not exist!')
    sys.exit(err)

# print(question_item)

answer = input(question_item['question'])

# let's strip whitespace from ends of string and change to lowercase:
answer = answer.strip().lower() 

if answer == question_item['answer'].strip().lower():
    print('Good job!')
else:
    print('Wrong answer. Better luck next time!')

Upvotes: 1

Zealous System
Zealous System

Reputation: 2324

You are iterating through list values. for i in questions will iterate through list values not list index,

you need to iterate through indexes of list. For that you can use enumerate. you should try this way..

for index, question_dict in enumerate(questions):
  if index == int(value):
        print("True")

    else:
        print("False")

Upvotes: 1

Related Questions