Lession 2: Control Structure in Python by Chat GPT
In Python, control structures determine the flow of execution in a program. These include conditional statements, loops, and jump statements. Here’s an overview:
1. Conditional Statements
Conditional statements allow you to execute code based on conditions.
if, elif, else
x = 10
if x > 5: # Condition is True
print("x is greater than 5")
elif x == 5: # Optional; executes if the first condition is False
print("x is equal to 5")
else: # Executes if all conditions above are False
print("x is less than 5")
2. Loops
Loops are used to execute a block of code repeatedly.
for Loop
Iterates over a sequence (like a list, tuple, string, or range).
for i in range(5): # Iterates from 0 to 4
print(i)
# Example with a list
colors = ["red", "blue", "green"]
for color in colors:
print(color)
while Loop
Repeats as long as a condition is True.
count = 0
while count < 5: # Loop until count reaches 5
print(count)
count += 1
3. Jump Statements
Control the flow of loops.
break
Exits the loop prematurely.
for i in range(10):
if i == 5:
break # Exit the loop
print(i)
continue
Skips the current iteration and moves to the next.
for i in range(5):
if i == 2:
continue # Skip this iteration
print(i)
pass
A placeholder that does nothing.
if True:
pass # Placeholder for future code
4. Nested Control Structures
Control structures can be nested inside each other.
for i in range(3):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
5. Exception Handling (Control Flow with try-except)
Manages errors and exceptions gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
These are the essential control structures in Python that help you manage program execution flow. Would you like a deeper dive into any specific type?
Comments
Post a Comment