course_model

Python Control Flow

Learning Outcomes: Python Control Flow

By the end of this section, you will be able to:

Example Code

If, Elif, Else Statements

x = 10
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

Boolean Expressions

n = 5
print(n > 3)      # True
print(n == 5)     # True
print(n != 2)     # True

For Loops Over Lists/Arrays/Ranges

nums = [1, 2, 3, 4]
for num in nums:
    print(num)

for i in range(5):
    print(i)

For Loops to Process Numbers in Arrays/Lists

squares = []
for n in [1, 2, 3, 4]:
    squares.append(n ** 2)
print(squares)

Conditional Logic Inside Loops

nums = [1, 2, 3, 4, 5]
evens = []
for n in nums:
    if n % 2 == 0:
        evens.append(n)
print(evens)

Break and Continue

for n in range(10):
    if n == 5:
        break  # Stop the loop when n is 5
    if n % 2 == 0:
        continue  # Skip even numbers
    print(n)

Using range()

for i in range(3, 8):
    print(i)

Combining Loops and Conditionals for Data Analysis

# Print all numbers greater than 10 in a list
arr = [4, 12, 7, 15, 3]
for n in arr:
    if n > 10:
        print(n)

List comprehensions


def is_odd(n):
    return n % 2 != 0

nums = range(0, 10)
squares = [n ** 2 for n in nums]
print(squares)

odd_squares = [n ** 2 for n in nums if is_odd(n)]
print(odd_squares)

Practice Problems