Logo

~/saidqb cat ecosystem/programming-language/python.md

Py

Python

General-purpose backend language

commit by saidqb

Intro

Python: bahasa interpreted, general-purpose, dynamically typed — dirancang readable, indentasi menentukan block (bukan {}).

Get Started

bash
python --version          # cek versi python yang terinstall
python script.py           # jalankan file script
python                       # masuk interactive REPL

Syntax

python
if 5 > 2:
    print("five is greater than two")   # indentasi (bukan {}) menentukan block
x = 5; y = 10                             # multi statement satu baris pakai ;

Output

python
print("Hello")                     # print + newline otomatis
print("a", "b", sep="-")            # custom separator -> "a-b"
print("no newline", end="")          # ganti newline akhir jadi string lain

Comments

python
# komentar satu baris
"""
komentar banyak baris (sebenarnya string literal,
tapi lazim dipakai sebagai comment block / docstring)
"""

Variables

python
x = 5                    # dynamically typed, tidak perlu deklarasi tipe
x, y, z = 1, 2, 3          # multiple assignment
x = y = z = 0               # assign nilai sama ke banyak variabel
global_var = 10               # module-level, bisa diakses lewat `global` di dalam fungsi

Data Types

python
type(5)          # <class 'int'>
type(5.0)         # <class 'float'>
type("x")          # <class 'str'>
type([1, 2])        # <class 'list'>
type((1, 2))          # <class 'tuple'>
type({1, 2})           # <class 'set'>
type({"a": 1})           # <class 'dict'>
type(True)                 # <class 'bool'>
type(None)                  # <class 'NoneType'>

Numbers

python
x = 10          # int
y = 10.5         # float
z = 1 + 2j        # complex
10 / 3             # 3.333... -> true division, selalu float
10 // 3              # 3 -> floor division
10 % 3                # 1 -> modulus
2 ** 3                  # 8 -> pangkat
round(3.567, 2)           # 3.57

Casting

python
int("10")           # str -> int
float("3.14")         # str -> float
str(10)                 # int -> str
int(3.9)                  # float -> int, truncate (bukan round) -> 3
bool(0)                     # 0/""/[]/None -> False, selain itu True

Strings

python
s = "Halo SaidQB"
s[0]                     # index pertama -> 'H'
s[0:4]                     # slicing -> 'Halo'
s[::-1]                      # reverse string
len(s)                          # panjang string
s.upper(); s.lower()              # ubah huruf besar/kecil
s.strip()                           # buang whitespace awal-akhir
s.replace("Halo", "Hai")              # ganti substring
s.split(" ")                            # split -> list
f"Halo {8} tahun"                         # f-string, interpolasi langsung

Booleans

python
bool(1)          # True
bool("")           # False -> string kosong falsy
5 > 3                # True
bool([])               # False -> list kosong falsy

Operators

python
5 + 3; 5 - 3; 5 * 3; 5 / 3; 5 % 3; 5 ** 2; 5 // 2   # aritmatika
5 == 5; 5 != 3; 5 > 3                                  # perbandingan
True and False; True or False; not True                 # logika
5 in [1, 5, 9]                                             # keanggotaan
x is None                                                    # identity check, bukan cuma equality

Lists

python
tags = ["python", "go", "php"]     # ordered, mutable, boleh duplikat
tags.append("rust")                  # tambah di akhir
tags.remove("go")                      # hapus by value
tags[0] = "Python"                       # mutable -> bisa diubah langsung
tags[1:3]                                  # slicing
[x * x for x in range(5)]                    # list comprehension

Tuples

python
point = (10, 20)          # ordered, immutable
x, y = point                # unpacking
point[0]                       # akses via index
point + (30,)                    # bikin tuple baru (concat), tidak mutate yang lama

Sets

python
tags = {"python", "go", "php"}    # unordered, unique, unindexed
tags.add("rust")                    # tambah elemen
tags.remove("go")                     # hapus elemen (error kalau tidak ada)
{1, 2} | {2, 3}                          # union -> {1, 2, 3}
{1, 2} & {2, 3}                            # intersection -> {2}

Dictionaries

python
user = {"name": "SaidQB", "age": 8}    # key-value pairs, ordered (3.7+)
user["name"]                              # akses via key
user["city"] = "Klaten"                     # tambah/update key
user.get("email", "N/A")                      # akses aman, default kalau key tidak ada
user.keys(); user.values(); user.items()        # iterasi key/value/pasangan

