[英]Python - Replaying While Loop Dice Roll Game
如果用户在被询问是否要再次掷骰子后输入无效响应,我应该如何重播以下循环?
如果不弄乱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'.")
从底部的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()
我建议你用两个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.