Control Statements Intro.
Control statements are essential for directing the flow of execution in a Python program. They allow you to make decisions, repeat code blocks, and control the program's logic.
Conditional Statements: if, else, elif
- if: Executes a block of code if a condition is true.
- else: Executes a block of code if the condition is false.
- elif: Used for multiple conditions, checks additional conditions if the previous ones are false.
Python
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Loops: for, while
- for: Iterates over a sequence (list, tuple, string, etc.) or a range of numbers.
- while: Repeats a block of code as long as a condition is true.
Python
# for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# while loop
count = 0
while count < 5:
print(count)
count += 1
Loop Control Statements: break, continue, pass
- break: Terminates the loop entirely.
- continue: Skips the current iteration and moves to the next.
- pass: Does nothing, often used as a placeholder for future code.
Python
for number in range(10):
if number == 5:
break
print(number)
for number in range(10):
if number % 2 == 0:
continue
print(number)
Example Combining Control Statements
Python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
Control statements are fundamental to programming logic and allow you to create dynamic and interactive programs.