[英]Second while loop only loops once
我正在做石头剪刀布游戏。 一切正常,除了我不明白为什么第二个while循环在此代码中不起作用。 我想制作程序,以便如果用户未输入“ R”,“ P”或“ S”,则将被告知用户该输入无效,并提示用户再次输入答案。 它对player1完全正常,但对player2不起作用。 对于player2,如果您不输入“ R”或“ P或“ S”,则无论您输入什么内容,它都会提示您再次输入一个新值,但只能输入一次。感谢所有帮助!
if playGame == "Y":
print("Ok, here we go.")
player1 = input("Player1, what is your choice, R, P, or S? ")
player1 = player1.upper()
while player1 != 'R' and player1 != 'P' and player1 != 'S':
player1 = input("Invalid answer. Please answer R, P, or S: ")
player1 = player1.upper()
player2 = input("Player2, what is your choice, R, P, or S? ")
player2 = player2.upper()
while player2 != 'R' and player2 != 'P' and player2 != 'S':
player2 = input("Invalid answer. Please answer R, P, or S: ")
player2 = player1.upper()
错误在最后一行
player2 = player1.upper()
应该
player2 = player2.upper()
当用户输入无效值时,使用while
循环反复询问用户。
码:
playGame = raw_input("You want to play game: if yes then enter Y:").upper()
if playGame == "Y":
print("Ok, here we go.")
player1 = ''
while 1:
player1 = raw_input("Player1, what is your choice, R, P, or S?:").upper()
if player1 not in ['R', 'P', 'S']:
print "Invalid answer."
else:
break
player2 = ''
while 1:
player2 = raw_input("Player2, what is your choice, R, P, or S?:").upper()
if player2 not in ['R', 'P', 'S']:
print "Invalid answer."
else:
break
print "player1:", player1
print "player2:", player2
输出:
vivek@vivek:~/Desktop/stackoverflow$ python 7.py
You want to paly game: if yes then enter Y:Y
Ok, here we go.
Player1, what is your choice, R, P, or S?:a
Invalid answer.
Player1, what is your choice, R, P, or S?:R
Player2, what is your choice, R, P, or S?:w
Invalid answer.
Player2, what is your choice, R, P, or S?:q
Invalid answer.
Player2, what is your choice, R, P, or S?:s
player1: R
player2: S
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.