首页 > 解决方案 > 编写至少一个函数来模拟掷骰子

问题描述

我的任务是编写至少一个函数来模拟掷骰子,并在循环中为每个玩家调用该函数,找到掷骰子的总和,尽管我发现自己严重遭受分析瘫痪的折磨。

样本输出

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:“函数”对象不可迭代

标签: pythonfunctionmethodsdice

解决方案


该错误是由最后一行引起的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))

推荐阅读