【发布时间】:2015-04-16 06:16:00
【问题描述】:
我需要询问用户是否想玩游戏,如果答案是y,那么程序会询问你想玩什么游戏,如果用户输入n,甚至输入他们将被再次询问,直到他们输入y。
现在我的 while 循环可以接受任何答案。任何人都能够看到我错过了什么或做错了什么?
playAGame = 'y'
while playAGame == 'y':
playAGame = raw_input('Would you like to play a game? (y/n)? ')
doAnother = 'y'
while doAnother == 'y':
print 'Chess'
print 'Tic Tac Toe'
print 'Tetris'
print 'Count'
print
print 'Global Thermonuclear War'
game = raw_input('Pick a game: ').lower()
if game == 'chess':
webbrowser.open_new("http://www.pygame.org/tags/chess")
break
elif game == 'tic tac toe':
webbrowser.open_new("http://www.pygame.org/tags/tictactoe")
break
elif game == 'tetris':
webbrowser.open_new("http://www.pygame.org/project-Clone+of+Tetris-2125-.html")
break
elif game == 'thermonuclear':
print "\nWouldn't you perfer a good game of chess?\n"
break
elif game == 'count':
maxNumber = input('How High? ')
for maxNumber in range(maxNumber):
print maxNumber
break
else:
print '\nI did not understand that!\n'
break
# Ask user if they want to do another
doAnother = raw_input('Do another (y/n)? ')
print '\nThanks for playing!'
print '\nGood Bye!'
【问题讨论】:
-
playAGame = 'y'; if playAGame == 'y':的意义何在?!另外请注意,如果他们玩过count,您只会询问用户是否想再玩一次。 -
如果假设有一段时间,但我仍然卡住......
-
请将其缩减为minimal example - 大多数代码都无关紧要。此外,请澄清您所期望的行为,以及会发生什么。
-
不要使用 playAGame 作为角色,而是使用布尔值。例如,在开始时将其命名为
isPlaying = True,并在您希望退出时将其设置为 false。或者只是使用 break 语句退出循环。
标签: python while-loop nested