Python
Readable by design.
Python's syntax reads almost like plain English. It's widely used for automation, scripting, data analysis, machine learning, and backend web development. A great second language after JavaScript.
Core concepts
Variables and types
Python is dynamically typed. You don't declare types — Python figures it out from the value. There's no const: convention is to write constants in ALL_CAPS. Python uses indentation (not braces) to define blocks.
name = "Sibah"
age = 17
height = 1.75
is_active = True
nothing = None
# Type checking
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
# F-strings (modern string formatting)
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)Lists and dicts
Lists are Python's ordered collections (like arrays). Dicts are key-value stores (like objects). Both are mutable. Python also has tuples (immutable lists) and sets (unique values).
# List
skills = ["Python", "JavaScript", "Lua"]
skills.append("Java") # add to end
skills[0] # "Python"
len(skills) # 4
# List comprehension
upper = [s.upper() for s in skills]
long = [s for s in skills if len(s) > 4]
# Dict
user = {
"name": "Sibah",
"age": 17,
"skills": ["JS", "Lua"]
}
user["name"] # "Sibah"
user.get("email", "") # "" (safe access)
user["location"] = "Indonesia"
# Iterate dict
for key, value in user.items():
print(f"{key}: {value}")Functions
Python functions are defined with def. They support default parameters, keyword arguments, and *args/**kwargs for variable-length inputs. Lambda is Python's equivalent of arrow functions — short, single-expression functions.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Sibah")) # Hello, Sibah!
print(greet("Sibah", "Hey")) # Hey, Sibah!
# Keyword arguments
print(greet(greeting="Hi", name="Sibah"))
# *args — variable positional arguments
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # 10
# **kwargs — variable keyword arguments
def describe(**info):
for key, value in info.items():
print(f" {key}: {value}")
describe(name="Sibah", age=17)
# Lambda
double = lambda x: x * 2
print(double(5)) # 10Conditions and loops
Python uses if/elif/else with no parentheses around conditions. for loops iterate directly over iterables — no index tracking needed. while loops run until a condition is false. break and continue control flow inside loops.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("Below B")
# for loop over a list
skills = ["JS", "Lua", "Python"]
for skill in skills:
print(skill)
# range: numeric loop
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
# while
count = 0
while count < 3:
print(count)
count += 1
# enumerate: index + value
for i, skill in enumerate(skills):
print(f"{i}: {skill}")Modules
Python comes with a large standard library. Import any module with import. Use from x import y to import specific things. Third-party packages are installed with pip.
import os
import json
from datetime import datetime
from pathlib import Path
# OS operations
print(os.getcwd()) # current directory
os.makedirs("output", exist_ok=True)
# JSON
data = {"name": "Sibah", "age": 17}
json_str = json.dumps(data, indent=2)
parsed = json.loads(json_str)
# Datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d"))
# File operations
file = Path("data.txt")
file.write_text("Hello, world")
content = file.read_text()
print(content)Exceptions
When something goes wrong, Python raises an exception. try/except catches it. Use specific exception types to handle different errors differently. finally always runs, even if an exception was raised.
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Multiple exceptions
try:
value = int("not a number")
except ValueError as e:
print(f"Value error: {e}")
except TypeError as e:
print(f"Type error: {e}")
finally:
print("This always runs")
# Raise your own
def get_user(id):
if id < 0:
raise ValueError(f"Invalid ID: {id}")
return {"id": id, "name": "Sibah"}
try:
user = get_user(-1)
except ValueError as e:
print(e)Basic OOP
Python is object-oriented. Classes bundle data (attributes) and behavior (methods). __init__ is the constructor. self refers to the current instance. Inheritance extends a class with new behavior.
class Player:
def __init__(self, name, level=1):
self.name = name
self.level = level
self.alive = True
def greet(self):
return f"I am {self.name}, level {self.level}"
def level_up(self):
self.level += 1
print(f"{self.name} is now level {self.level}")
def __repr__(self):
return f"Player({self.name!r}, level={self.level})"
class Admin(Player):
def __init__(self, name):
super().__init__(name, level=100)
self.is_admin = True
def kick(self, target):
print(f"{self.name} kicked {target}")
p = Player("Sibah")
p.level_up()
print(p)
admin = Admin("Staff")
admin.kick("Griefer")