2013-09-29 53 views
0

我试图显示两种混合素数颜色的二次色。我有点卡在代码上,但它似乎在我运行它时都会检查,它总是显示我放入的其他错误消息。我该怎么做?!Python的颜色练习

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

回答

3

input返回一个字符串,但在变量redblueyellow值是整数。整数和字符串不相等:

>>> '5' == 5 
False 

您可以变通的作法是要么使你redblueyellow变量字符串:

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,则会引发异常并导致程序崩溃而不是触发错误逻辑。您可以使用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 
+0

哇!谢谢,我很轻松地看了一眼。这么简单哈哈 – RobertJRodriguez