def imp():
import random
def choi(a):
random.choice(a)
if __name__ == '__main__':
imp()
choi(['a', 'b'])
Output:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
NameError: name 'random' is not defined
wjandrea
34k10 gold badges69 silver badges107 bronze badges
2 Answers 2
You have imported the package in a function so it is only imported locally for the scope of the function. So, when the function is exited, the imported package is no longer available.
Generally, the packages are imported at the top of the file:
import random
def choi(a):
choice = random.choice(a)
print(choice) # use print to see the output
return choice # use return to return the output
if __name__ == '__main__':
out = choi(['a', 'b']) # capture the return value in out
answered Mar 8, 2021 at 5:31
Krishna Chaurasia
9,6646 gold badges27 silver badges44 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Azizbek Sheripbayev
Thank you, I'm new here. I knew that, but I'm going to get Student badge. So, I should post question with at least 10 points. Can you please help me by upvoting this question?
Krishna Chaurasia
also, make sure to either
print/return the value else it is not much usefulKrishna Chaurasia
Don't worry about upvotes. As far as I know, there is no criteria for asking questions and if you ask good questions, people will upvote it by themselves.
I think because when you call imp(), you can import random lib, but after close imp() the main funciton can "remember" import this lib, so error.
Comments
lang-py
importat the beginning of the script or insidechoifunction