Python Basics
Quick reference guide for Python fundamentals.
Variables and Data Types
Python is dynamically typed (no need to declare types):
# ========== Numbers ==========
age = 25 # Integer
price = 19.99 # Float (decimal)
distance = 1e6 # Scientific notation (1,000,000)
# ========== Strings ==========
name = "Yudi" # Double quotes
message = 'Hello!' # Single quotes (same as double)
multiline = """
This is a
multi-line string
"""
# ========== Booleans ==========
is_active = True # Note: capital T and F
has_permission = False
# ========== Lists (ordered, mutable) ==========
fruits = ["apple", "banana", "orange"]
mixed = [1, "two", 3.0, True] # Can mix types
# ========== Dictionaries (key-value pairs) ==========
person = {
"name": "Yudi",
"age": 25,
"city": "Jakarta"
}
# Access: person["name"] → "Yudi"
# ========== Tuples (ordered, immutable) ==========
coordinates = (10, 20) # Cannot be changed after creation
# ========== Sets (unordered, unique values) ==========
unique_numbers = {1, 2, 3, 3, 2} # Becomes {1, 2, 3}
Control Flow
If Statements
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
Loops
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
# List iteration
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
Functions
Define reusable code blocks to avoid repetition:
# ========== Basic Function ==========
def greet(name):
"""Greet a person by name"""
return f"Hello, {name}!"
# ========== Multiple Parameters ==========
def add(a, b):
"""Add two numbers together"""
return a + b
# ========== Default Parameters ==========
def power(base, exponent=2):
"""Raise base to exponent (defaults to square)"""
return base ** exponent
# ========== Multiple Return Values ==========
def get_user():
"""Return multiple values as tuple"""
return "Yudi", 25, "Jakarta"
# ========== Variable Arguments ==========
def sum_all(*numbers):
"""Sum any number of arguments"""
return sum(numbers)
# ========== Calling Functions ==========
message = greet("Yudi") # "Hello, Yudi!"
result = add(5, 3) # 8
squared = power(5) # 25 (uses default exponent=2)
cubed = power(5, 3) # 125
name, age, city = get_user() # Unpack tuple
total = sum_all(1, 2, 3, 4, 5) # 15
List Comprehensions
Create lists efficiently in one line (Pythonic way):
# ========== Basic Comprehension ==========
# Traditional way:
squares = []
for x in range(10):
squares.append(x**2)
# Comprehension way (better):
squares = [x**2 for x in range(10)]
# Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# ========== With Condition (Filter) ==========
# Get only even numbers
evens = [x for x in range(20) if x % 2 == 0]
# Result: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# ========== Transform and Filter ==========
# Square even numbers only
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Result: [0, 4, 16, 36, 64]
# ========== Nested Comprehension (Matrix) ==========
# Create 3x3 multiplication table
matrix = [[i*j for j in range(3)] for i in range(3)]
# Result: [[0,0,0], [0,1,2], [0,2,4]]
# ========== String Operations ==========
# Convert to uppercase
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
# Result: ["ALICE", "BOB", "CHARLIE"]
Common Methods
String Methods
text = "Hello, World!"
text.lower() # "hello, world!"
text.upper() # "HELLO, WORLD!"
text.replace("Hello", "Hi") # "Hi, World!"
text.split(",") # ["Hello", " World!"]
List Methods
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
numbers.pop() # Removes last item
numbers.sort() # Sorts in place