我的计划如下:
#Question 6_2010.py
PlayerOneScore=0
PlayerTwoScore=0
NoOfGamesInMatch=(int(input('How many games in the match?')))
NoOfGamesPlayed=1+NoOfGamesInMatch
for NoOfGamesPlayed in range(NoOfGamesInMatch):
while NoOfGamesInMatch!=NoOfGamesPlayed:
PlayerOneWinsGame=(input('Did Player One win the game (enter Y or N)?'))
if PlayerOneWinsGame=='Y':
PlayerOneScore = PlayerOneScore + 1
else:
PlayerTwoScore = PlayerTwoScore + 1
print(PlayerOneScore)
print(PlayerTwoScore)
这并不复杂。我刚开始使用Python,所以我对循环有点困惑。当程序运行时,程序按原样运行 - 它打印"'Did Player One win the game (enter Y or N)?')"
我为NoOfGamesInMatch
输入的次数,但是,当它打印出玩家得分时,它只会执行1 0,具体取决于是否是否输入'Y'。如果我输入8个游戏,5个“Y”和3个“N”(或任何其他角色),它应该将PlayerOneScore打印为5,将PlayerTwoScore打印为3,但它只能打10个。
我的while循环中缺少什么?感谢。
答案 0 :(得分:3)
您的缩进只是关闭,因此增量发生在while
循环之外:
for NoOfGamesPlayed in range(NoOfGamesInMatch):
while NoOfGamesInMatch!=NoOfGamesPlayed:
PlayerOneWinsGame=(input('Did Player One win the game (enter Y or N)?'))
# Keep the if/else inside the while loop
if PlayerOneWinsGame=='Y':
PlayerOneScore = PlayerOneScore + 1
else:
PlayerTwoScore = PlayerTwoScore + 1
请注意,就目前的形式而言,您必须实际输入引用的字符串"Y"
,而不仅仅是Y
。
实际上,经过测试,我意识到你甚至不需要while
循环。拥有它(即使你增加NoOfGamesPlayed
倍数游戏。只需使用:
for NoOfGamesPlayed in range(NoOfGamesInMatch):
PlayerOneWinsGame=(input('Did Player One win the game (enter Y or N)?'))
if PlayerOneWinsGame=='Y':
PlayerOneScore = PlayerOneScore + 1
else:
PlayerTwoScore = PlayerTwoScore + 1