python - 编写至少一个函数来模拟掷骰子
问题描述
我的任务是编写至少一个函数来模拟掷骰子,并在循环中为每个玩家调用该函数,找到掷骰子的总和,尽管我发现自己严重遭受分析瘫痪的折磨。
样本输出
How many players are rolling dice? 2
How many dice does each player roll? 3
How many sides does each die have? 6
Player 1 rolled:
4
2
4
That totals: 10
Player 2 rolled:
1
3
5
That totals: 9
到目前为止我的代码
import random
#User inputs
r = int(input("How many times do you want to roll the dice? "))
s = int(input("how many sides do you want "))
p = int(input("How many players are rolling dice?"))
#Function Declaration
def Rolldice(s,r):
for i in range(0,r):
die = random.randint(1, s)
print(die)
#For loop that iterates through function declaration
for num in range(1,p+1):
print(f"player {num} rolled")
Rolldice(s,r)
print(sum(Rolldice))
虽然我收到下面列出的错误
TypeError:“函数”对象不可迭代
解决方案
该错误是由最后一行引起的print(sum(Rolldice))
。Rolldice
是一个函数,你不能对函数求和。我想这应该可以解决您的问题-
import random
#User inputs
r = int(input("How many times do you want to roll the dice? "))
s = int(input("how many sides do you want "))
p = int(input("How many players are rolling dice?"))
#Function Declaration
def Rolldice(s,r):
dies = []
for i in range(0,r):
die = random.randint(1, s)
print(die)
dies.append(die)
return dies
#For loop that iterates through function declaration
for num in range(1,p+1):
print(f"player {num} rolled")
dies = Rolldice(s,r)
print("That totals:", sum(dies))
推荐阅读
- ruby-on-rails - rails盲索引gem raw sql查询不起作用
- javascript - 如何在反应导航 5 中替换切换导航器?
- python - 如何在 Python 中与 Flask 并行运行其他代码
- assembly - 无法调整大小说明
- excel - 如何在Excel中查找范围内的值
- lua - 为什么我的强化道具没有出现在我的 LOVE2D 游戏中?
- string - 在 powershell 中,在匹配的模式前面添加一个变量
- azure - Azure 管道:是否必须在同一分支中拥有 azure 管道和代码
- azure - 如何从 Prometheus 服务器中的 Azure app-insight 获取自定义指标?
- python - 将两个变量放在这样的 if 语句中是什么意思:variable[variable2]?