Antriksh Shukla
Antriksh Shukla

Reputation: 5

I want to know what's wrong in my code. A set of 2 die are rolled and random values are printed

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

Answers (3)

Vignesh SP
Vignesh SP

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)
  1. The class Dice is not initialized in your code, you need to assign the class to a var to initiate it.
  2. The function roll is not returning any value, so return it.
  3. The var roll contains 6 elements and it cannot be fed to 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

wjandrea
wjandrea

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

Deepstop
Deepstop

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

Related Questions