Control Structures In Python

 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:

  • if statements 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.
  • else statements 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:

  • for loops 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:

  • while loops 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:

  • break statements are used to exit the loop prematurely, skipping the remaining iterations.
  • continue statements 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:

  • try statements are used to handle exceptions that may occur within a block of code.
  • except statements specify the code to execute if a specific exception is raised.
  • else statements are executed if no exceptions occur within the try block.
  • finally statements 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")

These control structures provide you with the flexibility to write dynamic and responsive code in Python, allowing you to handle different scenarios and control the flow of your program effectively.

Post a Comment

0 Comments