# IF Statements
# Simple IF
if condition:
do_something()
# IF-ELSE
if condition:
do_this()
else:
do_that()
# IF-ELIF-ELSE
if condition1:
do_first()
elif condition2:
do_second()
else:
do_third()
Comparison Operators:
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal
<= less than or equal
Logical Operators:
and - both must be true
or - at least one must be true
not - reverses the condition
Loops
FOR Loop
# Loop through a list
for item in my_list:
print(item)
# Loop with index
for i, item in enumerate(my_list):
print(f"Item {i}: {item}")
# Loop through two lists together
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# Loop through a range of numbers
for i in range(5): # 0, 1, 2, 3, 4
print(i)
WHILE Loop
counter = 0
while counter < 10:
print(counter)
counter += 1 # Don't forget to update!
Lists
# Create a list
fruits = ['apple', 'banana', 'orange', 'grape', 'peach']
# Access items
first = my_list[0] # First item
last = my_list[-1] # Last item
subset = my_list[1:3] # Slice: items 1-2
# Modify lists
my_list.append(6) # Add to end
my_list.remove(3) # Remove value 3
my_list.pop() # Remove last item
# Useful functions
len(my_list) # Number of items
sum(my_list) # Sum all numbers
max(my_list) # Maximum value
min(my_list) # Minimum value