control satatements

Control statements in Python are used to control the flow of program execution based on certain conditions. They allow you to make decisions, iterate over sequences, and execute different blocks of code based on specific conditions. The main control statements in Python include:

  1. if-elif-else Statements:
    • These statements are used to perform different actions based on different conditions.
    • Example:

code:

x = 10

if x > 0:
print(“Positive”)
elif x < 0:
print(“Negative”)
else:
print(“Zero”)

  1. for Loops:
    • for loops are used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.
    • Example:

fruits = [“apple”, “banana”, “orange”]

for fruit in fruits:
print(fruit)

  1. while Loops:
    • while loops are used to repeatedly execute a block of code as long as a condition is true.
    • Example:

count = 0

while count < 5:
print(count)
count += 1

  1. break Statement:
    • The break statement is used to terminate the loop prematurely and skip the remaining iterations.
    • Example:

fruits = [“apple”, “banana”, “orange”]

for fruit in fruits:
if fruit == “banana”:
break
print(fruit)

  1. continue Statement:
    • The continue statement is used to skip the current iteration of a loop and move to the next iteration.
    • Example:

fruits = [“apple”, “banana”, “orange”]

for fruit in fruits:
if fruit == “banana”:
continue
print(fruit)

  1. pass Statement:
    • The pass statement is used as a placeholder when a statement is syntactically required but does not need any code execution.
    • Example:

x = 5

if x > 0:
pass # No code execution needed
else:
print(“Negative”)

Control statements provide the ability to make decisions, perform repetitive tasks, and control the flow of execution in your Python programs. They are essential for implementing conditional logic and loops to handle different scenarios.

Leave a comment