-1

I was wondering if it was possible for someone to assist me with an error I receive when using the random function:

AttributeError: 'builtin_function_or_method' object has no attribute 'choice'

I have already imported the entire random library and ensured there are no other files called random.py in the same directory as where the file is saved.

Code:

from random import *

# Generates the random card

rank = ["Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
suit = ["Hearts", "Clubs", "Diamonds", "Spades"]

card_1 = ("The card is the %s of %s") % (random.choice(rank), random.choice(suit))
vaultah
  • 44,105
  • 12
  • 114
  • 143

3 Answers3

2

If you import all names from random into the global namespace via from random import *, random will refer to random.random,

In [4]: from random import *

In [5]: random
Out[5]: <function Random.random>

which doesn't have the choice attribute. Use choice or import random.

Try to avoid starred imports. See Why is “import *” bad? for more information.

Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143
1

Your problem is right here:

from random import *

Based on how you are importing, you cannot call choice like this:

random.choice 

Your reference for the random module is already within random when you do this:

from random import *

So your call based on your import should be:

choice

If you wanted to use random.choice, you would need to import like this:

import random

It would however be a much better practice to not use from <module> import *

Look at @vaultah answer for further explanation on why using import * is bad

idjaw
  • 25,487
  • 7
  • 64
  • 83
1

You just need to use choice instead of random.choice, As we didn't import random module causes this issue.

>>> card_1 = ("The card is the %s of %s") % (choice(rank), choice(suit))

>>> card_1 = ("The card is the %s of %s") % (random.choice(rank), random.choice(suit))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
Shankar
  • 846
  • 8
  • 24