0
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
asked Mar 8, 2021 at 5:27
3
  • Either use import at the beginning of the script or inside choi function Commented Mar 8, 2021 at 5:29
  • Is there any reason to why you are trying to import a module in a function? Commented Mar 8, 2021 at 5:29
  • Yes, you can import a module in a function, but it won't affect the global namespace, only the local namespace of the function. Commented Mar 8, 2021 at 6:29

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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?
also, make sure to either print/return the value else it is not much useful
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.
0

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.

answered Mar 8, 2021 at 5:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.