
Python Modules and Imports Explained Simply
Modules help organize code by splitting it into separate files. They make programs easier to manage and allow code reuse. What is a module? A module is a Python file ( .py ) containing functions, variables, or classes. For example, create a file named math_utils.py : def add ( a , b ): return a + b def multiply ( a , b ): return a * b pi = 3.14159 This file is now a module. Importing modules Use import to load a module. import math_utils result = math_utils . add ( 5 , 3 ) print ( result ) # 8 print ( math_utils . pi ) # 3.14159 Import specific items: from math_utils import add , pi print ( add ( 10 , 20 )) # 30 print ( pi ) # 3.14159 Import everything (not recommended for large modules): from math_utils import * print ( multiply ( 4 , 5 )) # 20 Using built-in modules Python has many built-in modules. Random module: import random print ( random . randint ( 1 , 10 )) # Random number between 1 and 10 print ( random . choice ([ " apple " , " banana " , " cherry " ])) # Random item Math mo
Continue reading on Dev.to
Opens in a new tab



