2013-10-02 25 views
0

我是一個初學python程序員。請提供援助。無效的文字int()與基本錯誤,每次我輸入任何顏色

lightcolor=int(input("Enter Red,Green,Yellow,White,Purple,Blue,Orange,Brown,or Black->")) 
if lightcolor=="Red": 
    print("Red Light-Please stop!!") 
elif lightcolor=="Green": 
    print("Green Light-Please continue") 
elif lightcolor=="Yellow": 
    print("Yellow Light-speed up") 
elif lightcolor=="White": 
    print("White Light-its too bright") 
elif lightcolor=="Purple": 
    print("Purple Light-pretty") 
elif lightcolor=="Blue": 
    print("Blue Light-thats unusual") 
elif lightcolor=="Orange": 
    print("Orange Light-bright as the sun") 

elif lightcolor=="Brown": 
    print("Brown Light-like dirt") 
elif lightcolor=="Black": 
    print("Black Light-very dark") 
else: 
    print("Sorry no such color"),lightcolor 

爲什麼我每次輸入任何顏色時都會遇到基本錯誤的int()無效文字?我正在使用Python 3.坦克的幫助我修復了整數,它工作。

+0

要調用' int()'輸入()'值,而'int(「紅色」)'無效。 – Blckknght

+0

因爲你想轉換爲一個整數,所以不能分析的字符串就像這樣=>「」Red「」或「Green」不是整數! –

+2

通常,當您收到錯誤消息並在StackOverflow上詢問有關它的問題時,實際在您的問題中包含回溯會很有幫助。在這種情況下,這實際上並不是必要的 - @Blckknght是100%正確的。什麼是int在那裏呢?無處不在... – mgilson

回答

1

int嘗試將輸入轉換爲整數,因此int('Red')將拋出ValueError

您應該使用raw_input代替input並刪除INT電話:

lightcolor=raw_input("Enter Red,Green,Yellow,White,Purple,Blue,Orange,Brown,or Black->") 
+0

Python 2的'raw_input' ... Python 3的''input'' – kojiro

+0

@kojiro未指定任何版本,並且AFAICT大多數操作系統默認仍帶有python2(例如,osx與2.7.2) – SheetJS

+0

@Nirk:'print'後面的圓括號表明這個用戶在Python 3上(儘管在這種情況下最後的'print'可能不會按預期工作。 – Blckknght

1

卸下int,並使其成爲一個dict將是前進的方向......

colours = { 
    # List colours... and spelling variations... (put in lower case for easier comp.) 
    'red': 'Stop', 
    'green': 'Go', 
    'black': 'Dark' 
} 
# Get colour and prompt based on the colours in the dictionary 
input_colour = input('Enter a colour (one of: {})'.format('|'.join(colours)) 
# Try and get description from colours, otherwise use "Not Valid!" 
print('That color is:', colours.get(input_colour.lower(), 'Not Valid!')) 
相關問題