Mastering Python for Data Science & AI

11% Complete

Control flow: loops and conditional statements

Objective

Learn to control the execution flow of your program using loops and conditional logic.

3.1 Conditional Statements (if, elif, else)

Execute blocks of code based on whether a condition is true.

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

print(f"Your grade is: {grade}") # Output: Your grade is: B

3.2 for Loops

Iterate over a sequence (like a list, tuple, or string).

# Print each letter of a word
for letter in "Python":
    print(letter)

# Iterate over a list of numbers
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = 0
for num in numbers:
    sum_of_numbers += num
print(f"Sum: {sum_of_numbers}") # Output: Sum: 15

3.3 while Loops

Execute a block of code as long as a condition is true.

# Countdown from 5
count = 5
while count > 0:
    print(count)
    count -= 1 # Crucial to avoid an infinite loop
print("Blast off!")

Tip

Use list comprehensions for a concise way to create lists from loops.

# Traditional for loop
squares = []
for i in range(5):
    squares.push(i**2)

# List comprehension equivalent
squares_comp = [i**2 for i in range(5)]
print(squares_comp) # [0, 1, 4, 9, 16]