我是python的新手,我的程序有问题。我正在尝试使用for循环创建“猜测颜色-游戏”,这是我的代码:
from random import randint
colors = ['red', 'blue', 'black', 'pink']
generator = randint(0,len(colors)-1)
guess = input('guess a color: ')
for color in colors[generator]:
if guess != colors[generator]:
print('wrong, try again')
guess = input('guess a color: ')
elif guess == colors[generator]:
break
print('yay, color was: ' + colors[generator])
答案 0 :(得分:1)
如果您非常仔细地查看代码输出,您会注意到您在“蓝色”答案中放置了一个空格。它接受的是不匹配的“蓝色”。由于您的for循环停止于随机选择的颜色的字母数,因此停止并输出了正确的颜色。如果要考虑错误的空间,应该具有以下内容:
from random import randint
colors = ['red', 'blue', 'black', 'pink']
generator = randint(0,len(colors)-1)
guess = input('guess a color: ')
while True: #you want to keep guessing until you actually get it
if guess != colors[generator]:
print('wrong, try again')
guess = input('guess a color: ').strip() #strip() here removes spaces
elif guess == colors[generator]:
break
print('yay, color was: ' + colors[generator])