Unexpected NameError in Python without syntax error
Question:
I’m trying to write in Visual Studio Code for Linux a simple roll dice program, but for some reason I have an unexpected NameError that makes me mad.
This is my code:
from random import randint
class Dice:
def __init__(self, sides):
self.sides = sides
def roll(self):
play = randint (1, Dice.sides)
print (play)
dado = Dice(6)
roll()
When I try to run program it fails with this error:
NameError: name ‘roll’ is not defined
I don’t understand why, I know is probably a very stupid thing, but I don’t see any problem whit the name "roll"…
Answers:
In your code, you are doing Object Oriented Programming (OOP), which in Python, consists of classes.
The roll
function is inside the Dice
class, so just doing roll()
is not enough.
You need to first create an instance of the class, and use that instance to run the roll
function:
dice = Dice(6)
dice.roll()
As for your example, you could do this:
dado.roll()
You should create an instance of the class first. Also, there is an error in roll function – you should use self.sides instead of Dice.sides. So, resulting code should look like this:
from random import randint
class Dice:
def __init__(self):
self.sides = 6
def roll(self):
play = randint(1, self.sides)
print(play)
my_dice = Dice()
my_dice.roll()
I’m trying to write in Visual Studio Code for Linux a simple roll dice program, but for some reason I have an unexpected NameError that makes me mad.
This is my code:
from random import randint
class Dice:
def __init__(self, sides):
self.sides = sides
def roll(self):
play = randint (1, Dice.sides)
print (play)
dado = Dice(6)
roll()
When I try to run program it fails with this error:
NameError: name ‘roll’ is not defined
I don’t understand why, I know is probably a very stupid thing, but I don’t see any problem whit the name "roll"…
In your code, you are doing Object Oriented Programming (OOP), which in Python, consists of classes.
The roll
function is inside the Dice
class, so just doing roll()
is not enough.
You need to first create an instance of the class, and use that instance to run the roll
function:
dice = Dice(6)
dice.roll()
As for your example, you could do this:
dado.roll()
You should create an instance of the class first. Also, there is an error in roll function – you should use self.sides instead of Dice.sides. So, resulting code should look like this:
from random import randint
class Dice:
def __init__(self):
self.sides = 6
def roll(self):
play = randint(1, self.sides)
print(play)
my_dice = Dice()
my_dice.roll()