loading...

Charming the Python: Modules

vickilanger profile image Vicki (she/her) Updated on ・1 min read

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.


Modules

Modules are chunks of code, saved in a file, that are made to help you do things easier. A module could be a file containing a single variable, or function, a massive codebase.

A module is a python script, saved as filename.py

Creating

Here's an example of something you may want to use later.

# fullname.py
def generate_full_name(firstname, lastname):
      space = ' '
      fullname = firstname + space + lastname
      return fullname
Enter fullscreen mode Exit fullscreen mode

Importing a Module

In order to use a module that you've created, you'll need to import it in a different file. Once imported, it can be used anywhere in your new file.

The syntax for using an imported module is modulename.funtion_name(parameters)

import fullname

print(fullname.generate_full_name('Vicki', 'Langer'))
Enter fullscreen mode Exit fullscreen mode

Importing Functions from a Module

You can use multiple functions from a module, by importing each one.

To do this, you'll follow the below syntax. Each script may have many functions. If you don't want to import allllllll of them, this is a great option.

from modulename import feed_pet, generate_full_name
Enter fullscreen mode Exit fullscreen mode

Built-In Modules

There are modules that are already included with Python. Here are some common ones.

math

import math
print(math.pi)

>>> 3.141592653589793
Enter fullscreen mode Exit fullscreen mode

random

random gives pseudo-random outputs

from random import random, randint
print(random())   # returns something bewtween 0 and 0.9999
print(randint(3, 72)) # returns a number between two arguments
Enter fullscreen mode Exit fullscreen mode

Series based on

Discussion

pic
Editor guide