Control structures in Python are constructs used to control the flow of execution within a program. They allow you to make decisions, iterate over sequences of data, and handle exceptions. The main control structures in Python include:
1. if...elif...else Statements:
ifstatements are used to execute a block of code only if a specified condition is true.elif(short for "else if") statements allow you to check additional conditions if the previous conditions are false.elsestatements are executed when none of the previous conditions are true.
Example:
x = 10 if x > 0: print("x is positive") elif x == 0: print("x is zero") else: print("x is negative")
2. for Loops:
forloops are used to iterate over a sequence (e.g., lists, tuples, strings) or other iterable objects.- They execute a block of code once for each item in the sequence.
Example:
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
3. while Loops:
whileloops are used to repeatedly execute a block of code as long as a specified condition is true.- They continue looping until the condition becomes false.
Example:
i = 1 while i <= 5: print(i) i += 1
4. break and continue Statements:
breakstatements are used to exit the loop prematurely, skipping the remaining iterations.continuestatements are used to skip the current iteration and continue with the next iteration of the loop.
Example:
for i in range(1, 11): if i == 5: break # Exit the loop when i reaches 5 print(i) for i in range(1, 11): if i % 2 == 0: continue # Skip even numbers print(i)
5. try...except...else...finally Statements:
trystatements are used to handle exceptions that may occur within a block of code.exceptstatements specify the code to execute if a specific exception is raised.elsestatements are executed if no exceptions occur within the try block.finallystatements are executed regardless of whether an exception occurs.
Example:
try: x = 10 / 0 # Division by zero except ZeroDivisionError: print("Division by zero is not allowed") else: print("Division successful") finally: print("Execution complete")
0 Comments