Module Beginner
Control Flow
Learn about if statements, loops, and control structures in Python
Control Flow
Control flow memungkinkan kita mengontrol eksekusi kode berdasarkan kondisi tertentu.
If Statements
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
Comparison Operators
x = 10
y = 20
# Equal
x == y # False
# Not equal
x != y # True
# Greater than
x > y # False
# Less than
x < y # True
# Greater than or equal
x >= y # False
# Less than or equal
x <= y # True
Loops
For Loop
# Iterate over list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Range with start and stop
for i in range(2, 6):
print(i) # 2, 3, 4, 5
While Loop
count = 0
while count < 5:
print(count)
count += 1
Break and Continue
# Break - exit the loop
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# Continue - skip current iteration
for i in range(5):
if i == 2:
continue
print(i) # 0, 1, 3, 4
List Comprehensions
Cara elegan untuk membuat list:
# Traditional way
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(10)]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
Conclusion
Control flow adalah fondasi penting dalam programming. Pahami dengan baik if statements dan loops karena akan sering digunakan dalam development sehari-hari.