Lewati ke konten
Kembali ke Blog

Cara Belajar Python Programming untuk Pemula

· · 5 menit baca

Python adalah bahasa programming yang mudah dipelajari dan sangat powerful. Mari pelajari dari dasar.

Install Python

Linux

# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip

python3 --version pip3 --version

Windows & Mac

# Download dari python.org
# Atau gunakan package manager

Mac dengan Homebrew

brew install python3

Windows dengan Chocolatey

choco install python

Python Basics

Hello World

# Print ke console
print("Hello, World!")

Input dari user

nama = input("Masukkan nama: ") print(f"Halo, {nama}!")

Variables dan Data Types

# String
nama = "Budi"
pesan = 'Hello World'
multi_line = """
Ini adalah
multi-line string
"""

Number

umur = 25 # integer harga = 99.99 # float kompleks = 3+4j # complex

Boolean

aktif = True selesai = False

None (null equivalent)

data = None

Type Conversion

# Convert types
angka_str = "123"
angka_int = int(angka_str)   # 123
angka_float = float(angka_str)  # 123.0

Check type

print(type(angka_int)) # <class 'int'>

Operators

Arithmetic Operators

a = 10
b = 3

print(a + b) # 13 (addition) print(a - b) # 7 (subtraction) print(a * b) # 30 (multiplication) print(a / b) # 3.33 (division) print(a // b) # 3 (floor division) print(a % b) # 1 (modulus) print(a ** b) # 1000 (exponent)

Comparison Operators

x = 5
y = 3

print(x == y) # False print(x != y) # True print(x > y) # True print(x <= y) # False

Logical Operators

a = True
b = False

print(a and b) # False print(a or b) # True print(not a) # False

Control Flow

If-Else Statement

nilai = 85

if nilai >= 90: print("A") elif nilai >= 80: print("B") elif nilai >= 70: print("C") else: print("D")

Ternary operator

status = "Lulus" if nilai >= 70 else "Tidak Lulus"

Match Statement (Python 3.10+)

hari = "Senin"

match hari: case "Senin" | "Selasa" | "Rabu": print("Hari kerja awal") case "Kamis" | "Jumat": print("Hari kerja akhir") case "Sabtu" | "Minggu": print("Weekend") case _: print("Tidak valid")

Loops

For Loop

# Range loop
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

Range with start and step

for i in range(0, 10, 2): print(i) # 0, 2, 4, 6, 8

Iterate list

buah = ["apel", "jeruk", "mangga"] for item in buah: print(item)

Enumerate

for index, item in enumerate(buah): print(f"{index}: {item}")

While Loop

i = 0
while i < 5:
    print(i)
    i += 1

Break and continue

for i in range(10): if i == 3: continue # Skip 3 if i == 7: break # Stop at 7 print(i)

Data Structures

Lists

# Create list
buah = ["apel", "jeruk", "mangga"]

Access elements

print(buah[0]) # apel print(buah[-1]) # mangga (last) print(buah[1:3]) # ['jeruk', 'mangga']

Modify

buah.append("anggur") # Add to end buah.insert(0, "durian") # Insert at index buah.remove("jeruk") # Remove by value buah.pop() # Remove last buah.pop(0) # Remove at index

List comprehension

angka = [1, 2, 3, 4, 5] kuadrat = [x**2 for x in angka]

[1, 4, 9, 16, 25]

genap = [x for x in angka if x % 2 == 0]

[2, 4]

Dictionaries

# Create dictionary
user = {
    "nama": "Budi",
    "umur": 25,
    "kota": "Jakarta"
}

Access

print(user["nama"]) # Budi print(user.get("email")) # None (safe access) print(user.get("email", "[email protected]"))

Modify

user["email"] = "[email protected]" user.update({"phone": "123456"}) del user["phone"]

Iterate

for key in user: print(f"{key}: {user[key]}")

for key, value in user.items(): print(f"{key}: {value}")

Dictionary comprehension

angka = [1, 2, 3, 4, 5] kuadrat = {x: x**2 for x in angka}

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Tuples and Sets

# Tuple (immutable)
koordinat = (10, 20)
x, y = koordinat  # Unpacking

Set (unique values)

angka = {1, 2, 3, 3, 4} # {1, 2, 3, 4} angka.add(5) angka.remove(1)

Set operations

a = {1, 2, 3} b = {2, 3, 4} print(a | b) # Union: {1, 2, 3, 4} print(a & b) # Intersection: {2, 3} print(a - b) # Difference: {1}

Functions

Basic Functions

# Define function
def sapa(nama):
    return f"Halo, {nama}!"

print(sapa("Budi"))

Default parameters

def sapa(nama="User"): return f"Halo, {nama}!"

Multiple return

def hitung(a, b): return a + b, a - b, a * b

tambah, kurang, kali = hitung(10, 5)

Args and Kwargs

# *args (variable positional arguments)
def jumlah(*angka):
    return sum(angka)

print(jumlah(1, 2, 3, 4, 5)) # 15

**kwargs (variable keyword arguments)

def info(**data): for key, value in data.items(): print(f"{key}: {value}")

info(nama="Budi", umur=25, kota="Jakarta")

Lambda Functions

# Lambda (anonymous function)
kuadrat = lambda x: x ** 2
print(kuadrat(5))  # 25

Use with map, filter

angka = [1, 2, 3, 4, 5] hasil = list(map(lambda x: x * 2, angka))

[2, 4, 6, 8, 10]

genap = list(filter(lambda x: x % 2 == 0, angka))

[2, 4]

File Handling

Read and Write Files

# Write file
with open("data.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Python is awesome!")

Read file

with open("data.txt", "r") as f: content = f.read() print(content)

Read line by line

with open("data.txt", "r") as f: for line in f: print(line.strip())

Append to file

with open("data.txt", "a") as f: f.write("\nNew line")

JSON Handling

import json

Write JSON

data = {"nama": "Budi", "umur": 25} with open("data.json", "w") as f: json.dump(data, f, indent=2)

Read JSON

with open("data.json", "r") as f: loaded = json.load(f) print(loaded["nama"])

Error Handling

Try-Except

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Tidak bisa dibagi nol!")
except Exception as e:
    print(f"Error: {e}")
else:
    print("Sukses!")
finally:
    print("Selalu dijalankan")

Raise exception

def validate_age(umur): if umur < 0: raise ValueError("Umur tidak boleh negatif") return umur

Kesimpulan

Python adalah bahasa yang versatile untuk berbagai keperluan. Mulai dengan basics lalu explore libraries seperti NumPy, Pandas, atau Django.

Ditulis oleh

Hendra Wijaya

Tinggalkan Komentar

Email tidak akan ditampilkan.