PYTHON / JAVASCRIPT / HTML / CSS
Learn coding
Reference, examples, and practice.
Python reference
26 topics01Python Basics
The print() function writes text to the screen. Anything inside the parentheses gets printed. Text must be wrapped in quotes.
# My first Python program
print("Hello, world!")
print("I am learning Python.")
# This line is a comment. Python skips it.
print(2 + 3) # prints 502Variables & Types
Python has several basic types: str (text), int (whole numbers), float (decimals), and bool (True/False).
name = "Ada" # str
age = 36 # int
pi = 3.14159 # float
is_awesome = True # bool
print(f"{name} is {age} years old.")
print(type(pi)) # <class 'float'>03Conditions
Indentation matters in Python — the code inside an if must be indented (usually 4 spaces).
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Keep practicing!")04Loops
A while loop repeats as long as its condition stays True. Be careful: a condition that never becomes False loops forever.
for i in range(5):
print(f"Counting: {i}")
total = 0
n = 1
while n <= 10:
total += n
n += 1
print(f"Sum of 1..10 is {total}")05Functions
Parameters are the inputs. return sends a value back to whoever called the function.
def greet(name):
return f"Hello, {name}!"
def area(width, height):
return width * height
print(greet("Ada"))
print(f"Area: {area(5, 3)}")06Lists & Dicts
A dict (dictionary) maps keys to values, like a real dictionary maps words to definitions.
inventory = ["sword", "shield", "potion"]
inventory.append("bow")
for item in inventory:
print(f"You have: {item}")
player = {"name": "Ada", "hp": 100, "level": 5}
print(player["name"])
player["hp"] -= 20
print(f"HP after the trap: {player['hp']}")07Working with Strings
Slicing takes part of a string with start:end. The end position is not included.
word = "Python"
print(word[0]) # P
print(word[1:4]) # yth
print(word.lower()) # python
sentence = "learn python today"
print(sentence.split())
print(sentence.replace("today", "now"))08Errors & Exceptions
A try block contains code that might fail. An except block handles a specific failure.
text = "42"
try:
number = int(text)
print(number * 2)
except ValueError:
print("Please enter a whole number.")09List Comprehensions
The pattern is [expression for item in sequence]. Python computes the expression for each item.
numbers = [1, 2, 3, 4, 5, 6] squares = [n * n for n in numbers] evens = [n for n in numbers if n % 2 == 0] print(squares) print(evens)
10Mini Project: Grade Report
Start by calculating a value, then build output that a person can understand.
scores = [70, 85, 90, 55]
def average(values):
return sum(values) / len(values)
print(f"Average: {average(scores):.1f}")
for score in scores:
status = "pass" if score >= 60 else "review"
print(score, status)11Dictionary Lookups
Square brackets retrieve a required key and raise KeyError when it is missing. get(key, default) is useful when absence is expected.
product = {"name": "Notebook", "price": 4}
product["price"] = 5
print(product.get("stock", 0))12Sets & Uniqueness
Use in for membership and & for intersection: values present in both sets. The | operator makes a union.
tags = {"python", "web", "python"}
print(len(tags))
print("web" in tags)13Tuples & Unpacking
Unpacking binds several names at once. The number of names must match the number of values unless a starred target gathers extras.
point = (4, 7) x, y = point print(x + y)
14Indexes with enumerate
Pass start=1 for human-friendly numbering. The underlying collection does not change.
for position, item in enumerate(["tea", "water"], start=1):
print(position, item)15Sort with a Key
A key function supplies the value used for comparison. key=len sorts strings by length rather than alphabetical order.
words = ["pear", "fig", "banana"] print(sorted(words, key=len))
16JSON Data
json.loads parses a JSON string into Python values; json.dumps produces JSON text from Python values. JSON uses double quotes around strings.
import json
data = json.loads('{"name": "Ada", "active": true}')
print(data["active"])17Your First Class
__init__ initializes the instance. self is the instance passed to methods; attributes such as self.name belong to that object.
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
c = Counter()
c.increment()
print(c.value)18Assertions & Edge Cases
A good test covers normal inputs and boundaries. For a passing threshold of 60, test 59, 60, and 61.
def passes(score):
return score >= 60
assert passes(60) is True
assert passes(59) is False
print("Tests passed")19While Loops
Something inside the loop must move toward ending it, such as increasing a counter. Otherwise the loop never stops.
count = 3
while count > 0:
print(count)
count -= 120Splitting & Joining Text
join() does the reverse. The separator comes first: ", ".join(items) glues the items together with a comma and a space.
words = "learn python today".split()
print(len(words))
print("-".join(words))21Default & Keyword Arguments
Keyword arguments name the parameter at the call site, such as greet("Ada", greeting="Hi"). Order stops mattering and the call reads clearly.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ada"))
print(greet("Ada", greeting="Hi"))22map, filter & lambda
map(function, items) applies a function to every item. filter(function, items) keeps items where the function returns true.
nums = [1, 2, 3, 4] doubled = list(map(lambda n: n * 2, nums)) print(doubled)
23Formatting Numbers
Use {n:05d} to pad with zeros, {n:,} for thousands separators, and {ratio:.0%} to show a percentage.
price = 4.5
print(f"${price:.2f}")
print(f"{1234567:,}")24Recursion
factorial(4) is 4 * factorial(3), and so on until factorial(1), which simply returns 1.
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)25Inheritance
Define a method with the same name in the subclass to override it. super() calls the parent version when you still need it.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"26Generators
Each time the loop asks for the next value, the function resumes after the previous yield. Values are produced lazily, so memory stays small.
def count_up(limit):
n = 1
while n <= limit:
yield n
n += 1
for value in count_up(3):
print(value)