Getting 'truth value is ambiguous' error when defining a function

Viewed 30

Can anyone explain to me why the below code block doesn't work? I get a ValueError returned: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What's strange (to me at least, as a Pandas newb) is that if I simply print response == correct_answer it works just fine.

import numpy as np 

def this_is_jeopardy(Category, Value):
    df = jeopardy_data[(jeopardy_data['Category'] == Category) & (jeopardy_data['Value'] == Value)]
    question = np.random.choice(df.Question)
    print(question)
    response = input('Enter your answer here:')
    correct_answer = df[df['Question'] == question].Answer

    if response == correct_answer:
        print('Correct! That\'s worth ' + Value + 'ponts. Select another category to continue.')
    else:
        print('Not quite. The correct answer is ' + correct_answer + ' Select another category to continue.')
    
this_is_jeopardy('HISTORIC NAMES', '$1000')
1 Answers

response is a string, whereas correct_answer is likely a single value series.

Try changing correct_answer = df[df['Question'] == question].Answer

to correct_answer = df[df['Question'] == question].Answer.values[0]

Related