Modules
Modules
1. math module:
1. math module:
python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0
print(math.factorial(5)) # Output: 120
print(math.pow(2, 3)) # Output: 8.0
print(math.pi) # Output: 3.141592653589793
2. os module:
python
Copy code
import os
print(os.getcwd()) # Output: Current directory path
os.mkdir('test_dir') # Creates a directory named 'test_dir'
print(os.listdir()) # Output: ['test_dir', 'some_file.txt']
os.remove('some_file.txt') # Removes 'some_file.txt'
3. sys module:
4. datetime module:
python
Copy code
from datetime import datetime, timedelta
now = datetime.now()
print(now) # Output: Current date and time
print(now.strftime('%Y-%m-%d')) # Output: Date in the format YYYY-MM-DD
future_date = now + timedelta(days=5)
print(future_date) # Output: Current date + 5 days
5. random module:
python
Copy code
import random
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
print(random.random()) # Output: Random float between 0 and 1
print(random.choice(['apple', 'banana', 'cherry'])) # Randomly picks an
item
list_ = [1, 2, 3, 4]
random.shuffle(list_)
print(list_) # Output: Shuffled list
6. json module:
python
Copy code
import json
data = {"name": "John", "age": 30}
json_str = json.dumps(data) # Convert to JSON string
print(json_str) # Output: '{"name": "John", "age": 30}'
python_obj = json.loads(json_str)
print(python_obj['name']) # Output: John
7. re module:
• re.match(pattern, string): Checks if the pattern matches the start of the string.
• re.search(pattern, string): Searches for the first occurrence of the pattern in the
string.
• re.findall(pattern, string): Returns a list of all matches of the pattern in the
string.
• re.sub(pattern, repl, string): Replaces occurrences of the pattern with repl.
python
Copy code
import re
pattern = r'\d+'
text = 'There are 123 apples'
match = re.findall(pattern, text) # Finds all digits
print(match) # Output: ['123']
text = re.sub(r'apples', 'bananas', text)
print(text) # Output: 'There are 123 bananas'
8. collections module:
python
Copy code
from collections import Counter, defaultdict, namedtuple
# Counter
counts = Counter(['a', 'b', 'a', 'c', 'b', 'b'])
print(counts) # Output: Counter({'b': 3, 'a': 2, 'c': 1})
# Defaultdict
d = defaultdict(int)
d['apple'] += 1
print(d['apple']) # Output: 1
# Namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # Output: 10 20
9. itertools module:
python
Copy code
import itertools
perms = itertools.permutations([1, 2, 3])
print(list(perms)) # Output: All permutations of [1, 2, 3]
python
Copy code
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4]) # Sums all elements
print(result) # Output: 10
These examples show how you can use the built-in functions of various standard Python
modules effectively.
4o
You said:
some more
ChatGPT said:
ChatGPT
Here are some additional built-in Python modules along with their commonly used functions
and examples:
• time.time(): Returns the current time in seconds since the epoch (1970-01-01).
• time.sleep(seconds): Pauses execution for the given number of seconds.
• time.ctime(): Converts a time expressed in seconds to a readable string format.
• time.strftime(format): Returns a string representing the date and time in a
specific format.
python
Copy code
import time
print(time.time()) # Output: Current time in seconds since the
epoch
time.sleep(2) # Pauses execution for 2 seconds
print(time.ctime()) # Output: Current date and time in a readable
format
print(time.strftime('%Y-%m-%d %H:%M:%S')) # Output: Custom formatted date-
time
python
Copy code
import calendar
print(calendar.month(2024, 9)) # Output: September 2024 calendar
print(calendar.isleap(2024)) # Output: True (2024 is a leap year)
print(calendar.weekday(2024, 9, 24)) # Output: Day of the week (0=Monday,
6=Sunday)
print(calendar.calendar(2024)) # Output: Full calendar of 2024
python
Copy code
import subprocess
subprocess.run(['echo', 'Hello, World!']) # Output: Hello, World!
python
Copy code
import hashlib
hash_object = hashlib.md5(b'Hello')
print(hash_object.hexdigest()) # Output: MD5 hash of the string 'Hello'
hash_object = hashlib.sha256(b'Hello')
print(hash_object.hexdigest()) # Output: SHA-256 hash of the string
'Hello'
python
Copy code
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config.get('Settings', 'theme')) # Output: The value of the 'theme'
in 'Settings' section
python
Copy code
import csv
# Reading from a CSV file
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row) # Output: Each row as a list
# Writing to a CSV file
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', '30', 'New York'])
Provides a flexible framework for emitting log messages from Python programs.
python
Copy code
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.error('This is an error message')
python
Copy code
import shutil
shutil.copy('source.txt', 'destination.txt') # Copy file
shutil.move('source.txt', 'new_location.txt') # Move file
shutil.rmtree('test_dir') # Delete directory
python
Copy code
import zipfile
# Create a ZIP file
with zipfile.ZipFile('my_files.zip', 'w') as z:
z.write('file1.txt')
z.write('file2.txt')
python
Copy code
import glob
print(glob.glob('*.txt')) # Output: List of all text files in the current
directory
python
Copy code
import uuid
unique_id = uuid.uuid4()
print(unique_id) # Output: A random UUID like 123e4567-e89b-12d3-a456-
426614174000
Provides support for enumerations, which are a set of symbolic names bound to unique,
constant values.
python
Copy code
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
python
Copy code
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8080)) # Bind to localhost on port 8080
s.listen(1) # Listen for incoming connections
These additional modules expand the functionality of Python and make it highly versatile for
tasks such as file handling, networking, logging, and much more.
python
Copy code
import math
2. os module:
python
Copy code
import os
3. sys module:
python
Copy code
import sys
4. datetime module:
python
Copy code
now = datetime.now()
5. random module:
python
Copy code
import random
list_ = [1, 2, 3, 4]
random.shuffle(list_)
6. json module:
python
Copy code
import json
python_obj = json.loads(json_str)
7. re module:
• re.match(pattern, string): Checks if the pattern matches the start of the string.
• re.search(pattern, string): Searches for the first occurrence of the pattern in the string.
• re.findall(pattern, string): Returns a list of all matches of the pattern in the string.
• re.sub(pattern, repl, string): Replaces occurrences of the pattern with repl.
python
Copy code
import re
pattern = r'\d+'
8. collections module:
python
Copy code
# Counter
# Defaultdict
d = defaultdict(int)
d['apple'] += 1
print(d['apple']) # Output: 1
# Namedtuple
p = Point(10, 20)
print(p.x, p.y) # Output: 10 20
9. itertools module:
python
Copy code
import itertools
python
Copy code
print(result) # Output: 10
These examples show how you can use the built-in functions of various standard Python modules
effectively.
Here’s a breakdown of the built-in functions provided by some of the commonly used
Python modules with examples:
1. math module:
Functions for mathematical operations.
python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0
print(math.factorial(5)) # Output: 120
print(math.pow(2, 3)) # Output: 8.0
print(math.pi) # Output: 3.141592653589793
2. os module:
python
Copy code
import os
print(os.getcwd()) # Output: Current directory path
os.mkdir('test_dir') # Creates a directory named 'test_dir'
print(os.listdir()) # Output: ['test_dir', 'some_file.txt']
os.remove('some_file.txt') # Removes 'some_file.txt'
3. sys module:
python
Copy code
import sys
print(sys.version) # Output: Python version
print(sys.argv) # Output: Command-line arguments list
sys.exit() # Exits the interpreter
4. datetime module:
python
Copy code
from datetime import datetime, timedelta
now = datetime.now()
print(now) # Output: Current date and time
print(now.strftime('%Y-%m-%d')) # Output: Date in the format YYYY-MM-DD
future_date = now + timedelta(days=5)
print(future_date) # Output: Current date + 5 days
5. random module:
python
Copy code
import random
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
print(random.random()) # Output: Random float between 0 and 1
print(random.choice(['apple', 'banana', 'cherry'])) # Randomly picks an
item
list_ = [1, 2, 3, 4]
random.shuffle(list_)
print(list_) # Output: Shuffled list
6. json module:
python
Copy code
import json
data = {"name": "John", "age": 30}
json_str = json.dumps(data) # Convert to JSON string
print(json_str) # Output: '{"name": "John", "age": 30}'
python_obj = json.loads(json_str)
print(python_obj['name']) # Output: John
7. re module:
Functions for working with regular expressions.
• re.match(pattern, string): Checks if the pattern matches the start of the string.
• re.search(pattern, string): Searches for the first occurrence of the pattern in the
string.
• re.findall(pattern, string): Returns a list of all matches of the pattern in the
string.
• re.sub(pattern, repl, string): Replaces occurrences of the pattern with repl.
python
Copy code
import re
pattern = r'\d+'
text = 'There are 123 apples'
match = re.findall(pattern, text) # Finds all digits
print(match) # Output: ['123']
text = re.sub(r'apples', 'bananas', text)
print(text) # Output: 'There are 123 bananas'
8. collections module:
python
Copy code
from collections import Counter, defaultdict, namedtuple
# Counter
counts = Counter(['a', 'b', 'a', 'c', 'b', 'b'])
print(counts) # Output: Counter({'b': 3, 'a': 2, 'c': 1})
# Defaultdict
d = defaultdict(int)
d['apple'] += 1
print(d['apple']) # Output: 1
# Namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # Output: 10 20
9. itertools module:
python
Copy code
import itertools
perms = itertools.permutations([1, 2, 3])
print(list(perms)) # Output: All permutations of [1, 2, 3]
python
Copy code
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4]) # Sums all elements
print(result) # Output: 10
These examples show how you can use the built-in functions of various standard Python
modules effectively.
4o
You said:
some more
ChatGPT said:
ChatGPT
Here are some additional built-in Python modules along with their commonly used functions
and examples:
• time.time(): Returns the current time in seconds since the epoch (1970-01-01).
• time.sleep(seconds): Pauses execution for the given number of seconds.
• time.ctime(): Converts a time expressed in seconds to a readable string format.
• time.strftime(format): Returns a string representing the date and time in a
specific format.
python
Copy code
import time
print(time.time()) # Output: Current time in seconds since the
epoch
time.sleep(2) # Pauses execution for 2 seconds
print(time.ctime()) # Output: Current date and time in a readable
format
print(time.strftime('%Y-%m-%d %H:%M:%S')) # Output: Custom formatted date-
time
python
Copy code
import calendar
print(calendar.month(2024, 9)) # Output: September 2024 calendar
print(calendar.isleap(2024)) # Output: True (2024 is a leap year)
print(calendar.weekday(2024, 9, 24)) # Output: Day of the week (0=Monday,
6=Sunday)
print(calendar.calendar(2024)) # Output: Full calendar of 2024
python
Copy code
import subprocess
subprocess.run(['echo', 'Hello, World!']) # Output: Hello, World!
hash_object = hashlib.sha256(b'Hello')
print(hash_object.hexdigest()) # Output: SHA-256 hash of the string
'Hello'
python
Copy code
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config.get('Settings', 'theme')) # Output: The value of the 'theme'
in 'Settings' section
python
Copy code
import csv
# Reading from a CSV file
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row) # Output: Each row as a list
Provides a flexible framework for emitting log messages from Python programs.
python
Copy code
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.error('This is an error message')
python
Copy code
import shutil
shutil.copy('source.txt', 'destination.txt') # Copy file
shutil.move('source.txt', 'new_location.txt') # Move file
shutil.rmtree('test_dir') # Delete directory
python
Copy code
import zipfile
# Create a ZIP file
with zipfile.ZipFile('my_files.zip', 'w') as z:
z.write('file1.txt')
z.write('file2.txt')
python
Copy code
import uuid
unique_id = uuid.uuid4()
print(unique_id) # Output: A random UUID like 123e4567-e89b-12d3-a456-
426614174000
Provides support for enumerations, which are a set of symbolic names bound to unique,
constant values.
python
Copy code
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
python
Copy code
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 8080)) # Bind to localhost on port 8080
s.listen(1) # Listen for incoming connections
These additional modules expand the functionality of Python and make it highly versatile for
tasks such as file handling, networking, logging, and much more.
• time.time(): Returns the current time in seconds since the epoch (1970-01-01).
• time.strftime(format): Returns a string representing the date and time in a specific format.
python
Copy code
import time
• calendar.calendar(year): Returns a string with the calendar for the entire year.
python
Copy code
import calendar
python
Copy code
import subprocess
python
Copy code
import hashlib
hash_object = hashlib.md5(b'Hello')
hash_object = hashlib.sha256(b'Hello')
python
Copy code
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
python
Copy code
import csv
reader = csv.reader(csvfile)
writer = csv.writer(csvfile)
Provides a flexible framework for emitting log messages from Python programs.
python
Copy code
import logging
logging.basicConfig(level=logging.DEBUG)
python
Copy code
import shutil
python
Copy code
import zipfile
z.write('file1.txt')
z.write('file2.txt')
z.extractall('extracted')
python
Copy code
import glob
python
Copy code
import uuid
unique_id = uuid.uuid4()
Provides support for enumerations, which are a set of symbolic names bound to unique, constant
values.
python
Copy code
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
python
Copy code
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
These additional modules expand the functionality of Python and make it highly versatile for tasks
such as file handling, networking, logging, and much more.