The import statement is one of the most important features of Python’s module system. It allows a program to access functions, classes, variables, and other reusable code stored in another module.
When a Python project contains multiple modules, the import statement connects those modules together.
The most common forms you will use are:
import module
from module import object
import module as alias
from module import object as alias
Understanding these four patterns is enough to handle most basic module-import requirements in a Data Analytics-focused Python course.
The simplest form is:
import math
After importing the module, we can access its functionality using the module name followed by a dot.
import math
result = math.sqrt(64)
print(result)
Output:
8.0
Here, math is the module and sqrt() is a function provided by that module.
The general pattern is:
module_name.object_name
For example:
math.sqrt()
math.pi
math.pow()
This style is very clear because the module name remains visible.
Suppose a program uses several libraries containing functions with similar names.
Using the module name makes the source of the function obvious.
math.sqrt(100)
Immediately tells us that sqrt() comes from the math module.
This can improve readability, especially in larger programs.
For example:
import math
import statistics
numbers = [10, 20, 30, 40]
average = statistics.mean(numbers)
root = math.sqrt(100)
print(average)
print(root)
It is easy to identify which module provides each function.
A Python program can import multiple modules.
import math
import random
import statistics
We can then use them:
numbers = [10, 20, 30, 40]
average = statistics.mean(numbers)
root = math.sqrt(144)
random_number = random.randint(1, 100)
print(average)
print(root)
print(random_number)
This is common in real Python programs.
For example, a Data Analytics script might need:
import csv
import json
import statistics
import datetime
Each module can handle a different responsibility.
Python also allows us to import only a particular function, class, or variable from a module.
The syntax is:
from module import object
For example:
from math import sqrt
result = sqrt(81)
print(result)
Output:
9.0
Notice that we no longer need to write:
math.sqrt()
We can directly use:
sqrt()
This can make code shorter when only a few objects from a module are required.
You can import multiple objects from the same module.
from math import sqrt, pi
print(sqrt(25))
print(pi)
Another example:
from statistics import mean, median
numbers = [
10,
20,
30,
40,
50
]
print(mean(numbers))
print(median(numbers))
This approach is useful when your program needs only a small number of specific functions.
Both approaches are valid.
Using:
import math
math.sqrt(25)
keeps the module name visible.
Using:
from math import sqrt
sqrt(25)
allows direct access to the imported function.
A useful way to remember the difference is:
import math
↓
Use math.sqrt()
from math import sqrt
↓
Use sqrt()
For beginners, import module is often easier to understand because the relationship between the module and its functionality remains visible.
Python allows us to assign a shorter name to an imported module.
The syntax is:
import module as alias
For example:
import math as m
print(
m.sqrt(100)
)
Here, m is an alias for math.
Instead of:
math.sqrt(100)
we can write:
m.sqrt(100)
Aliases are particularly common in Data Analytics.
As you progress into Data Analytics, you will frequently see standard conventions such as:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
These aliases are widely recognized in Python Data Analytics code.
For example:
import pandas as pd
data = pd.DataFrame({
"Name": [
"Rahul",
"Priya"
],
"Marks": [
85,
92
]
})
print(data)
Here, pd is simply an alias for the Pandas module.
You will study Pandas and NumPy in your separate courses, so the important concept here is how module aliases work.
You can also give an imported function or object an alias.
For example:
from math import sqrt as square_root
print(
square_root(49)
)
Now square_root() is the local name for the imported sqrt() function.
This can be useful when a name is unclear, too long, or conflicts with another name in your program.
Let’s now apply the same concepts to a module that you create yourself.
Create a file named:
analytics_tools.py
Inside it, write:
def total(values):
return sum(values)
def average(values):
if len(values) == 0:
return 0
return sum(values) / len(values)
def maximum(values):
return max(values)
Now create another file in the same project directory:
main.py
Inside main.py:
import analytics_tools
sales = [
10000,
15000,
20000,
12000
]
print(
analytics_tools.total(sales)
)
print(
analytics_tools.average(sales)
)
print(
analytics_tools.maximum(sales)
)
This is a simple example of building your own reusable analytics module.
Instead of importing the complete module, you can import individual functions.
from analytics_tools import average
sales = [
10000,
15000,
20000
]
result = average(sales)
print(result)
You can also import several functions:
from analytics_tools import total, average
sales = [
10000,
15000,
20000
]
print(total(sales))
print(average(sales))
This demonstrates that the same import principles apply to both Python’s built-in modules and your own modules.
You can also create an alias for a custom module.
import analytics_tools as at
sales = [
10000,
15000,
20000
]
print(
at.average(sales)
)
Here:
analytics_tools
has been shortened to:
at
This is technically valid, although aliases should be used thoughtfully. A meaningful module name is often preferable to an unnecessarily short alias when the code is easier to understand without it.
A module can contain variables as well as functions.
For example:
analytics_config.py
TAX_RATE = 0.18
COMPANY_NAME = "Vista Analytics"
Another program can import them:
from analytics_config import TAX_RATE
print(TAX_RATE)
Or import the module:
import analytics_config
print(
analytics_config.TAX_RATE
)
This demonstrates that modules are not limited to functions.
Modules can also contain classes.
For example:
student.py
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print(
self.name,
self.marks
)
Another program can import the class:
from student import Student
student = Student(
"Rahul",
85
)
student.display()
This is one of the ways Python projects are divided into reusable components.
When Python encounters an import statement, it needs to locate the requested module.
For a simple project, if your custom module and main program are in the same directory, Python can normally find the module.
For example:
project/
│
├── main.py
└── analytics_tools.py
Then:
import analytics_tools
can normally work from main.py.
For larger applications, Python uses its import system and module search path to determine where modules can be found.
You do not need to memorize the complete import system for a basic Data Analytics course. The important practical idea is that Python must be able to locate the module you are trying to import.
If Python cannot locate a module, you may see:
ModuleNotFoundError
For example:
import my_unknown_module
If that module is not available in the current Python environment or import path, Python can raise a ModuleNotFoundError.
This is one of the most common problems beginners encounter while learning imports.
When you see this error, check:
Another common error is:
ImportError
This can occur when Python finds the module but cannot import the requested object in the way specified.
For example:
from math import something_that_does_not_exist
The module exists, but the requested name does not.
This distinction is useful:
ModuleNotFoundError
↓
Python cannot find the requested module
ImportError
↓
Python has an import-related problem with
the requested object or import operation
Python allows:
from math import *
This imports many names from the module into the current namespace.
Although it works, it is generally not recommended for clean, maintainable code.
Consider:
from math import *
print(sqrt(25))
Someone reading this code may not immediately know where sqrt() came from.
Compare:
import math
print(
math.sqrt(25)
)
The second version makes the source of the function obvious.
Therefore, prefer explicit imports such as:
import math
or:
from math import sqrt
when appropriate.
In a professional Python file, imports are normally placed near the top.
For example:
import math
import statistics
from datetime import date
from analytics_tools import average
def process_data(values):
return average(values)
This makes it easy to see which external functionality the program depends on.
It also makes the code easier to read and maintain.
Suppose you are creating a simple sales-analysis program.
You might have a reusable module:
sales_tools.py
containing:
def calculate_total(sales):
return sum(sales)
def calculate_average(sales):
if not sales:
return 0
return sum(sales) / len(sales)
def calculate_highest(sales):
return max(sales)
Your main program can import it:
import sales_tools
sales = [
12000,
18000,
15000,
22000,
17000
]
total = sales_tools.calculate_total(
sales
)
average = sales_tools.calculate_average(
sales
)
highest = sales_tools.calculate_highest(
sales
)
print("Total Sales:", total)
print("Average Sales:", average)
print("Highest Sales:", highest)
This small example demonstrates an important professional habit: keeping reusable business logic separate from the main program.
For basic Python development, these patterns cover most situations:
| Syntax | Use |
|---|---|
import math |
Import a complete module |
from math import sqrt |
Import a specific object |
import pandas as pd |
Import with an alias |
from math import sqrt as root |
Import an object with an alias |
The most important thing is not to memorize every possible import variation. Instead, understand what each form does and choose the approach that keeps your code clear.
import module imports a module and normally uses dot notation to access its objects.from module import object imports a specific object directly.as creates an alias for a module or imported object.ModuleNotFoundError generally indicates that Python cannot locate the requested module.ImportError can occur when an import operation or requested object cannot be imported as specified.from module import * is generally discouraged because it can make code less clear.In the next part, we will learn how to create your own Python modules properly, including reusable functions and variables, module structure, the __name__ variable, and the important if __name__ == "__main__": pattern.
Creating your own Python modules is the next step after learning how the import statement works. A custom module allows you to place reusable functions, variables, classes, and other Python code into a separate file and use that code in other programs.
This becomes especially useful when your Python projects grow beyond a few hundred lines. Instead of keeping every function in one large file, you can divide the project into smaller, meaningful modules.
For example, a Data Analytics project could be organized like this:
project/
│
├── main.py
├── data_loader.py
├── data_validator.py
├── analytics_tools.py
└── report_generator.py
Each module has a clear responsibility, while main.py can coordinate the complete workflow.
Let’s create a simple module called:
calculator.py
Inside this file, write:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError(
"Cannot divide by zero."
)
return a / b
This file is now a reusable Python module.
We can create another file called:
main.py
and import the module:
import calculator
print(
calculator.add(10, 5)
)
print(
calculator.subtract(10, 5)
)
print(
calculator.multiply(10, 5)
)
print(
calculator.divide(10, 5)
)
The important idea is that the functions remain inside calculator.py. The main program simply uses them.
A good custom module should generally contain code that belongs to the same logical area.
For example, a module called:
student_tools.py
could contain functions related to students:
def calculate_percentage(marks, total):
if total == 0:
raise ValueError(
"Total marks cannot be zero."
)
return (
marks / total
) * 100
def is_passed(percentage):
return percentage >= 40
def get_grade(percentage):
if percentage >= 90:
return "A+"
elif percentage >= 80:
return "A"
elif percentage >= 70:
return "B"
elif percentage >= 60:
return "C"
elif percentage >= 40:
return "D"
return "F"
Another program can import these functions whenever student analysis is required.
Let’s create a more relevant example for Data Analytics.
Create:
analytics_tools.py
Add:
def calculate_total(values):
return sum(values)
def calculate_average(values):
if not values:
return 0
return sum(values) / len(values)
def calculate_minimum(values):
if not values:
return None
return min(values)
def calculate_maximum(values):
if not values:
return None
return max(values)
Now create:
main.py
and import the module:
import analytics_tools
sales = [
10000,
15000,
12000,
18000,
22000
]
total = analytics_tools.calculate_total(
sales
)
average = analytics_tools.calculate_average(
sales
)
minimum = analytics_tools.calculate_minimum(
sales
)
maximum = analytics_tools.calculate_maximum(
sales
)
print("Total:", total)
print("Average:", average)
print("Minimum:", minimum)
print("Maximum:", maximum)
This is a simple example of modular Data Analytics programming.
The main program focuses on using the analytical functions, while the actual calculation logic remains inside the reusable module.
You can also import only the functions you need.
from analytics_tools import calculate_average
Then:
sales = [
10000,
15000,
20000
]
average = calculate_average(
sales
)
print(average)
You can import several functions:
from analytics_tools import (
calculate_total,
calculate_average
)
This can be useful when a program needs only a small part of a larger module.
A module can contain variables as well.
For example:
config.py
COMPANY_NAME = "Vista Analytics"
TAX_RATE = 0.18
PASSING_MARKS = 40
Another program can use them:
import config
print(
config.COMPANY_NAME
)
print(
config.TAX_RATE
)
print(
config.PASSING_MARKS
)
This can be useful for constants and configuration values that are shared across different parts of an application.
There is an important behavior to understand when working with custom modules.
Consider a module:
calculator.py
def add(a, b):
return a + b
print(
"Calculator module loaded"
)
Now another file imports it:
import calculator
The statement:
print(
"Calculator module loaded"
)
is executed when the module is imported.
This is important because a Python module can contain both reusable definitions and executable statements.
In professional code, we often want functions and classes to be available when imported without automatically running application-specific code.
This is where the special variable __name__ becomes important.
Python provides a special built-in variable called:
__name__
Its value depends on how the Python file is being used.
When a file is executed directly, Python normally sets:
__name__
to:
"__main__"
For example:
print(__name__)
If you run that file directly, the output will be:
__main__
This tells Python that the file is currently being executed as the main program.
Now imagine two files.
calculator.py:
print(__name__)
And:
main.py:
import calculator
If you run main.py, the value of __name__ inside calculator.py will not be "__main__".
Instead, it will normally contain the module’s name:
calculator
So there is an important difference:
File executed directly
↓
__name__ == "__main__"
File imported as a module
↓
__name__ == module name
This difference allows us to control which code should execute automatically.
One of the most common patterns in Python is:
if __name__ == "__main__":
print(
"Program is running directly."
)
This condition checks whether the current file is being executed directly.
If it is, the code inside the condition runs.
If the file is imported as a module, the condition is false, so the code inside it does not run.
This is extremely useful for creating reusable modules.
Consider:
calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
if __name__ == "__main__":
print(
add(10, 5)
)
print(
subtract(10, 5)
)
If you run:
python calculator.py
the example calculations inside the if block execute.
But if another program uses:
import calculator
the example calculations do not automatically execute.
The functions are simply made available to the importing program.
This is one of the most useful patterns for creating clean reusable Python modules.
Without the if __name__ == "__main__": pattern, code written for testing or demonstration may execute every time the module is imported.
For example:
def calculate_average(values):
return sum(values) / len(values)
print(
calculate_average(
[10, 20, 30]
)
)
If another program imports this module, the print statement will also execute.
That may not be what we want.
Instead:
def calculate_average(values):
return sum(values) / len(values)
if __name__ == "__main__":
print(
calculate_average(
[10, 20, 30]
)
)
Now the test code runs only when the module is executed directly.
This gives us a clean structure:
Reusable functions
↓
Available when imported
Test / demonstration code
↓
Runs only when file is executed directly
This is an important habit when building Python modules.
Let’s build a small but practical module.
Create:
sales_analysis.py
Write:
def total_sales(sales):
return sum(sales)
def average_sales(sales):
if not sales:
return 0
return sum(sales) / len(sales)
def highest_sales(sales):
if not sales:
return None
return max(sales)
def lowest_sales(sales):
if not sales:
return None
return min(sales)
if __name__ == "__main__":
sample_sales = [
10000,
15000,
12000,
18000
]
print(
"Total:",
total_sales(sample_sales)
)
print(
"Average:",
average_sales(sample_sales)
)
print(
"Highest:",
highest_sales(sample_sales)
)
print(
"Lowest:",
lowest_sales(sample_sales)
)
If we execute the file directly, the sample analysis runs.
If we import the module:
import sales_analysis
the functions become available, but the sample analysis does not automatically run.
We can then use:
sales = [
25000,
30000,
28000
]
print(
sales_analysis.average_sales(
sales
)
)
This is a clean and reusable module design.
1. Putting everything into one module
A module should have a meaningful responsibility. If a single file contains unrelated database logic, visualization logic, file handling, and API processing, the benefits of modular organization are reduced.
2. Using unclear module names
Prefer:
sales_analysis.py
over:
x.py
3. Running application code during import
Use:
if __name__ == "__main__":
for code that should execute only when the file is run directly.
4. Creating circular dependencies unnecessarily
For example, if A.py imports B.py while B.py also imports A.py, the project can become difficult to manage. Good module design should minimize unnecessary circular dependencies.
Create a module called:
student_analysis.py
Add these functions:
calculate_total()
calculate_average()
calculate_highest()
calculate_lowest()
Then add:
if __name__ == "__main__":
and test the functions with a sample list of student marks.
Create a second file called:
main.py
Import the module and use the functions with a different set of marks.
Observe the difference between:
python student_analysis.py
and:
python main.py
This exercise will help you understand the difference between direct execution and module import.
.py file.__name__ identifies how a Python file is being used.__name__ is normally "__main__".__name__ normally contains the module name.if __name__ == "__main__": allows test or execution-specific code to run only when the file is executed directly.In the final part of this lesson, we will combine modules and imports into a practical Python project. We will organize multiple modules, connect them through imports, process data, handle errors, and finish with exercises, interview questions, and a complete revision.
अब तक हमने सीखा कि Python module क्या होता है, import statement कैसे काम करता है, custom module कैसे बनाया जाता है, और if __name__ == "__main__": का उपयोग क्यों किया जाता है। अब इन सभी concepts को एक छोटे practical project में combine करते हैं.
इस project में हम एक simple Student Performance Analysis System बनाएंगे। इसका उद्देश्य केवल programming सीखना नहीं है, बल्कि यह समझना है कि एक real Python project को अलग-अलग modules में कैसे organize किया जाता है.
हम project को छोटे और logical components में divide करेंगे:
student_project/
│
├── main.py
├── student_data.py
├── analysis_tools.py
└── report.py
यह structure हमें दिखाता है कि एक ही बड़ी Python file बनाने के बजाय अलग-अलग responsibilities को अलग modules में रखा जा सकता है.
सबसे पहले एक file बनाइए:
student_data.py
इस module में हम student records रखेंगे.
students = [
{
"id": 101,
"name": "Rahul",
"marks": 85
},
{
"id": 102,
"name": "Priya",
"marks": 92
},
{
"id": 103,
"name": "Amit",
"marks": 76
},
{
"id": 104,
"name": "Neha",
"marks": 88
},
{
"id": 105,
"name": "Ravi",
"marks": 69
}
]
अब students variable दूसरे Python files में import किया जा सकता है.
उदाहरण के लिए:
from student_data import students
print(students)
इस तरह data को main program से अलग रखा गया है.
अब दूसरी file बनाइए:
analysis_tools.py
इस module में हम student marks से संबंधित reusable functions बनाएंगे.
def calculate_total(students):
return sum(
student["marks"]
for student in students
)
def calculate_average(students):
if not students:
return 0
total = calculate_total(students)
return total / len(students)
def find_highest(students):
if not students:
return None
return max(
students,
key=lambda student: student["marks"]
)
def find_lowest(students):
if not students:
return None
return min(
students,
key=lambda student: student["marks"]
)
अब हमारा analysis logic एक अलग module में है.
इसका फायदा यह है कि अगर future में हमें किसी दूसरे student dataset पर वही calculations करनी हों, तो हमें functions दोबारा लिखने की आवश्यकता नहीं होगी.
अब हम इन functions को अपने main program में import कर सकते हैं.
एक नई file बनाइए:
main.py
इसमें:
from student_data import students
from analysis_tools import (
calculate_total,
calculate_average,
find_highest,
find_lowest
)
अब functions को directly use किया जा सकता है.
total = calculate_total(students)
average = calculate_average(students)
highest = find_highest(students)
lowest = find_lowest(students)
फिर results display कर सकते हैं:
print("Total Marks:", total)
print("Average Marks:", average)
print(
"Highest:",
highest["name"],
highest["marks"]
)
print(
"Lowest:",
lowest["name"],
lowest["marks"]
)
यहाँ main.py खुद calculations नहीं कर रहा है. वह अलग modules में मौजूद functionality का उपयोग कर रहा है.
हमारे project में अब तीन अलग responsibilities हैं:
student_data.py
↓
Student Data
analysis_tools.py
↓
Analysis Functions
main.py
↓
Combines Everything
यह modular programming का basic idea है.
हम चाहें तो आगे एक fourth module भी बना सकते हैं जो report generation का काम करे.
अब file बनाइए:
report.py
इसमें एक function बनाते हैं:
def display_report(
total,
average,
highest,
lowest
):
print(
"\n--- Student Performance Report ---"
)
print(
"Total Marks:",
total
)
print(
"Average Marks:",
round(average, 2)
)
print(
"Top Student:",
highest["name"]
)
print(
"Highest Marks:",
highest["marks"]
)
print(
"Lowest Student:",
lowest["name"]
)
print(
"Lowest Marks:",
lowest["marks"]
)
अब main.py में इसे import करें:
from report import display_report
और report generate करें:
display_report(
total,
average,
highest,
lowest
)
अब project का flow इस प्रकार हो गया:
student_data.py
↓
Student Data
↓
analysis_tools.py
↓
Calculations
↓
report.py
↓
Report
↓
main.py
अब main.py को थोड़ा बेहतर तरीके से organize करते हैं.
from student_data import students
from analysis_tools import (
calculate_total,
calculate_average,
find_highest,
find_lowest
)
from report import display_report
def run_analysis():
total = calculate_total(students)
average = calculate_average(students)
highest = find_highest(students)
lowest = find_lowest(students)
display_report(
total,
average,
highest,
lowest
)
if __name__ == "__main__":
run_analysis()
अब run_analysis() हमारा main application function है.
और:
if __name__ == "__main__":
यह सुनिश्चित करता है कि analysis तभी automatically execute हो जब main.py को directly run किया जाए.
Imagine that future में हमें student analysis को किसी दूसरे Python application से call करना है.
अगर पूरा program सीधे file में लिखा होता, तो import करने पर unwanted code execute हो सकता था.
लेकिन अब हमारा structure साफ है:
Functions
↓
Reusable
run_analysis()
↓
Application logic
if __name__ == "__main__":
↓
Direct execution
यह pattern Python projects में बहुत commonly दिखाई देता है.
अब हम project को थोड़ा अधिक realistic बनाते हैं.
एक नई file बनाइए:
validation.py
इसमें function बनाएँ:
def validate_student(student):
required_fields = [
"id",
"name",
"marks"
]
for field in required_fields:
if field not in student:
return False
marks = student["marks"]
if not isinstance(
marks,
(int, float)
):
return False
if marks < 0 or marks > 100:
return False
return True
अब main.py में इसे import किया जा सकता है:
from validation import validate_student
और students को validate कर सकते हैं:
valid_students = []
for student in students:
if validate_student(student):
valid_students.append(student)
अब analysis केवल valid records पर किया जा सकता है.
total = calculate_total(valid_students)
average = calculate_average(valid_students)
यह Data Analytics workflow के लिए एक useful pattern है:
Raw Data
↓
Validation
↓
Valid Data
↓
Analysis
↓
Report
अब हमारा पूरा project कुछ इस तरह दिखाई देता है:
student_project/
│
├── main.py
│
├── student_data.py
│
├── validation.py
│
├── analysis_tools.py
│
└── report.py
हर module का अलग purpose है:
| Module | Responsibility |
|---|---|
student_data.py |
Student records |
validation.py |
Data validation |
analysis_tools.py |
Calculations |
report.py |
Report generation |
main.py |
Complete workflow |
यह structure छोटी projects के लिए भी useful है और बड़े applications को समझने के लिए एक अच्छा foundation देता है.
अब सभी modules को connect करके main.py कुछ इस प्रकार हो सकता है:
from student_data import students
from validation import validate_student
from analysis_tools import (
calculate_total,
calculate_average,
find_highest,
find_lowest
)
from report import display_report
def run_analysis():
valid_students = []
for student in students:
if validate_student(student):
valid_students.append(student)
if not valid_students:
print(
"No valid student records found."
)
return
total = calculate_total(
valid_students
)
average = calculate_average(
valid_students
)
highest = find_highest(
valid_students
)
lowest = find_lowest(
valid_students
)
display_report(
total,
average,
highest,
lowest
)
if __name__ == "__main__":
run_analysis()
अब हमारा main program केवल workflow को control कर रहा है. Individual tasks दूसरे modules में मौजूद हैं.
Real-world Data Analytics projects अक्सर एक single calculation तक सीमित नहीं होते.
एक typical workflow में कई operations हो सकते हैं:
इन सभी operations को अलग modules में organize किया जा सकता है.
उदाहरण के लिए:
data_loader.py
cleaning.py
validation.py
analysis.py
visualization.py
reporting.py
यह approach project को अधिक structured बनाती है.
अपने custom modules के लिए simple और descriptive names इस्तेमाल करें.
अच्छे examples:
data_loader.py
student_analysis.py
sales_report.py
file_utils.py
validation.py
ऐसे names से module का purpose तुरंत समझ आता है.
आमतौर पर module names में lowercase और underscores का उपयोग करना readable होता है.
उदाहरण:
student_analysis.py
is easier to read than:
StudentAnalysisModule.py
अब खुद एक छोटा modular Python project बनाइए.
Project का नाम रखें:
sales_project
इसमें चार modules बनाएं:
sales_data.py
sales_analysis.py
sales_report.py
main.py
sales_data.py में sales values रखें.
sales_analysis.py में functions बनाएं:
calculate_total()
calculate_average()
find_highest()
find_lowest()
sales_report.py में report display करने का function बनाएं.
और main.py में सभी modules import करके complete analysis चलाएं.
अंत में:
if __name__ == "__main__":
का उपयोग जरूर करें.
What is a Python module?
A Python module is generally a .py file containing reusable Python code such as functions, classes, variables, and constants.
Why are modules used?
Modules help organize code, reduce duplication, improve maintainability, and encourage code reuse.
What does import do?
The import statement makes functionality from another module available to the current Python program.
What is __name__?
__name__ is a special Python variable whose value depends on whether the file is being executed directly or imported as a module.
What does __name__ == "__main__" mean?
It indicates that the current Python file is being executed directly rather than imported as a module.
Why use if __name__ == "__main__":?
It allows specific code to execute only when the file is run directly and prevents that code from automatically executing when the module is imported.
Can a module contain classes?
Yes. A Python module can contain classes, functions, variables, constants, and other Python code.
What is the difference between a module and a package?
A module is generally a Python file, while a package is a structured collection of related Python modules.
Let’s summarize the complete concept:
Python Module
↓
Reusable Python File
↓
Functions / Classes / Variables
↓
import
↓
Used by Another Program
For a larger project:
Data Module
↓
Validation Module
↓
Analysis Module
↓
Report Module
↓
Main Program
And for direct execution:
if __name__ == "__main__":
run_program()
The key idea is simple: modules allow us to divide a Python application into reusable and logically organized components.
This becomes increasingly important as your programs become larger. In Data Analytics, the same principle can be used to separate data loading, validation, analysis, visualization, and reporting logic.
After completing this lesson, you should be able to:
__name__.if __name__ == "__main__":.Lesson 1 is now complete.