我想知道如何在Python中求和和使用范围值。
假设我要使用以下内容:
You rolled 12 dices. The numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11.
Would you like to score the points for all different numbers (50 points)?
我将如何为所有数字得分?
我对for n in range(12):
和random.randint(1,12)
有所了解,但是我对Python不太了解,并希望对此有所帮助。预先谢谢你。
答案 0 :(得分:1)
您的意思是:
print("You rolled", sum(number), "dices. The numbers are", random.sample(range(50), 12), ".")
答案 1 :(得分:0)
我认为这对于numpy是一项很好的任务。
首先,您应该确定他们要使用多少个骰子,以及每个骰子上要具有多少条边。然后,您应该掷骰子,并根据边缘的数量获得每个骰子的输出(将重复进行模拟真实世界的场景)。最后,您询问他们是否要求和,是否使用np.sum()
对他们求和。
完整代码:
import numpy as np
num_dice = int(input("How many dice would you like to roll? "))
dice_sides = int(input("How many sides per die? "))
while num_dice <= 0 or dice_sides <=0:
if num_dice <= 0:
num_dice = int(input("Invalid number of dice, enter a number greater than or equal to 1."))
else:
dice_sides = int(input("Invalid number of sides, enter a number greater than or equal to 1."))
rolled_nums = np.random.choice(range(1, dice_sides), size=num_dice, replace=True)
# If you don't want the brackets around the numbers produced by the dice rolling,
# use ", ".join(str(i) for i in list(rolled_nums)) instead of list(rolled_nums) here.
print("You rolled {} dices. The numbers are {}.".format(num_dice, list(rolled_nums)))
decision = input("Would you like to sum the points for all the rolled numbers? (y/n) -> ")
if decision == 'y' or decision == 'Y':
print("Total sum of all the rolled numbers is: {}".format(np.sum(rolled_nums)))
else:
quit()
一些要注意的事项:
format()
中print()
的使用,这有助于保持命令的整洁。我强烈建议将其与更复杂的代码一起使用,这样可以节省生命。在此处查看更多详细信息:https://www.geeksforgeeks.org/python-format-function/ ", ".join(str(i) for i in list(rolled_nums))
而不是list(rolled_nums)
。这在代码中带有注释 编辑:
如果您不喜欢numpy,那么这里仅使用import random
就具有相同的功能。
import random
num_dice = int(input("How many dice would you like to roll? "))
dice_sides = int(input("How many sides per die? "))
while num_dice <= 0 or dice_sides <=0:
if num_dice <= 0:
num_dice = int(input("Invalid number of dice, enter a number greater than or equal to 1."))
else:
dice_sides = int(input("Invalid number of sides, enter a number greater than or equal to 1."))
# Roll the dice one at a time and store their values
rolled_nums = []
for _ in range(num_dice):
rolled_nums.append(random.choice(range(1, dice_sides)))
print("You rolled {} dices. The numbers are {}.".format(num_dice, rolled_nums))
decision = input("Would you like to sum the points for all the rolled numbers? (y/n) -> ")
if decision == 'y' or decision == 'Y':
print("Total sum of all the rolled numbers is: {}".format(sum(rolled_nums)))
else:
quit()
同样,您可以使用上述方法(第3点)从数字列表中删除方括号。