If...Else

python
age = 18
if age >= 18:
    print("dewasa")
elif age >= 13:
    print("remaja")
else:
    print("anak-anak")

status = "dewasa" if age >= 18 else "belum"   # ternary satu baris

Match

python
match status:
    case "active":
        print("aktif")
    case "inactive" | "banned":     # multiple pattern
        print("nonaktif")
    case _:
        print("unknown")              # wildcard, wajib exhaustive

While Loops

python
i = 0
while i < 5:
    print(i)
    i += 1
else:
    print("selesai")     # jalan kalau while berakhir normal (tanpa break)

For Loops

python
for tag in ["python", "go", "php"]:
    print(tag)

for i, tag in enumerate(["python", "go"]):   # index + value sekaligus
    print(i, tag)

for i in range(5):
    if i == 3:
        break            # hentikan loop
    if i == 1:
        continue           # lompat ke iterasi berikutnya

Functions

python
def greet(name: str, greeting: str = "Halo") -> str:   # default arg + type hint
    return f"{greeting}, {name}!"

def total(*args, **kwargs):    # *args = positional variadic, **kwargs = keyword variadic
    return sum(args)

square = lambda x: x * x       # anonymous function

Range

python
range(5)              # 0, 1, 2, 3, 4
range(2, 5)              # 2, 3, 4
range(0, 10, 2)             # 0, 2, 4, 6, 8 -> step 2
list(range(5))                # konversi ke list

Arrays

python
from array import array
nums = array('i', [1, 2, 3])   # typed array, lebih hemat memory dari list biasa
nums.append(4)
nums[0]
# catatan: di Python, "array" sehari-hari biasanya cukup pakai `list`

Iterators

python
it = iter([1, 2, 3])     # bikin iterator dari iterable
next(it)                    # 1
next(it)                      # 2

class Counter:                 # custom iterator: wajib __iter__ dan __next__
    def __init__(self, limit):
        self.n, self.limit = 0, limit
    def __iter__(self):
        return self
    def __next__(self):
        if self.n >= self.limit:
            raise StopIteration
        self.n += 1
        return self.n

Modules

python
import math                    # import seluruh module
from math import sqrt            # import satu fungsi
import math as m                   # alias
from math import *                   # import semua (hindari, bisa bentrok nama)
dir(math)                              # list semua nama di dalam module

Dates

python
from datetime import datetime
now = datetime.now()                   # tanggal + waktu sekarang
now.year; now.month; now.day
now.strftime("%Y-%m-%d")                 # format ke string
datetime.strptime("2026-08-23", "%Y-%m-%d")   # parse string -> datetime

Math

python
import math
math.sqrt(16)          # akar kuadrat
math.pow(2, 3)            # pangkat -> float
math.floor(4.9); math.ceil(4.1)
math.pi
max(1, 2, 3); min(1, 2, 3); abs(-5)   # builtin, tidak perlu import math

JSON

python
import json
json.dumps({"name": "SaidQB"})            # dict -> string JSON
json.loads('{"name": "SaidQB"}')            # string JSON -> dict
json.dumps(data, indent=2)                    # pretty print

RegEx

python
import re
re.match(r"^\d+
quot;
, "12345") # cocokkan dari awal string re.search(r"\d+", "abc123") # cari di mana saja dalam string re.findall(r"\d+", "a1 b22 c333") # semua kecocokan -> list re.sub(r"-", "/", "2026-08-23") # ganti semua kecocokan

PIP

bash
pip install requests               # install package
pip install -r requirements.txt      # install dari file
pip freeze > requirements.txt          # export daftar package terinstall
pip uninstall requests                    # hapus package
pip list                                     # daftar package terinstall

Try...Except

python
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except Exception as e:               # catch-all, taruh paling akhir
    print(f"Unknown error: {e}")
else:
    print("tidak ada error")            # jalan kalau try sukses tanpa exception
finally:
    print("selesai")                      # selalu jalan

String Formatting

python
name, age = "SaidQB", 8
f"Halo {name}, umur {age}"              # f-string (paling umum dipakai)
"Halo {}, umur {}".format(name, age)      # .format()
"Halo %s, umur %d" % (name, age)            # %-formatting (gaya lama)
f"{3.14159:.2f}"                               # format angka -> "3.14"

None

python
x = None                 # representasi "tidak ada nilai", bukan 0/""/False
x is None                  # cara yang benar cek None (bukan ==)
def f(): pass                 # fungsi tanpa return -> otomatis return None

