3 回答
TA贡献1812条经验 获得超5个赞
将下一个用户输入cont2分配给的位置,您只需重新分配给cont。如果用户按“N”,这将“中断”while 循环。然后您将不再需要第二个 while 循环。
编辑:正如上面 Daniel 所说,你的代码 nog 总是给出相同的计算机掷骰子。Yoy 应该将ai行更改为while 循环内部。
import random
import time
player = random.randint(1,6)
# remove ai = random.randint(1,6) here
cont = str(input('Roll the dice? Y/N'))
while cont == "Y":
print ("You are rolling...")
time.sleep(3)
print ("You rolled " + str(player))
print("The computer rolls...." )
ai = random.randint(1,6) # <-- add here again
time.sleep(3)
print ("The computer rolled " + str(ai))
if player > ai:
print("You win")
if ai > player:
print("You lose")
cont = str(input('Would you like to play again? Y/N')) # <-- this line is changed
print ("I hope you enjoyed playing dice. Have a great day!")
您还可以通过.upper()在输入后添加来使其对给定的用户输入更加健壮。所以:cont = str(input('Roll the dice? Y/N')).upper()。如果用户然后输入 'y' 而不是 'Y',它仍然可以工作。
TA贡献1869条经验 获得超4个赞
import random
import time
cont = str(input('Roll the dice? Y/N'))
while cont == "Y":
player = random.randint(1,6)
ai = random.randint(1,6)
print ("You are rolling...")
time.sleep(3)
print ("You rolled " + str(player))
print("The computer rolls...." )
time.sleep(3)
print ("The computer rolled " + str(ai))
if player > ai:
print("You win")
if ai > player:
print("You lose")
cont2 = str(input('Would you like to play again? Y/N'))
if cont2.lower() == 'y':
cont == "Y"
elif cont2.lower() == 'n':
cont == "N"
break
print ("I hope you enjoyed playing dice. Have a great day!"
只是为了使您的代码更健壮,我在while循环中包含了掷骰子的值。其次,您可以while使用 an摆脱第二个循环,if--else使您的代码更具可读性和可理解性。
添加回答
举报