Why is the syntax different for importing the random module?

According to the datetime exercise to use the datetime module, we would need to specify the object and the module name:

from <module_name> import <object_name>
ex: from datetime import datetime

However, for the random module exercise, the syntax is different:

import random
  1. Is this because the random module doesn’t have multiple objects to use like the datetime module?
  2. Does the import random syntax equate to import <module_name> and does this mean that it’s importing the entire random module?
  3. For datetime, is it only importing the datetime object from the datetime module?
1 Like

Hi @sarrininja, welcome to the forums! Good question. :+1:

Not at all, there are many objects exposed by the random module. :slight_smile:

Got it in one.

If you want to import an entire module into your Python program, you can use the syntax import <module_name> and every object from that module will be available in your code.

So, let’s say we did import random because we wanted to get a random number between 1 and 10. Importing this way, we would not be able to do num = randint(1,10). We would, instead, have to do num = random.randint(1,10). (This is because import <module> results in Python becoming aware of the module, but not any of the module objects.) We need to actively tell Python which module contains the function we want to use.

If, instead, we do from random import randint we are telling Python that we’re only interested in that one module object - the function randint. Python imports only the object(s) we ask for, and adds them directly - so importing this way lets us use num = randint(1,10).

There is more about modules on the Python Docs if you were curious. :slight_smile:

1 Like

@thepitycoder, thank you for answering my questions. It helped clarify any confusions i may have had. :+1:

1 Like