0

我是一个初学者的python程序员。请需要帮助。

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。坦克寻求帮助我修复了 int 并且它起作用了。

4

2 回答 2

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!'))
于 2013-10-03T02:03:46.520 回答
1

int尝试将输入转换为整数,因此int('Red')会抛出ValueError.

您应该使用raw_input而不是input删除 int 调用:

lightcolor=raw_input("Enter Red,Green,Yellow,White,Purple,Blue,Orange,Brown,or Black->")
于 2013-10-02T02:58:38.210 回答