Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dice program
#1
Problem statement :
Dice: The module random contains functions that generate random numbers in a variety of ways.
The function randint() returns an integer in the range you provide. The following code returns a number between 1 and 6:
from random import randint
x = randint(1, 6)
Make a class Die with one attribute called sides, which has a default value of 6.
Write a method called roll_die() that prints a random number between 1 and the number of sides the die has.
Make a 6-sided die and roll it 10 times.Make a 10-sided die and a 20-sided die. Roll each die 10 times.

My try:

from random import randint
class Dice(object):
    def __init__(self):
        self.sides=6
        
    def roll_dice(self):
        x=randint(1,self.sides)
        print(x)
        
dice_roll1=Dice()
dice_roll1.roll_dice(10)
I'm getting this error:
Error:
Traceback (most recent call last): File "main.py", line 19, in <module> dice_roll1.roll_dice(10) TypeError: roll_dice() takes 1 positional argument but 2 were given
Please help me clear this error
Reply
#2
can you explain why do you pass 10 as argument to Dice.roll_dice() method?
Because it is the problem. When you call a class method it always get the instance as first argument (that's self argument for)

So to start from beginning

you need to have sides argument in the __init__() method. It has to have default value of 6. So when you don't pass something different or nothing at all it will be 6-sides dice. But for example if you instantiate dice and pass sides=10, it will be 10-sides dice.

To roll the dice 10 times you need a loop
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank you so much buran. I modified the code and got the results
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020