Lesson 15
Modules & Imports
Organize code across files
1What Are Modules?✨
Modules are files containing Python code that can define functions, classes, and variables. They help organize code, making it reusable and easier to manage.
2Creating a Module🎯
To create a module, simply save your code in a file with a .py extension. For example, create a file named `math_operations.py` with the following code:
def add(a, b):
return a + bdef subtract(a, b):
return a - b3Using Modules💡
You can use your module in another Python file by importing it. Here's how to use the `math_operations` module:
import math_operationsresult_add = math_operations.add(5, 3)
result_subtract = math_operations.subtract(10, 4)print(result_add) # Outputs: 8
print(result_subtract) # Outputs: 64Benefits of Using Modules🚀
- ✓ Promotes code reusability
- ✓ Keeps your code organized
- ✓ Makes collaboration easier
- ✓ Helps manage larger projects
5Importing Specific Functions🔍
Sometimes, you only need specific functions from a module. You can import them like this:
from math_operations import addresult = add(7, 2)
print(result) # Outputs: 96Creating Your Own Project⭐
Now that you understand modules and imports, try creating a small project! Organize your code into multiple modules, like one for math operations and another for string manipulations. This will help you practice and see the power of modular programming!
🎯 Practice Challenges
Master Modules & Imports by completing all 3 difficulty levels
Modules & Imports - Easy Challenge
Start with the basics. Perfect for beginners!
Modules & Imports - Medium Challenge
Get more challenging. Build your confidence!
Modules & Imports - Hard Challenge
Master this concept. Prove your skills!
🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →
Ready to Master Modules & Imports? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 14: Lambda FunctionsWrite compact anonymous functions
- Next lesson →Lesson 16: File Handling BasicsRead and write text files
- Grade 8 courseJavaScript Basics - Web ProgrammingJavaScript coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 7 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.