How to compare the elements of one list with those of two others and generate an output for every element in python?

Question:

I tried to create a function with two "for loops" to compare the elements of two lists and generate an output for each comparison, but my output is always 0.

What is wrong with my code?

UserInput = ["A", "B", "A"]

CorrectAnswers = ["A", "B", "B"]
FalseAnswers = ["B", "A", "A"]

def run():
    score = 0
    for i in UserInput:
        for z in CorrectAnswers:
            if i is z:
                score = score + 1
            elif i is not z:
                for p in FalseAnswers:
                    if p is x:
                        score = score - 1
            else:
                raise ValueError("Invalid Input")
    print(score)

run()
        
    

Thanks a lot in advance…and please don’t decry me again.

Asked By: Julian

||

Answers:

I’m assuming you want to compare 2 arrays element wise.

Maybe you should try something like this:

for index, val in enumerate(UserInput): 
   if val == CorrectAnswers[index]:
      'do something'
   else:
      'do something else'

be aware that you might have a case where len(UserInput) > len(CorrectAnswers) you have to catch that case before you enter the for loop

Answered By: Der Esel

run function

def run(user_input, answers):
    score = 0

    for user_answer_index, user_answer in enumerate(user_input):  # looping over the value and the index (enumerate)
        try:  
            if user_answer == answers[user_answer_index]:  # if the answers are the same 
                score += 1
                
        except IndexError:  # index error 
            print("index error")

    print(score)

main function

def main():
    # data 
    user_input = ["A", "B", "A"]
    correct_answers = ["A", "B", "B"]
    
    run(user_input, correct_answers)

main()
Answered By: ironl1111

Part of the issue with your original code is that you reference "x" but it isn’t assigned.
I modified your code more than intended but you it looked like you wanted to use the enumerate() function where you can create an index based one one list and use it reference that same position in another list.

def run():
    score = 0
    for i, j in enumerate(UserInput):
            if j == CorrectAnswers[i]:
                score = score+1        
            elif j == FalseAnswers[i]:
                score = score-1
            else:
                raise ValueError("Invalid Input")
    return(score)   
print(run())
Answered By: Omnishroom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.