SebTheGoat
SebTheGoat

Reputation: 15

Python printing random numbers in functions

I'm trying to make a dice rolling simulator, I haven't come very far, and I already have a problem.

Here's my code:

#Dice roll simulation

from random import *

#The minimum and maximum numbers on the dice
min = 1
max = 6

#The function for rolling the dice. Should print a number between 1 and 6...
def roll (min, max):
number = random.randint(min, max)
    print(number)
    return

roll(min, max)

The function 'roll' should print out a random number between 1 and 6, but instead, I get this error message whenever I run the program:

C:\Users\Sebastian\PycharmProjects\minigames\venv\Scripts\python.exe C:/Users/Sebastian/PycharmProjects/minigames/diceroll.py Traceback (most recent call last): File "C:/Users/Sebastian/PycharmProjects/minigames/diceroll.py", line 15, in roll(min, max) File "C:/Users/Sebastian/PycharmProjects/minigames/diceroll.py", line 11, in roll number = random.randint(min, max) AttributeError: 'builtin_function_or_method' object has no attribute 'randint'

Process finished with exit code 1

Upvotes: 1

Views: 815

Answers (2)

Mithilesh_Kunal
Mithilesh_Kunal

Reputation: 929

Why is your code failing?

The problem is with your import statement.

How to correct it?

Your code contains, from random import * as the first statement. This imports all the items present in random.py. Thus the below code will work.

from random import *
print(randint(1,6))

The other option is to import the module as below.

import random
print(random.randint(1,6))

Among the above two approaches, the good practice is to use the second type. Reason is when your code grows, it will be easy to identify the source of the called function.

Upvotes: 2

fcracker79
fcracker79

Reputation: 1218

random modules includes the randint method, so either:

  1. replacefrom random import * with import random
  2. replace random.randint with randint as Ab Bennt suggested.

Upvotes: 3

Related Questions