Home > front end >  I am facing an Attribute Error while using random() function in Python
I am facing an Attribute Error while using random() function in Python

Time:08-07

I am trying to use random library in Python. The code is as follows:

import random
#print random integer
rand_int = random.randint(1,10)
print(rand_int)

However VSCode is showing the error:

devjyotisinha@Devjyotis-MacBook-Air Udemy % python3 -u "/Users/devjyotisinha/Desktop/Python/Udemy/random.py"
Traceback (most recent call last):
  File "/Users/devjyotisinha/Desktop/Python/Udemy/random.py", line 1, in <module>
    import random
  File "/Users/devjyotisinha/Desktop/Python/Udemy/random.py", line 3, in <module>
    rand_int = random.randint(1,10)
AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import)

The code is working fine on online editors such as replit.com but VSCode is showing an error. What does the attribute error mean as I learnt that randint is an attribute of random?

CodePudding user response:

Can you please try changing your file name, I can see it's random.py This might be the issue.

CodePudding user response:

This is probably because you have a local file named random.py. Run the following code if you want to check in the future:

import random

print(random.__file__)

Follow the following:

# ⛔️ result if shadowed by local file
# /home/borislav/Desktop/bobbyhadz_python/random.py

# ✅ result if pulling in correct module
# /usr/lib/python3.10/random.py

Your file directory has random.py in it, DO NOT do this. Rename it! When you have a file with this, the VScode will immediately go to the file and try finding the randint method in it, which of course you don't have in your file.

  • Related