如果在询问用户是否要再次掷骰子后输入无效响应,我应该如何重播下面的循环?
如果不弄乱while循环,我就无法使其工作。这是我到目前为止所拥有的
# Ask the player if they want to play again
another_attempt = input("Roll dice again [y|n]?")
while another_attempt == 'y':
roll_guess = int(input("Please enter your guess for the roll: "))
if roll_guess == dicescore :
print("Well done! You guessed it!")
correct += 1
rounds +=1
if correct >= 4:
elif roll_guess % 2 == 0:
print("No sorry, it's", dicescore, "not", roll_guess)
incorrect += 1
rounds +=1
else:
print("No sorry, it's ", dicescore, " not ", roll_guess, \
". The score is always even.", sep='')
incorrect += 1
rounds +=1
another_attempt = input('Roll dice again [y|n]? ')
if another_attempt == 'n':
print("""Game Summary""")
else:
print("Please enter either 'y' or 'n'.")
答案 0 :(得分:0)
从底部的while循环中删除if else语句,并在while循环中添加以下内容:
another_attempt = input('Roll dice again [y|n]? ')
if another_attempt != 'n' or another_attempt == 'y':
another_attempt = 'y'
elif another_attempt == 'n':
print("""Game Summary
===========
You played""", rounds, """games
|--> Number of correct guesses:""", correct, """
|--> Number of incorrect guesses:""", incorrect, """
Thanks for playing!""")
exit()
答案 1 :(得分:0)
我建议您使用两个while循环来完成此操作,并使用函数使代码逻辑更清晰。
def play_round():
# Roll dice
# Compute score
# Display dice
# Get roll guess
def another_attempt():
while True:
answer = input("Roll dice again [y|n]?")
if answer == 'y':
return answer
elif answer == 'n':
return answer
else:
print("Please enter either 'y' or 'n'.")
def play_game():
while another_attempt() == 'y':
play_round()
# Print game summary