Python Cheat Sheet

Python adalah bahasa pemrograman tingkat tinggi yang banyak digunakan dalam aplikasi web, pengembangan perangkat lunak, ilmu data, dan machine learning (ML). Developer menggunakan Python karena efisien dan mudah dipelajari serta dapat dijalankan di beberapa platform.

Berikut ini merupakan cheat sheet penggunaan Python yang bisa Anda pelajari untuk mendalami Python.

Working With Files

Reading a File

Untuk membaca seluruh konten file.

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

Penjelasan:

  • with open('example.txt', 'r') as file: baris ini membuka file yang bernama ’example.txt’ dalam mode baca (‘r’) dan mengasosiasikannya dengan variabel file. Penggunaan with memastikan bahwa file akan ditutup secara otomatis setelah blok kode ini selesai dijalankan.
  • content = file.read() baris ini membaca seluruh isi file dan menyimpannya dalam variabel content.
  • print(content) baris ini mencetak isi dari variabel content ke konsol.

Writing to a File

Untuk menulis teks ke file, mode ini menimpa konten yang telah ada.

with open('example.txt', 'w') as file:
    file.write('Hello, Python!')

Appending to a File

Untuk menambahkan teks ke akhir baris file yang telah ada.

with open('example.txt', 'a') as file:
    file.write('\nAppend this line.')

Reading Lines into a List

Untuk membaca file baris demi baris pada daftar.

with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)

Iterating Over Each Line in a File

Untuk memproses setiap baris dalam file.

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

Checking If a File Exists

Untuk memeriksa apakah file ada sebelum melakukan operasi file.

import os
if os.path.exists('example.txt'):
    print('File exists.')
else:
    print('File does not exist.')

Penjelasan:

  • import os Untuk mengimpor modul os yang menyediakan fungsi untuk berinteraksi dengan sistem opearasi.
  • if os.path.exists('example.txt'): untuk memeriksa apakah file example.txt ada di direktori saat ini.

Writing Lists to a File

Untuk menulis setiap elemen daftar ke baris baru dalam file.

lines = ['First line', 'Second line', 'Third line']
with open('example.txt', 'w') as file:
    for line in lines:
        file.write(f'{line}\n')

Penjelasan:

  • lines = ['First line', 'Second line', 'Third line'] Baris ini mendefinisikan sebuah list.
  • for line in lines: Ini adalah loop for yang mengiterasi melalui setiap baris yang ada dalam list lines.
  • file.write(f'{line}\n') Setiap baris dari list lines akan ditulis ke dalam file dengan ekspresi f-string untuk memastukan nilai variabel line.

Using With Blocks for Multiple Files

Untuk melakukan operasi dengan banyak file secara bersamaan menggunakan with blocks.

with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
    content = source.read()
    destination.write(content)

Deleting a File

Untuk menghapus file dengan aman jika ada.

import os
if os.path.exists('example.txt'):
    os.remove('example.txt')
    print('File deleted.')
else:
    print('File does not exist.')

Reading and Writing Binary Files

Untuk membaca dan menulis file dalam mode biner. (gambar, video, dll)

# Reading a binary file
with open('image.jpg', 'rb') as file:
    content = file.read()
# Writing to a binary file
with open('copy.jpg', 'wb') as file:
    file.write(content)

Working With Simple HTTP APIs

Basic GET Request

Untuk mengambil data dari API endpoint menggunakan GET request.

import requests
response = requests.get('https://api.example.com/data')
data = response.json()  # Assuming the response is JSON
print(data)

GET Request with Query Parameters

Untuk mengirim request GET dengan parameter kueri.

import requests
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://api.example.com/search', params=params)
data = response.json()
print(data)

Handling HTTP Errors

Untuk menangani kemungkinan kesalahan HTTP dengan baik.

import requests
response = requests.get('https://api.example.com/data')
try:
    response.raise_for_status()  # Raises an HTTPError if the status is 4xx, 5xx
    data = response.json()
    print(data)
except requests.exceptions.HTTPError as err:
    print(f'HTTP Error: {err}')

Penjelasan:

  • response = requests.get('https://api.example.com/data'): Kode ini mengirimkan permintaan HTTP GET ke URL yang telah ditentukan. Lalu hasilnya akan disimpan ke variabel response
  • try:: Ini memulai blok try, yang akan mengeksekusi kode di dalamnya.
  • response.raise_for_status(): Memeriksa status respon HTTP. Jika status adalah 4xx atau 5xx maka akan memunculkan HTTPError.
  • except requests.exceptions.HTTPError as err:: Jika ada kesalahan HTTP, blok except akan menangkapnya dan mencetak pesan kesalahan.

