我的目标是制作一个同时掷多个骰子的功能。用户输入骰子上有多少面(包括 2-20 之间),用户输入要使用的骰子数量(3 和 6 之间)。然后程序计算一个介于 1 和用户输入的边数之间的随机数,以生成骰子落在的边(和得分)。并将显示生成的每个骰子的得分(面)。我不知道如何正确地将它组合在一起,并且一直在尝试类似问题的其他代码,但还没有运气。我有一些循环来验证输入是否在范围内,但我删除了它以保持简短。输出示例Enter # of faces [2,20]: 10Enter # of dice [3,6]: 4You have rolled: [9, 3, 8, 8]代码:face = int( input( "how many sides are on your die? enter a number between 2-20 inclusive: "))number_of_dice = int( input( "How many dice are you using? Must be between 3-6 inclusive" ) )def roll_die(): for _ in range(rolls): print random.randint(1, face)
1 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
与其打印掷骰子,不如将其添加到列表中。
import random
faces = int(input("How many sides on a die? ")
num_dice = int(input("How many dice? ")
rolls = []
for die in range(num_dice):
dice_roll = random.randint(1, faces)
rolls.append(dice_roll)
print("You have rolled: " + str(rolls))
然后你可以对可读性进行一些小的改进,比如重构这个
rolls = []
for die in range(num_dice):
dice_roll = random.randint(1, faces)
rolls.append(dice_roll)
进入这个
rolls = [random.randint(1, faces) for _ in range(num_dice)]
甚至使用字符串格式或 f 字符串进行打印。
print("You have rolled: {}".format(rolls))
# or
print(f"You have rolled: {rolls}")
添加回答
举报
0/150
提交
取消