This chapter shows you some basic control flow statements in Python, including if, elif, and else statements for conditional logic, and for loops for iteration.
I will not ask you to write these, but the AI will often create them for you. I expect that you will be able to walk through the code and explain what is happening.
Outcomes:
if, elif, and else statements control the program flowfor loops process values in arrays or lists.break and continue statements control loop execution.range() function for numeric iteration.Reading:
Links:
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
n = 5
print(n > 3) # True
print(n == 5) # True
print(n != 2) # True
nums = [1, 2, 3, 4]
for num in nums:
print(num)
for i in range(5):
print(i)
squares = []
for n in [1, 2, 3, 4]:
squares.append(n ** 2)
print(squares)
nums = [1, 2, 3, 4, 5]
evens = []
for n in nums:
if n % 2 == 0:
evens.append(n)
print(evens)
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)
for i in range(3, 8):
print(i)
# Print all numbers greater than 10 in a list
arr = [4, 12, 7, 15, 3]
for n in arr:
if n > 10:
print(n)
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)