Setting Timeout for Requests

Untuk mengatur batas waktu (timeout) saat menjalankan request GET.

import requests
try:
    response = requests.get('https://api.example.com/data', timeout=5)  # Timeout in seconds
    data = response.json()
    print(data)
except requests.exceptions.Timeout:
    print('The request timed out')

Using Headers in Requests

Untuk menyertakan header saat menjalankan request (misalnya authorization)

import requests
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.get('https://api.example.com/protected', headers=headers)
data = response.json()
print(data)

POST Request with JSON Payload

Untuk mengirim data ke API endpoint menggunakan request POST dengan payload JSON.

import requests
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('https://api.example.com/submit', json=payload, headers=headers)
print(response.json())

Handling Response Encoding

Untuk menangani response encoding dengan benar.

import requests
response = requests.get('https://api.example.com/data')
response.encoding = 'utf-8'  # Set encoding to match the expected response format
data = response.text
print(data)

Using Sessions with Requests

Untuk membuat session object agar dapat membuat beberapa permintaan ke host yang sama dan dapat meningkatkan kinerja.

import requests
with requests.Session() as session:
    session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})
    response = session.get('https://api.example.com/data')
    print(response.json())

Handling Redirects

Untuk menangani dan menonaktifkan redirect dalam permintaan.

import requests
response = requests.get('https://api.example.com/data', allow_redirects=False)
print(response.status_code)

Streaming Large Responses

Untuk memproses file berukuran besar dalam beberapa bagian, daripada memuat semuanya ke dalam memory.

import requests
url = "https://api.example.com/large-data.txt"
with requests.get(url, stream=True) as r:
  with open('data.txt','wb') as f:
    for chunk in r.iter_content(chunk_size=10 * 1024):
      f.write(chunk)

Working With Lists

Creating a List

Untuk menambahkan elemen ke dalam list.

# A list of mystical elements
elements = ['Earth', 'Air', 'Fire', 'Water']

Appending to a List

Menambahkan elemen baru ke akhir daftar.

elements.append('Aether')

Inserting into a List

Untuk menyisipkan elemen pada posisi tertentu dalam list.

# Insert 'Spirit' at index 1
elements.insert(1, 'Spirit')

Removing from a List

Menghapus elemen berdasarkan nilai dari list.

elements.remove('Earth')  # Removes the first occurrence of 'Earth'

Popping an Element from a List

Untuk menghapus dan mengembalikan elemen pada indeks tertentu. (defaultnya adalah last item)

last_element = elements.pop()

Finding the Index of an Element

Untuk menemukan indeks dalam list element

index_of_air = elements.index('Air')

List Slicing

Untuk membagi daftar dalam sub list.

# Get elements from index 1 to 3
sub_elements = elements[1:4]

List Comprehension

Untuk membuat daftar baru dengan menerapkan ekspresi ke setiap elemen yang sudah ada.

# Create a new list with lengths of each element
lengths = [len(element) for element in elements]

Sorting a List

Untuk mengurutkan list.

elements.sort()

Reversing a List

Membalikkan list elemen.

elements.reverse()

Working With Dictionaries

Creating a Dictionary

Membuat kamus baru.

# A tome of elements and their symbols
elements = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li'}

Adding or Updating Entries

Untuk menambah entri baru atau mengubah entri yang sudah ada.

elements['Carbon'] = 'C'  # Adds 'Carbon' or updates its value to 'C'

Removing an Entry

Untuk membuang entri dari kamus.

del elements['Lithium']  # Removes the key 'Lithium' and its value

Checking for Key Existence

Untuk memeriksa suatu kunci apakah ada di kamus.

if 'Helium' in elements:
    print('Helium is present')

Iterating Over Keys

Untuk menampilkan seluruh kunci di kamus.

for element in elements:
    print(element)  # Prints each key

Iterating Over Values

Untuk menampilkan seluruh value dari kunci di kamus.

for symbol in elements.values():
    print(symbol)  # Prints each value

Iterating Over Items

Untuk menampilkan kunci dan value bersamaan.

for element, symbol in elements.items():
    print(f'{element}: {symbol}')

Dictionary Comprehension

Untuk membuat kamus baru yang dapat berubah.

# Squares of numbers from 0 to 4
squares = {x: x**2 for x in range(5)}

Merging Dictionaries

Menggabungkan dua kamus atau lebih.

alchemists = {'Paracelsus': 'Mercury'}
philosophers = {'Plato': 'Aether'}
merged = {**alchemists, **philosophers}  # Python 3.5+

