1. Package Management in Python
pip (Python Package Installer)
Tool dasar untuk manajemen package Python.
Fitur Utama pip:
- Instalasi package dari PyPI
- Uninstall package
- Update package
- List package terinstal
- Generate requirements.txt
# Basic Commands
pip install package_name # Install single package
pip install package_name==1.0.0 # Install specific version
pip uninstall package_name # Remove package
pip list # List installed packages
pip freeze > requirements.txt # Save package list
pip install -r requirements.txt # Install from requirements
pip show package_name # Package info
pip search package_name # Search PyPI
# Upgrade pip itself
python -m pip install --upgrade pip
# Install multiple packages
pip install requests pandas numpy
# Upgrade package
pip install --upgrade package_name
# Install in user directory
pip install --user package_name
Best Practices pip:
# 1. Create virtual environment first
python -m venv myenv
# 2. Activate virtual environment
# Windows:
myenv\Scripts\activate
# Unix/macOS:
source myenv/bin/activate
# 3. Install packages
pip install -r requirements.txt
# 4. Save dependencies
pip freeze > requirements.txt
2. Essential Built-in Modules
1. OS Module
Modul untuk berinteraksi dengan sistem operasi.
import os
# Current Working Directory
current = os.getcwd()
os.chdir('/path/to/dir')
# Path Operations
path = os.path.join('folder', 'subfolder', 'file.txt')
abs_path = os.path.abspath('file.txt')
dirname = os.path.dirname('/path/to/file.txt')
filename = os.path.basename('/path/to/file.txt')
# Directory Operations
os.mkdir('new_directory') # Single directory
os.makedirs('path/to/directory') # Recursive
os.rmdir('directory') # Remove empty directory
os.removedirs('path/to/dir') # Remove recursive
# File Operations
os.rename('old.txt', 'new.txt')
os.remove('file.txt')
exists = os.path.exists('file.txt')
# List Directory
files = os.listdir('.')
for root, dirs, files in os.walk('.'):
print(root, dirs, files)
# Environment Variables
os.environ['MY_VAR'] = 'value'
value = os.environ.get('MY_VAR')
os.getenv('MY_VAR', 'default')
# System Commands
os.system('echo Hello') # Execute system command
# Path Manipulation
os.path.split('/path/to/file.txt')
os.path.splitext('file.txt')
2. Datetime Module
Modul untuk menangani tanggal dan waktu.
from datetime import datetime, date, time, timedelta
# Current Date and Time
now = datetime.now() # Current local date and time
today = date.today() # Current local date
utc_now = datetime.utcnow() # Current UTC date and time
# Creating Date/Time
specific_date = date(2024, 2, 1)
specific_time = time(13, 30, 0)
specific_datetime = datetime(2024, 2, 1, 13, 30, 0)
# Formatting
formatted = now.strftime('%Y-%m-%d %H:%M:%S')
date_string = '2024-02-01 13:30:00'
parsed = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
# Date Operations
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
yesterday = today - timedelta(days=1)
# Time Differences
diff = datetime(2024, 12, 31) - datetime.now()
days_until = diff.days
seconds_until = diff.seconds
# Date Properties
print(now.year, now.month, now.day)
print(now.hour, now.minute, now.second)
3. Math Module
Modul untuk operasi matematika.
import math
# Basic Math
print(math.sqrt(16)) # Square root: 4.0
print(math.pow(2, 3)) # Power: 8.0
print(math.fabs(-5)) # Absolute value: 5.0
print(math.factorial(5)) # Factorial: 120
# Rounding
print(math.floor(3.7)) # Floor: 3
print(math.ceil(3.2)) # Ceil: 4
print(math.trunc(3.7)) # Truncate: 3
# Constants
print(math.pi) # Pi: 3.141592653589793
print(math.e) # e: 2.718281828459045
print(math.tau) # Tau: 6.283185307179586
# Trigonometry (radians)
print(math.sin(math.pi/2)) # Sine: 1.0
print(math.cos(math.pi)) # Cosine: -1.0
print(math.tan(math.pi/4)) # Tangent: 1.0
# Converting degrees/radians
print(math.degrees(math.pi)) # Radians to degrees: 180.0
print(math.radians(180)) # Degrees to radians: 3.141592653589793
Let me continue with the remaining essential modules:
4. Random Module
Modul untuk menghasilkan angka dan pilihan acak.
import random
# Random Numbers
random_float = random.random() # Float 0.0 <= x < 1.0
random_int = random.randint(1, 10) # Integer between 1 and 10
random_range = random.randrange(0, 10, 2) # Even numbers 0-8
# Floating point randomization
random_uniform = random.uniform(1.0, 10.0) # Float between 1.0 and 10.0
# Sequence Operations
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list) # Shuffle list in-place
random_choice = random.choice(my_list) # Pick random item
random_samples = random.sample(my_list, 3) # Pick 3 unique items
# Probability
weighted_choice = random.choices(['red', 'blue', 'green'],
weights=[5, 2, 3], k=2) # Weighted random choices
# Seed for reproducibility
random.seed(42) # Set seed for reproducible results
5. JSON Module
Modul untuk bekerja dengan format data JSON.
import json
# Python Object to JSON String
data = {
'name': 'John',
'age': 30,
'city': 'New York',
'hobbies': ['reading', 'music'],
'active': True,
'height': 1.75
}
# Serialization (Python to JSON)
json_string = json.dumps(data, indent=4, sort_keys=True)
print(json_string)
# Deserialization (JSON to Python)
python_dict = json.loads(json_string)
print(python_dict['name'])
# Working with Files
# Writing JSON to file
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
# Reading JSON from file
with open('data.json', 'r') as f:
loaded_data = json.load(f)
# Custom encoding/decoding
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def person_encoder(obj):
if isinstance(obj, Person):
return {'name': obj.name, 'age': obj.age}
raise TypeError(f'Object {obj} is not JSON serializable')
person = Person('John', 30)
json_string = json.dumps(person, default=person_encoder)
6. Sys Module
Modul untuk berinteraksi dengan Python interpreter.
import sys
# System Information
print(sys.version) # Python version
print(sys.platform) # Operating system platform
print(sys.executable) # Python executable location
# Python Path
print(sys.path) # Module search path
sys.path.append('/path/to/module') # Add path
# Standard Input/Output
sys.stdout.write('Hello\n') # Write to stdout
sys.stderr.write('Error\n') # Write to stderr
input_line = sys.stdin.readline() # Read from stdin
# Command Line Arguments
print(sys.argv) # List of command line arguments
script_name = sys.argv[0] # Script name
arguments = sys.argv[1:] # Arguments
# Exit Program
sys.exit(0) # Exit with status 0 (success)
sys.exit(1) # Exit with status 1 (error)
# Memory Information
print(sys.getsizeof([1, 2, 3])) # Size of object in bytes
# Modules
print(sys.modules) # Dictionary of loaded modules
7. Collections Module
Modul yang menyediakan alternatif untuk tipe data built-in.
from collections import Counter, defaultdict, namedtuple, deque, OrderedDict
# Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
color_count = Counter(colors)
print(color_count) # Counter({'blue': 3, 'red': 2, 'green': 1})
print(color_count.most_common(2)) # [('blue', 3), ('red', 2)]
# defaultdict
d = defaultdict(list) # Default value is empty list
d['a'].append(1) # No KeyError if key doesn't exist
d['b'].append(2)
print(d) # defaultdict(<class 'list'>, {'a': [1], 'b': [2]})
# namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p.x, p.y) # 11 22
print(p[0], p[1]) # 11 22
# deque (double-ended queue)
d = deque(['a', 'b', 'c'])
d.append('d') # Add to right
d.appendleft('e') # Add to left
print(d) # deque(['e', 'a', 'b', 'c', 'd'])
# OrderedDict (ordered dictionary)
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])