The ABCs of Python: “from”, “import” and rolling the dice

Here are two more keywords in Python. We’ll take them in reverse alphabetical order because our explanations should make more sense that way:

import

The keyword import is one of the very best friends of the lazy (some would say “productive”) programmer. Using import, you can bring pre-made modules into your program. Let’s say, for example, that you want to be able to inject some randomness into your code (although that sounds bad, it can be fantastically useful) but you don’t especially want to spend time writing up unique functions for achieving that. So, you write the following:

import random

Now, you can use any of the functions that are part of that module. You can, for example, use the randint and the randrange functions.  Maybe you want to randomly select one number from 2 to 50 and you want to select another from the same range but only if it’s an even number (that is, the outcome could be 2 or 4 or 6, etc.). After you’ve imported random, You can write:

print (random.randint(2,50))
print (random.randrange(2, 51, 2))

from

Now let’s say you don’t need to use multiple functions from the random module. You just need the one called randint. You can do it this way:

from random import randint
print (randint(1,6))

This will give you a random number between 1 and 6, as if you were rolling a virtual dice.

So, when should you use the from statement to import just one function from a module? Good question. Unfortunately, there’s no clear answer. It’s a bit of a roll of the dice since each has its advantages and disadvantages. If you want to know more, I recommend the ‘import module’ or ‘from module import’ discussion in Stackoverflow.

Featured image: Diacritica - Own work; Wikimedia Commons