Getting a Value with Default

Untuk mengambil nilai secara aman, jika tidak ada akan diberikan nilai default.

element = elements.get('Neon', 'Unknown')  # Returns 'Unknown' if 'Neon' is not found

Working With The Operating System

Navigating File Paths

Untuk membuat path file yang sesuai dengan sistem operasi lalu mengembalikan direktori dan file dari path tersebut.

import os
# Craft a path compatible with the underlying OS
path = os.path.join('mystic', 'forest', 'artifact.txt')
# Retrieve the tome's directory
directory = os.path.dirname(path)
# Unveil the artifact's name
artifact_name = os.path.basename(path)

Listing Directory Contents

Untuk melihat isi dari folder.

import os
contents = os.listdir('enchanted_grove')
print(contents)

Creating Directories

Untuk membuat direktori baru.

import os
# create a single directory
os.mkdir('alchemy_lab')
# create a hierarchy of directories
os.makedirs('alchemy_lab/potions/elixirs')

Removing Files and Directories

Untuk menghapus file dan direktori.

import os
# remove a file
os.remove('unnecessary_scroll.txt')
# remove an empty directory
os.rmdir('abandoned_hut')
# remove a directory and its contents
import shutil
shutil.rmtree('cursed_cavern')

Executing Shell Commands

Untuk menjalankan perintah shell dengan modul subprocess

import subprocess
# Invoke the 'echo' incantation
result = subprocess.run(['echo', 'Revealing the arcane'], capture_output=True, text=True)
print(result.stdout)

Penjelasan:

  • import subprocess: mengimpor modul subprocess yang memungkinkan untuk menjalankan proses baru, menghubungkan ke stream input/output/error, dan memperoleh output kode.
  • result = subprocess.run(['echo', 'Revealing the arcane'], capture_output=True, text=True): Menjalankan perintah echo dalam shell. capture_output=True menangkap output dari perintah yang dijalankan, sedangkan text=True mengarahkan output sebagai teks (dalam bentuk string) daripada byte.
  • print(result.stdout): mencetak hasil output ke console.

Working with Environment Variables

Untuk membaca dan menambahkan environment

import os
# Read the 'PATH' variable
path = os.environ.get('PATH')
# Create a new environment variable
os.environ['MAGIC'] = 'Arcane'

import subprocess
check = subprocess.run("echo $MAGIC", shell=True)
print(check.stdout)

Changing the Current Working Directory

Untuk masuk atau mengubah direktori kerja saat ini.

import os
# Traverse to the 'arcane_library' directory
os.chdir('arcane_library')
check = os.listdir()
print(check)

Path Existence and Type

Untuk mengecek keberadaan dan membedakan file dan direktori.

import os
# Check if a path exists
exists = os.path.exists('mysterious_ruins')
# Ascertain if the path is a directory
is_directory = os.path.isdir('mysterious_ruins')
# Determine if the path is a file
is_file = os.path.isfile('ancient_manuscript.txt')

print(exists, is_directory, is_file)

Working with Temporary Files

Membuat temporary file dan direktori.

import tempfile
# Create a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False)
print(temp_file.name)
# Erect a temporary directory
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)

Getting System Information

Untuk mendapatkan informasi sistem host.

import os
import platform
# Discover the operating system
os_name = os.name  # 'posix', 'nt', 'java'
# Unearth detailed system information
system_info = platform.system()  # 'Linux', 'Windows', 'Darwin'

Working With CLI — STDIN, STDOUT, STDERR

Reading User Input

Untuk mendapatkan input dari STDIN

user_input = input("username: ")
print(f"username anda: {user_input}")

Printing to STDOUT

Menampilkan message atau STDOUT ke console terminal.

print('contoh pesan')

Formatted Printing

Menampilkan message berdasarkan variabel yang telah dibuat.

name = "Merlin"
age = 300
print(f"{name}, of {age} years, speaks of forgotten lore.")

Reading Lines from STDIN

Menampilkan STDIN per baris ke console terminal.

import sys
for line in sys.stdin:
    print(f"Echo from the void: {line.strip()}")

Writing to STDERR

Untuk mengirim message ke STDERR.

import sys
sys.stderr.write("Beware! The path is fraught with peril.\n")

Redirecting STDOUT

Untuk redirect STDOUT.

import sys
with open('mystic_log.txt', 'w') as f:
    sys.stdout = f  # Redirect STDOUT to a file
    print("This message is inscribed within the mystic_log.txt.")

Redirecting STDERR

Untuk redirect STDERR.

