Zacharea Islam
Zacharea Islam

Reputation: 9

How do you validate user input against 2D array

Need help validating the user input. Making a quiz where the questions and answers are stored in a 2D array

Array3x2 = [['Question 1 what is 100*10/2: ','Question 2 what is 20*10*5: 
','Question 3 what is 300*20: '],
[500,1000,6000]]

question_1 = input(Array3x2[0][0])
if question_1 == Array3x2[0][1]:
    print('correct')

It runs but doesn't validate the input it just loops over again. Part of a larger program that's what I mean by loops over again

Upvotes: 1

Views: 600

Answers (2)

Lateralus
Lateralus

Reputation: 802

In python 3 the input command returns the user input value as a string.
I cleaned up the code a bit and this seems to work well.

quiz = [["Question 1 what is 100*10/2: ", 500], ["Question 2 what is 20*10*5: ", 1000],
    ["Question 3 what is 300*20: ", 6000]]

for question, answer in quiz:
    user_input = int(input(question))
    if user_input == answer:
        print("Correct!")
    else:
        print("Incorrect")

Upvotes: 0

sameera sy
sameera sy

Reputation: 1718

You are making a mistake while comparing them. Your code should be the below.

Array3x2 = [['Question 1 what is 100*10/2: ','Question 2 what is 20*10*5:','Question 3 what is 300*20: '],
[500,1000,6000]]

question_1 = int(input(Array3x2[0][0])) # Type cast
if question_1 == Array3x2[1][0]: # Answers are in the 1st array and not in the 0th array
    print('correct')

You are comparing the wrong index. You should compare it with the 0th element in the 1st array. You are comparing the 0th answer with the 1st question. Also, you need to typecast the input you receive from the console. Always input is read as string and you are comparing it with a integer.

          0                               1                              2
 Array 0 ['Question 1 what is 100*10/2: ','Question 2 what is 20*10*5: ','Question 3 what is 300*20: ']

           0    1   2
 Array 1 [500,1000,6000]

Check the above code and it should work fine.

Upvotes: 1

Related Questions