【问题标题】:Making a program randomly roll a 6-sided die制作程序随机掷 6 面骰子
【发布时间】:2020-05-02 12:35:32
【问题描述】:

我正在尝试做这个项目,但我迷路了。这是我第一次做这样的程序,我不知道从哪里开始。我试图让 dice.roll = 1 到 6 的范围,但我认为我不应该这样做,因为它说名称“random”没有定义。我不知道我做错了什么,也没有人可以解释。


# ************************

# Step 1: import from dice the Dice class

from dice import Dice

# Step 2: For the variable name dice, assign the Dice() class

class Dice():
    results=[]
# Step 3: Declare an empty results list

    results=[] 

# Step 4: Roll the dice 1000 times 


for roll_num in range(1000):
    dice.roll= random.randint(1,6)

# stores the results for each single dice roll in a list
    result = dice.roll()
    results.append(result)

# analyze the results
frequencies = []

# range starts at 0, increments by 1 and stops just before the last number
# Uses +1 to stop just before 7 for 1-6 sides

for value in range(1, dice.num_sides +1):

# Step 5: call the value as you count the results
    frequency = results.count()
# Step 6: similar to the results list, keep appending or adding the frequency
    frequencies.append()

# Step 7: Print the frequencies to the Python Shell
print()

【问题讨论】:

  • random 是一个必须导入的模块。你确定你已经导入了依赖? (即import random
  • 我的老师让我们为它导入这个程序。我试图弄清楚如何让骰子滚动 1000 次,但我不明白如何。 from random import randint class Dice(): """一个六面骰子的类""" def __init__(self, dice_sides=6): """六面骰子。""" self.dice_sides = dice_sides def roll(self): """返回一个介于 1 和边数之间的随机值。""" return randint(1, self.dice_sides)
  • 这能回答你的问题吗? Python dice simulation
  • google.com/search?q=python+dice周围有很多人做同样的作业。

标签: python


【解决方案1】:

老实说,我觉得 OP(原发帖人)对几个 python 概念缺乏理解。

  1. 在模块中导入

我相信您有一个名为dice.py 的python 文件,其中包含Dice 类的定义,可能如下(来自您的cmets)

from random import randint
class Dice():
    """A class for a single six-sided die"""
    def __init__(self, dice_sides=6):
        """A six-sided die."""
        self.dice_sides = dice_sides

    def roll(self):
        """Returns a random value between 1 and the number of sides."""
        return randint(1, self.dice_sides)

你应该知道random中的一个函数randint被导入到python文件dice.py中,然后就可以使用文件中的函数了,比如randint(1, self.dice_sides)

Dice.roll()的返回值应该是randint(1, self.dice_sides+1)

  1. 类的实例

从模块dice 导入Dice 后,您可以像下面这样实例化该类。这将更正您在第 2 步中的代码。

adice = Dice()
# then this would be a 6-side dice

然后你可以从变量中得到一个卷号,因为它有方法(即类中的函数)roll

a_random_result = adice.roll()
print(a_random_result)

在此之后,您应该使用 for 循环来获得 1000 个结果并将它们存储在 results 中。

【讨论】:

  • 如果您认为他 lacks understanding for several python concepts 最好在 cmets 中发布一个教程链接或找到一些重复的问题。
  • stackoverflow(在我的理解中)不应该是一个自定义教程集合,人们一遍又一遍地教其他人最基本的语言技能。
  • 谢谢,我可以阅读问答指南并获得更多经验。
猜你喜欢
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 2015-05-10
  • 2014-04-21
  • 1970-01-01
  • 2019-03-04
  • 2015-06-29
  • 2021-02-13
相关资源
最近更新 更多