import sys
with open('warnings.txt', 'w') as f:
    sys.stderr = f  # Redirect STDERR
    print("This warning is sealed within warnings.txt.", file=sys.stderr)

Prompting for Passwords

Untuk prompt password.

import getpass
secret_spell = getpass.getpass("Masukan password Anda: ")
print(f"password yang diketik: {secret_spell}")

Command Line Arguments

Menguraikan argumen pada baris perintah.

import sys
# The script's name is the first argument, followed by those passed by the invoker
script, first_arg, second_arg = sys.argv
print(f"Invoked with the sacred tokens: {first_arg} and {second_arg}")
$ python script_name.py test 123
Invoked with the sacred tokens: test and 123

Using Argparse for Complex CLI Interactions

Membuat instruksi pada baris perintah.

import argparse
parser = argparse.ArgumentParser(description="Invoke the ancient scripts.")
parser.add_argument('spell', help="The spell to cast")
parser.add_argument('--power', type=int, help="The power level of the spell")
args = parser.parse_args()
print(f"Casting {args.spell} with power {args.power}")
$ python script_name.py --power 100 spell
Casting spell with power 100

Working With Async IO (Asyncrounous Programming)

Defining an Asynchronous Function

Untuk mendeklarasikan fungsi async.

import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(2)
    print("Data retrieved.")

async def main():
    await fetch_data()

asyncio.run(main())

Awaiting Multiple Coroutines

Untuk menjalankan beberapa fungsi async.

import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(2)
    print("Data retrieved.")

async def run_shell(cmd):
    await asyncio.create_subprocess_shell(cmd)

async def main():
    await fetch_data()
    task1 = run_shell('date')
    task2 = run_shell('date')
    await asyncio.gather(task1, task2)

asyncio.run(main())

Creating Tasks

Untuk menjalankan beberapa fungsi async.

import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(2)
    print("Data retrieved.")

async def run_shell(cmd):
    await asyncio.create_subprocess_shell(cmd)

async def main():
    await fetch_data()
    task1 = run_shell('time mysql web1 -pweb1 -e "source /home/user/web2.sql"')
    task2 = run_shell('time mysql web1_1 -pweb1 -e "source /home/user/web2.sql"')
    await task1
    await task2

asyncio.run(main())

Asynchronous Iteration

Untuk simulasi pengambilan item dengan fungsi async.

import asyncio

async def fetch_item(item):
    await asyncio.sleep(1)
    print(f"Fetched {item}")
async def main():
    items = ['potion', 'scroll', 'wand']
    for item in items:
        await fetch_item(item)
asyncio.run(main())

Handling Exceptions in Asynchronous Code

Untuk menangkap dan mengelola error dengan baik menggunakan fungsi async.

import asyncio

async def risky_spell():
    await asyncio.sleep(1)
    raise ValueError("instruksi kurang jelas!")
async def main():
    try:
        await risky_spell()
        print("hore hore berhasil")
    except ValueError as e:
        print(f"Caught an error: {e}")
asyncio.run(main())

Kode diatas akan mengeksekusi risky_spell() dan karena ada tambahan raise ValueError, ini akan mensimulasikan kode yang dijalankan mengalami error dan akan menampilkan pesan error.

$ python script_name.py
Caught an error: instruksi kurang jelas!

Jika kode raise dicomment atau dimatikan maka eksekusi risky_spell() akan dianggap berhasil.

$ python script_name.py
hore hore berhasil

Asynchronous Generators

Untuk membuat generator async.

import asyncio

async def fetch_items():
    items = ['crystal', 'amulet', 'dagger']
    for item in items:
        await asyncio.sleep(1)
        yield item
async def main():
    async for item in fetch_items():
        print(f"Found {item}")
asyncio.run(main())

Using Semaphores

Untuk membatasi jumlah tugas secara bersamaan.

import asyncio

async def task(semaphore, name):
    async with semaphore:
        print(f"{name} is working")
        await asyncio.sleep(1)
        print(f"{name} is done")

async def main():
    semaphore = asyncio.Semaphore(2)  # Hanya dua tugas yang diperbolehkan berjalan secara bersamaan
    await asyncio.gather(
        task(semaphore, "Task 1"),
        task(semaphore, "Task 2"),
        task(semaphore, "Task 3"),
        task(semaphore, "Task 4")
    )

asyncio.run(main())

Event Loops

Untuk membuat loop async.

import asyncio

async def perform_spell():
    print("Casting spell...")
    await asyncio.sleep(1)
    print("Spell cast.")
loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(perform_spell())
finally:
    loop.close()

Referensi: