By the end of this section, you will be able to:
if, elif, and else statements to control the flow of a Python program based on conditions.for loops.for loops to process and analyze numbers in arrays or lists.break and continue statements to control loop execution.Understand and use the range() function for numeric iteration.
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)