RobertJRodriguez
RobertJRodriguez

Reputation: 27

Python color exercise

I'm trying to display the secondary color of two mixed prime colors. I'm a little stuck on the code but it seems like it all checks to me yet when I run it, it always displays the else error message I put in. What do I do?!

print('Choose two primary colors to get their secondary color.')
print('Choose the number 1 for red, 2 for blue and 3 for yellow.')

red = 1
blue = 2
yellow = 3


def main():
    prime_1 = input('Enter your first primary color: ')
    prime_2 = input('Enter your second primary color: ')

    if prime_1 == red and prime_2 == blue:
        print('Your secondary color is purple!')

    elif prime_1 == yellow and prime_2 == red:
        print('Your secondary color is orange!')

    elif prime_1 == blue and prime_2 == yellow:
        print('Your secondary color is green!')

    else:
        print('That is not a primary color!')

main()

Upvotes: 0

Views: 2574

Answers (1)

icktoofay
icktoofay

Reputation: 129001

input returns a string, but the values in the variables red, blue, and yellow are integers. Integers and strings are not equal:

>>> '5' == 5
False

You can work around this by either making your red, blue, and yellow variables strings:

red = '1'
blue = '2'
yellow = '3'

Or converting the user's input to an integer before comparing:

prime_1 = int(input('Enter your first primary color: '))
prime_2 = int(input('Enter your second primary color: '))

If you decide to go with the approach of converting the user's input to an integer before comparing, note that this has another failure mode: if they enter a string that's a valid integer but an invalid color like 4, your error message will be output; but if they enter a string that's not a valid integer, like red, it will raise a ValueError exception and crash your program rather than triggering your error logic. You could catch that using a try block or two:

try:
    prime_1 = int(input('Enter your first primary color: '))
except ValueError:
    prime_1 = None
try:
    prime_2 = int(input('Enter your second primary color: '))
except ValueError:
    prime_2 = None

Upvotes: 3

Related Questions