What a module is and how to import it
A module is a Python file ( .py ) that contains functions, variables and classes ready to be used in other programs. Instead of…
Discover how a Python program is organized into modules. You will learn how to import code with import, from and as, how to use everyday modules such as math and random, how to explore what a module offers with dir and help, and how to create your own reusable modules with the if __name__ == "__main__" guard. Reinforce what you learn with practical exercises.
A module is a Python file ( .py ) that contains functions, variables and classes ready to be used in other programs. Instead of…
The math module gathers the mathematical functions that are not included by default in the language: roots, rounding…
The random module generates random numbers and choices: it is the basis of games, raffles and simulations. It is imported with…
Any .py file you write is a module, and you can import it from another file just like math or random . This way you can split a…
When a project grows, a single file is not enough, and neither is a folder full of loose modules. A package is a folder that…
To finish with modules, three pieces of the import mechanism that explain most strange errors.
Real programs use third-party packages, and each project may need different versions of the same package. Installing everything…
Create a Python program that rounds a decimal number in three different ways with the math module.
Create a Python program that calculates the greatest common divisor (GCD) and the least common multiple (LCM) of two numbers.
Create a Python program that calculates in how many ways k elements can be chosen from n , with and without regard to order.
Create a Python program that simulates dice rolls with the random module.
Create a Python program organized as a reusable module: the functions are defined at the top and the main program only runs when…
The import statement needs the module name written in the code. When the name is only known while the program runs, you use…
Python stores the modules that have already been imported in the sys.modules dictionary: if you import one again, it is not run…
A file can be run as a program or imported as a module. The special name __name__ is "__main__" in the first case and the module…
When a module imports another one, the second must be loaded first. If two modules import each other, there is a circular import…