Spex3
    

Python Standard Library Modules & __name__ Variable 📚🐍


    

    

Python's standard library provides many built-in modules that help with mathematical operations, randomness, file handling, date/time manipulation, and system interactions.

1️⃣ Standard Library Modules
Here are some commonly used built-in modules:

🔢 math Module (Mathematical Operations)
The math module provides advanced mathematical functions.

✅ Example Usage

import math

print(math.sqrt(25)) # 5.0 (Square root)
print(math.pow(2, 3)) # 8.0 (Power)
print(math.pi) # 3.141592653589793 (Pi constant)
print(math.sin(math.radians(30))) # 0.5 (Sine of 30 degrees)
🎲 random Module (Random Number Generation)
The random module is used for generating random numbers.

✅ Example Usage

import random

print(random.randint(1, 10)) # Random number between 1 and 10
print(random.choice(["apple", "banana", "cherry"])) # Random choice from list
print(random.shuffle([1, 2, 3, 4, 5])) # Shuffle a list
print(random.uniform(1.5, 5.5)) # Random float between 1.5 and 5.5
📅 datetime Module (Date and Time Handling)
The datetime module helps with handling date and time.

✅ Example Usage

import datetime

now = datetime.datetime.now()
print(now) # Current date and time

print(now.strftime("%Y-%m-%d %H:%M:%S")) # Format date as string

# Create a specific date
my_birthday = datetime.datetime(2000, 5, 20)
print(my_birthday.strftime("%A, %d %B %Y")) # Saturday, 20 May 2000
💻 os Module (Operating System Interactions)
The os module allows interaction with the operating system.

✅ Example Usage

import os

print(os.name) # Name of the operating system (e.g., 'posix' for Linux/Mac, 'nt' for Windows)

print(os.getcwd()) # Get current working directory

# List all files in a directory
print(os.listdir("."))

# Create and remove a directory
os.mkdir("test_folder") # Create a directory
os.rmdir("test_folder") # Remove a directory
2️⃣ __name__ Variable in Python
The __name__ variable helps differentiate whether a script is being run directly or imported as a module.

🔹 How __name__ Works?
✅ Example: script.py (Main File)

print("This is script.py")
print("Value of __name__:", __name__)
📌 If run directly:

$ python script.py
🔹 Output:

markdown

This is script.py
Value of __name__: __main__
✅ When a script runs directly, __name__ is "__main__".

🔹 __name__ in Modules
Let's say we have a module named my_module.py:


# my_module.py
def greet():
print("Hello from my_module!")

print("my_module is being run")
print("Value of __name__:", __name__)
Now, import my_module in another script:


import my_module
📌 Output when imported:

my_module is being run
Value of __name__: my_module

✅ When imported, __name__ is the module name (not __main__).

🔹 Using if __name__ == "__main__"

To prevent unwanted execution when importing a module, use:


# my_module.py
def greet():
print("Hello from my_module!")

if __name__ == "__main__":
print("Running my_module directly!")
greet()

✅ What happens?

🔹 If run directly:


$ python my_module.py
Output:


Running my_module directly!
Hello from my_module!

🔹 If imported in another script:


import my_module
Output: Nothing! (greet() is not called)

✅ The if __name__ == "__main__" block only runs when the script is executed directly.

3️⃣ Summary

Module Usage Example

math Advanced math operations math.sqrt(16), math.pi

random Random number generation random.randint(1,10), random.choice()

datetime Date and time handling datetime.datetime.now()

os System interactions os.getcwd(), os.listdir(".")

__name__ Identifies script execution mode if __name__ == "__main__"


    Date: 2025-03-24 00:00:00.000000