迭代不是迭代?

  • 本文关键字:迭代 python iterator
  • 更新时间 :
  • 英文 :


我一直在做一个掷骰子的程序。我想做的一件事是让它投掷特定数量的骰子(如2d6)。然而,这部分代码似乎不起作用,我认为它只返回一次掷骰子。

我有:

import random

# Format die rolls like so:  n dice d die size.  i.e. "4d6" will roll 4 six sided dice.
# You can also leave off the number of dice if you want to roll just one.
def die_roll(input_1):  # This is the dice rolling function
roll = 0
if "d" not in input_1:  # Should weed out most strings
return "Not a valid die"
splitter = input_1.split("d")  # should split the die roll into number of dice and die type
die_type = splitter[1]  # Grabs the second item from the list created above and sets it to the type of die used
pos1 = splitter[0]  # Tells you how many die to roll
if pos1 == "":  # Puts a 1 in the multiplication place so that the math works in cases such as "d6" or "d4"
pos1 = "1"
if die_type not in ["4", "6", "8", "10", "12", "20", "100"]:  # Checks whether a valid die was indicated
return "Not a valid die"
else:
if pos1 == "1":
roll = dice(die_type)
return roll
else: # This specifically is what I need help with
for i in range(int(pos1)):
roll = roll + dice(die_type)
return roll

def dice(roller):  # Rolls the actual dice.  Splitting it off here, theoretically, makes handling iteration.
output = 0
if roller == "4":
output = random.randrange(1, 4)
if roller == "6":
output = random.randrange(1, 6)
if roller == "8":
output = random.randrange(1, 8)
if roller == "10":
output = random.randrange(1, 10)
if roller == "12":
output = random.randrange(1, 12)
if roller == "20":
output = random.randrange(1, 20)
if roller == "100":
output = random.randrange(1, 100)
return output

while True:
thing = input("What would you like to roll?")
print(die_roll(thing))

所以我的问题是,为什么它似乎不迭代?

return roll标识错误。这将导致函数在1次迭代后返回。

else: # This specifically is what I need help with
for i in range(int(pos1)):
roll = roll + dice(die_type)
return roll

将验证输入与实际尝试掷骰子分开处理。

def validate_dice_input(s: str) -> Tuple[int, int]:
try:
n_dice, n_sides = s.split("d")
n_dice = int(n_dice)
n_sides = int(n_sides)
except Exception:
raise ValueError(f"Invalid dice input {s}")
if n_dice < 0:
raise ValueError(f"Cannot roll a negative number of dice ({n_dice})")
if n_sides not in [4, 6, 8, 10, 12, 20, 100]:
raise ValueError(f"Unknown die size '{n_sides}'")
return n_dice, n_sides

那么,掷一个骰子和掷多个骰子实际上没有什么不同。将全部滚动,并求和。

def dice_roll(dice: Tuple[int, int]) -> int:
n, s = dice
return sum(die_roll(s) for _ in range(n))

die_roll不一定要做自己的验证。只要你得到一个整数输入,无论输入是否对应于"实数",所做的功都是一样的。模具大小与否。(使用roll方法的Die类将有助于防止在无效骰子上调用roll,因为您可以首先防止创建无效的Die实例。)

def die_roll(sides: int) -> int:
return random.randint(1, sides)

然后你的循环,一旦它从validate_date_input得到一个值,就可以简单地用这个值调用dice_roll

while True:
thing = input("What would you like to roll?")
try:
dice = validate_dice_input(thing)
except ValueError as exc:
print(exc)
print("Try again")
continue
print(dice_roll(dice))

相关内容

  • 没有找到相关文章

最新更新