Why do I have to put 'import random' first? Magic 8 Ball Project

Hey,

In Beginner’s Python 3, Lesson 2, Control Flows, Project: Magic 8 Ball

Why do I have to put


import random

Before I type any other good? e.g. the print functions?

What is the purpose of this?

Hi there,

The reason why you import modules is because you’re able to call functions that are not built into that Python module. For example, consider the random module. It has several methods such as randint(), choice(), shuffle() etc. In order to use these methods you must import the random module into your file:

import random

Then you can use it’s methods:

import random

n = random.randint(1, 10)

You can also import specific methods from modules that you need like so:

from random import choice

n = choice([1, 2, 3, 4, 5])

So again, you import modules into your file to gain access to its code. Does that answer your question?

2 Likes

Hi there,

This is very very helpful and insightful - thanks!

However it doesn’t quite answer my question - my main question is, why does it have to come before the string variables?

Thank you so much!

I apologize for not answering your question. According to the Python documentation ,

It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names, if placed at the top level of a module (outside any functions or classes), are added to the module’s global namespace.

Additionally, Python is a scripting language, meaning it is interpreted not compiled, and on execution runs from “top to bottom, left to right” (similar to a human reading a page). Therefore, any third-party module must be imported before it can be used or interpreted by Python. For example, consider the following code.

n = random.randint(1, 10)

As Python interprets this, when it encounters the name random it will cause a NameError because Python does not know what the name random is. Therefore the module must be import first before it can be used:

import random

n = random.randint(1, 10)

Now as Python interprets this line of code, it now knows what random is, and will execute correctly. Does that answer your question? If not, please feel free to ask again!

Best regards,

1 Like

Thanks for your reply and thank you for your time! That is very much appreciated. :blush:

1 Like