Python bases in more than 128 words[Partie 5]

This article follows on from the first four parts that can be viewed here:

I am discussing the basics of the Python language to learn it quickly. In France these bases are taught in high school at the second SNT, first and senior NSI classes. They are also part of the knowledge program for CAPES NSI.

Consolidation of functions:

A module is a file that contains a set of functions that you want to include in your app.

Example file

def greetings (name):
  print ("Hi" - name)

Using the module in a Python program:

import mymodule

monmodule.salutations ("Sebastian")

Module renaming:

import monmodule as mod

mod.salutations ("Daniel")

The dir function is an integrated function to list all function names (or variable names) in a module.

import platform

res - dir (platform)

It is possible to import only parts of a module, using the keyword from.

from mymodule import greetings

greetings ("John")


Packages allow a hierarchical structuring of the module's name space.

Packages help prevent collisions between module names.

Creating a package is quite simple because it uses the directory structure of the operating system.

If we consider a directory called pkg that contains two modules, and

The content of the modules is:

def test():
    print ('test module 1')

Toto class:
def test2():
    print ('test module 2')

Joe class:

With this structure, if the pkg directory is in a location where it can be found (i.e. one of the directories contained in sys.path).

It is possible to refer to the two modules (pkg.module1, pkg.module2) and import them:

import pkg.module1, pkg.module2

x - pkg.module2.Joe()

Random value:

random import

(random.random)) #Retourne a decimal number randomly between 0 and 1
(random.randint(10,20)) #Retourne a whole in the defined gap
member '["Seb","Jean","Louise"]
(random.choice) #Retourne an item on the list randomly