2014-02-16 72 views
1

我想寫一個程序,要求用戶輸入兩種顏色,然後顯示結果顏色。這是我到目前爲止有:python多功能編程

#Define function that prompts user to enter data 
def ask(): 
    color1=input('Enter name of first primary color:') 
    color2=input('Enter name of second primary color:') 
    mixColors(color1,color2) 
#Write function that displays the different color combinations 
def mixColors(color1,color2): 
    if color1==red and color2==blue: 
     print('Mixing red and blue, you get purple.') 
    elif color1==blue and color2==red: 
     print('Mixing blue andred, you get purple.') 
    elif color1==red and color2==yellow: 
     print('Mixing red and yellow, you get orange.') 
    elif color1==yellow and color2==red: 
     print('Mixing yellow and red, you get orange.') 
    elif color1==blue and color2==yellow: 
     print('Mixing blue and yellow you get green.') 
    elif color1==yellow and color2==blue: 
     print('Mixing yellow and blue, you get green.') 
    else: 
     print("I don't know what you get by mixing", color1,'and',color2,'.') 
ask() 

當我運行程序,出現此錯誤消息:

Traceback (most recent call last): 
    File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 23, in <module> 
    ask() 
    File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 6, in ask 
    mixColors(color1,color2) 
    File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 9, in mixColors 
    if color1==red and color2==blue: 
NameError: global name 'red' is not defined 
+0

你應該使用鍵的字典(「紅」,「藍」),(「藍」,「紅」),(「紅」 ,'yellow')等 – eyquem

+0

如果使用frozensets作爲鍵,則可以減少字典中的項目數 – Matt

回答

6

在Python中,字符串必須用單或雙引號('"封閉)。否則,他們將被視爲變量。

在這種情況下,red既不是變量也不是字符串。由於red不是字符串,因此Python在當前名稱空間,父名稱空間和全局名稱空間中搜索red。但變數red不在其中任何一個。所以,它放棄並拋出錯誤信息。

所以,所有的如果條件應該已經

if color1=="red" and color2=="blue": 
... 
elif color1=="blue" and color2=="red": 
... 
elif color1=="red" and color2=="yellow": 
... 
elif color1=="yellow" and color2=="red": 
... 
elif color1=="blue" and color2=="yellow": 
... 
elif color1=="yellow" and color2=="blue": 
... 
+0

現在可以使用。謝謝! – user3307366

+1

@ user3307366很酷。請考慮[接受此答案](http://meta.stackexchange.com/a/5235/235416),如果它可以幫助你。 – thefourtheye