从while循环中的原始输入中断

2024-06-03 13:51:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了一个非常简单的掷骰子脚本。你可以滚三次。但是,我不知道如何打破while循环,避免最后一次的原始输入。在

#!/usr/bin/python

from random import randrange, uniform

def rollDice():
  dice = randrange(3,18)
  print ("You rolled: %s" % dice)

maxReRoll = 2
c = 0
reRoll = "y"

while reRoll in ["Yes", "yes", "y", "Y"]:
  if c > maxReRoll:
    break
  else:
    rollDice()
    c+=1
    reRoll = raw_input("Roll again?  y/n ")

Tags: fromimport脚本binusrdefrandomuniform
2条回答

只是需要一点交换。在

while reRoll in ["Yes", "yes", "y", "Y"]:
  rollDice()
  c+=1
  if c >= maxReRoll:  # notice the '>=' operator here
    break
  else:
    reRoll = raw_input("Roll again?  y/n ")

这应该对您有用:

from random import randrange


def roll_dice():
    dice = randrange(3,18)
    print("You rolled: %s" % dice)

max_rolls = 2
c = 0
re_roll = "y"

while re_roll.lower() in ["yes", "y"] and (c < max_rolls):
    roll_dice()
    c += 1
    if c != max_rolls:
        re_roll = input("Roll again?  y/n ")

相关问题 更多 >