In Python, control structures are used to alter the flow of execution based on certain conditions or to iterate over a set of values. Here are the main control structures in Python:

  1. Conditional Statements:
    • if statement: It executes a block of code if a certain condition is true.
    • if-else statement: It executes a block of code if a condition is true, and a different block of code if the condition is false.
    • if-elif-else statement: It allows multiple conditions to be checked sequentially, and executes the block of code associated with the first true condition.
                
                 x=5
                 if x > 0:
                          print(“Positive”)
                 elif x < 0:
                          print(“Negative”)
                 else:
                         print(“Zero”)

 

  1. Loops:
    • for loop: It iterates over a sequence (such as a list, string, or range) or any iterable object, executing a block of code for each item in the sequence.
    • while loop: It repeatedly executes a block of code as long as a certain condition is true.
                  # for loop
                  fruits = [“apple”, “banana”, “cherry”]
                  for fruit in fruits:
                          print(fruit)
                  # while loop
                  count = 0
                  while count < 5:
                         print(count)
                  count += 1

 

  1. Control Statements:
    • break statement: It terminates the innermost loop and resumes execution at the next statement after the loop.
    • continue statement: It skips the rest of the current iteration of a loop and moves to the next iteration.
    • pass statement: It is a placeholder statement that does nothing. It is used when a statement is syntactically required but no action is needed.
 

Leave a Reply

Your email address will not be published. Required fields are marked *

%d