Reputation: 5
I made a code for generating random values when a set of 2 die are rolled. Error says roll isn't defined. Can't figure out why it says that. I want to know what's wrong with my approach, I've already seen other solutions to the problem.
Novice programmer. My first problem related to generating random values.
import random
class Dice:
def roll(self):
roll = (1, 2, 3, 4, 5, 6)
toss = random.randint(roll)
print(toss, toss)
toss = random.randint(roll)
Error :
NameError: name 'roll' is not defined
Upvotes: 0
Views: 125
Reputation: 446
import random
class Dice:
def roll(self):
roll = 6
return roll
obj = Dice()
number = obj.roll()
toss = random.randint(1,number)
toss2 = random.randint(1,number)
print(toss, toss2)
Dice
is not initialized in your code, you need to assign the class to a var to initiate it.randint
function as it only takes 2 arguments. So I changed the value of roll
to the largest number and fed it to the randint
Upvotes: 0
Reputation: 33107
The problem is that roll
isn't defined in the global namespace, only under Dice
or Dice.roll
depending on which one you're talking about.
As well, random.randint
takes two arguments, which define the range.
I don't know why you're using a class for something so simple, but if you insist, you could do it like this:
import random
class Die:
def __init__(self, sides):
if sides <= 1:
raise ValueError('Sides must be more than 1')
self.sides = sides
def roll(self):
return random.randint(1, self.sides)
d6 = Die(6)
print(d6.roll(), d6.roll())
Upvotes: 1
Reputation: 3817
You don't need a class or a function for this operation if what you want is toss to be a number between 1 and 6.
All you need is the following.
import random
toss1 = random.randint(1,6)
toss2 = random.randint(1,6)
print(toss1, toss2)
Enjoy learning Python. It's a lot of fun.
Upvotes: 2