Understanding the significance of the name variable in Python scripts
Explanation
- The
__name__variable is a built-in variable in Python that indicates the name of the module. - When a Python script is run directly,
__name__is set to'__main__', allowing for specific code execution. - This feature is commonly used to differentiate between running a script as the main program versus importing it as a module in another script.
- It enables the inclusion of test code or script execution logic that should only run when the script is executed directly.
- This practice promotes modularity and reusability of code by preventing certain code from running during imports.
python
# 1. What do you mean by __name__ == '__main__'What is a module?
Any file with an extention of .py is called a module in python.
Whenever we execute a program it's module name is main and this name is stored in name variable
Understanding the behavior of the name attribute in Python modules
Explanation
- The
displayfunction is defined to print the string 'hello' when called. - The function
display()is invoked, resulting in 'hello' being printed to the console. - The
print(__name__)statement outputs the name of the current module; if run as the main program, it will display__main__. - The
print(display.__name__)statement shows the name of the functiondisplay, which is 'display', regardless of the module context. - This code snippet illustrates how the
__name__attribute helps differentiate between the main module and imported modules in Python.
python
def display():
print('hello')
display()
print(__name__) # It is basically for the same module
print(display.__name__) # It prints the module name is imported from another module like module.__name__ output is module instead of __main__. __main__ is for the current module which is yours than other modules developed by someone.Output
text
hello
__main__
displayImporting a module
- But what is the need to import a module?
- How to import a module
This code demonstrates module importation and the use of the special variable name in Python.
Explanation
- The code imports a module named
testand calls thehellofunction from that module, passing the string 'madhu' as an argument. - The
print(__name__)statement outputs the name of the current module, which will be'__main__'if the script is run directly. - The
print(test.__name__)statement outputs the name of the imported module, which will be'test'. - This snippet illustrates how Python distinguishes between the main program and imported modules using the
__name__variable.
python
import test
test.hello('madhu')
print(__name__)
print(test.__name__)Output
text
hello madhu
__main__
testImporting custom and built-in modules to execute functions in Python
Explanation
- The code imports the built-in
mathmodule for mathematical operations and a user-defined module namedtest. - It calls the
hellofunction from thetestmodule, passing the string 'madhu' as an argument. - The
printfunction outputs the result ofmath.floor(4.3), which rounds down the float to the nearest integer, resulting in 4.
python
# import multiple module -> user defined + builtin
import math
import test
test.hello('madhu')
print(math.floor(4.3))Output
text
hello madhu
4Variations of import statement
Importing essential libraries for mathematical operations and random number generation in Python
Explanation
- The
mathlibrary provides access to mathematical functions and constants, such as trigonometric functions and logarithms. - The
randomlibrary allows for generating random numbers and performing random selections, useful in simulations and games. - Both libraries are standard in Python, meaning they come pre-installed and do not require additional installation.
- Importing these libraries enables the use of their functionalities throughout the script, enhancing its capabilities.
python
# Normal
import math
import randomImporting multiple modules for mathematical operations, random number generation, and testing functionalities
Explanation
- The code imports three different modules:
math,random, andtest. - The
mathmodule provides access to mathematical functions like trigonometry, logarithms, and constants. - The
randommodule is used for generating random numbers and performing random selections. - The
testmodule is likely a custom or third-party module intended for testing purposes, though its specific functionality is not defined in the snippet. - This approach of importing multiple modules in a single line can help streamline code but may reduce readability if overused.
python
# clubbing together
import math, random, testThis code demonstrates the use of specific mathematical functions from a module and a custom import.
Explanation
- The
factorialfunction from themathmodule calculates the factorial of a given number, in this case,5, which results in120. - The
floorfunction from themathmodule rounds down a floating-point number to the nearest integer, here it processes4.8but does not print the result. - The
hellofunction is imported from a custom module namedtest, but it is not used in this snippet. - The code showcases selective importing, which can help reduce memory usage and improve performance by only bringing in necessary functions.
python
# importing specific names from module
from math import factorial, floor
from test import hello
print(factorial(5))
floor(4.8)Output
text
120
4This code snippet demonstrates how to import and rename Python modules for mathematical operations and data manipulation.
Explanation
- The code imports the
math,numpy,pandas, andmatplotlib.pyplotlibraries, renamingmathtomfor convenience. - The
math.factorial(5)function call computes the factorial of the number 5, which equals 120. - Using aliases for modules helps to shorten the code and improve readability, especially when frequently calling functions from these libraries.
numpyis typically used for numerical operations,pandasfor data manipulation, andmatplotlib.pyplotfor plotting, making this import setup versatile for data analysis tasks.
python
# renaming modules
import math as m
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
m.factorial(5)Output
text
120This code calculates the factorial of the number 5 using a mathematical function.
Explanation
- The code imports the
factorialfunction from themathmodule and renames it toffor convenience. - The
f(5)function call computes the factorial of 5, which is the product of all positive integers up to 5 (i.e., 5 x 4 x 3 x 2 x 1). - The result of
f(5)is 120, as it returns the factorial value. - This snippet demonstrates how to use built-in mathematical functions in Python for efficient calculations.
python
from math import factorial as f
f(5)Output
text
120Order of execution of a module
This code snippet retrieves and prints the Python module search paths from the system environment.
Explanation
- The
sysmodule is imported to access system-specific parameters and functions. - The
sys.pathlist contains the directories that Python searches for modules when importing. - A
forloop iterates through each path insys.path. - The
print(p)statement outputs each directory path to the console. - This can be useful for debugging import issues or understanding the module search order.
python
import sys
for p in sys.path:
print(p)Output
text
C:\Program Files\JetBrains\PyCharm 2025.2.2\plugins\python-ce\helpers\jupyter_debug
C:\Program Files\JetBrains\PyCharm 2025.2.2\plugins\python-ce\helpers\pydev
C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.3312.0_x64__qbz5n2kfra8p0\python313.zip
C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.3312.0_x64__qbz5n2kfra8p0\DLLs
C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.3312.0_x64__qbz5n2kfra8p0\Lib
C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.3312.0_x64__qbz5n2kfra8p0
C:\Users\madhu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages
C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.13_3.13.3312.0_x64__qbz5n2kfra8p0\Lib\site-packagesWhat are packages in Python
A package in python is a directory containing similar sub packages and modules.
- A particular directory is treated as package if it has
__init__.pyfile in it. - The
__init__.pyfile may be empty or contain some initialization code related to the package
What are 3rd party packages?
- The python community creates packages and make it available for other programmers
- PyPI -> Python Package Index
- You can upload your own package
- You can also install packages from PyPI and install using pip
- pip is a package manager utility
- it is automatically installed with python