User Input

python
name = input("Nama: ")        # selalu return string
age = int(input("Umur: "))       # perlu casting manual kalau butuh angka

VirtualEnv

bash
python -m venv venv                # bikin virtual environment
source venv/bin/activate            # aktifkan (Linux/Mac)
venv\Scripts\activate                 # aktifkan (Windows)
deactivate                              # keluar dari virtualenv

OOP

Python OOP dibangun di atas class & object seperti bahasa lain, tapi lebih fleksibel: batasan akses lewat konvensi underscore (bukan keyword private), dan tiap method eksplisit terima self sebagai parameter pertama.

Classes/Objects

python
class User:
    pass

u = User()               # instansiasi object dari class
u.name = "SaidQB"           # atribut bisa ditambah dinamis (kecuali pakai __slots__)

init Method

python
class User:
    def __init__(self, name, email):   # constructor, jalan otomatis saat instansiasi
        self.name = name
        self.email = email

u = User("SaidQB", "said@example.com")

self Parameter

python
class User:
    def __init__(self, name):
        self.name = name             # self = referensi ke instance itu sendiri
    def greet(self):                   # wajib jadi parameter pertama tiap method
        return f"Halo, {self.name}"

Class Properties

python
class User:
    species = "Human"          # class attribute -- shared semua instance
    def __init__(self, name):
        self.name = name           # instance attribute -- unik per instance

User.species                          # akses lewat class
u = User("SaidQB"); u.name              # akses lewat instance

Class Methods

python
class User:
    count = 0
    def __init__(self, name):
        self.name = name
        User.count += 1

    @classmethod
    def total(cls):              # terima cls, bukan self -- kerja di level class
        return cls.count

    @staticmethod
    def is_valid_name(name):       # tidak terima self/cls, murni utility function
        return len(name) > 0

Inheritance

python
class Animal:
    def __init__(self, name):
        self.name = name
    def sound(self):
        return "..."

class Cat(Animal):                   # Cat mewarisi semua dari Animal
    def sound(self):                    # override method parent
        return "Meong"
    def info(self):
        return super().sound()            # panggil method parent secara eksplisit

Polymorphism

python
class Cat:
    def sound(self): return "Meong"
class Dog:
    def sound(self): return "Guk"

for animal in [Cat(), Dog()]:
    print(animal.sound())     # method sama, perilaku beda tergantung tipe object

Encapsulation

python
class User:
    def __init__(self, name):
        self._name = name        # convention: _prefix = "protected", jangan diakses dari luar
        self.__secret = "x"          # name mangling: _User__secret, "private" secara konvensi

    @property
    def name(self):                    # getter
        return self._name

    @name.setter
    def name(self, value):               # setter -- bisa validasi sebelum assign
        self._name = value

Inner Classes

python
class Order:
    class Item:                  # class di dalam class, dikelompokkan secara logis
        def __init__(self, name, qty):
            self.name, self.qty = name, qty

    def __init__(self):
        self.items = []

order = Order()
item = Order.Item("Buku", 2)       # akses lewat Order.Item

File Handling

python
f = open("file.txt", "r")      # mode: r (read), w (write), a (append), x (create)
f.close()                         # wajib ditutup manual kalau tidak pakai `with`

Read Files

python
with open("file.txt", "r") as f:   # `with` otomatis close file walau ada exception
    content = f.read()                # baca semua isi jadi satu string
    f.seek(0)                            # balik ke awal file
    lines = f.readlines()                  # baca semua baris jadi list

with open("file.txt") as f:
    for line in f:                         # iterasi per baris, hemat memory buat file besar
        print(line.strip())

Write/Create Files

python
with open("file.txt", "w") as f:    # 'w' -- overwrite/bikin baru, hapus isi lama
    f.write("Halo dunia")

with open("file.txt", "a") as f:      # 'a' -- append, tambah di akhir tanpa hapus isi lama
    f.write("\nBaris baru")

with open("newfile.txt", "x") as f:     # 'x' -- bikin file baru, error kalau sudah ada
    f.write("data")

Delete Files

python
import os

os.remove("file.txt")           # hapus satu file
os.path.exists("file.txt")         # cek dulu sebelum hapus, biar tidak error
os.rmdir("folder_kosong")            # hapus folder (harus kosong)

import shutil
shutil.rmtree("folder")                # hapus folder + isinya (tidak harus kosong)