0

我正在尝试显示两种混合原色的二次色。我有点卡在代码上,但似乎一切都对我进行了检查,但当我运行它时,它总是显示我输入的 else 错误消息。我该怎么办?!

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()
4

1 回答 1

3

input返回一个字符串,但变量redblue和中的值yellow是整数。整数和字符串不相等:

>>> '5' == 5
False

您可以通过制作 、 和 variables 字符串来解决redblue问题yellow

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

或者在比较之前将用户的输入转换为整数:

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

如果您决定在比较之前将用户的输入转换为整数,请注意这有另一种失败模式:如果他们输入的字符串是有效整数但颜色无效,例如4,您的错误消息将被输出;但是如果他们输入一个不是有效整数的字符串,例如red,它会引发ValueError异常并使您的程序崩溃,而不是触发您的错误逻辑。您可以使用一try两个块来捕捉它:

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
于 2013-09-29T23:02:31.973 回答