Conditional Statements

The if conditional statement in Python is used to execute a block of code only if a specified condition is true. It can be extended with elif (else if) and else clauses to handle multiple conditions and provide alternative execution paths.

a = 10
b = 3

# Basic if statement
if a > b:
    print("a is greater than b")

# if-elif-else statement
if a < b:
    print("a is less than b")
elif a == b:
    print("a is equal to b")
else:
    print("a is greater than b")

For Loop

Loops in Python are used to repeat a block of code multiple times. The for loop iterates over a sequence (like a list, tuple, or string) or other iterable objects.

# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Loop through a range of numbers
for i in range(5):
    print(i)

While Loop

Loops in Python are used to repeat a block of code multiple times. The while loop repeatedly executes a block of code as long as a specified condition is true.

# Initialize a counter
count = 0

# Loop while the counter is less than 5
while count < 5:
    print(count)
    count += 1

Break

The break statement in Python is used to exit a loop prematurely, skipping any remaining iterations even if the loop's condition has not been met.

# Using break in a for loop:
for i in range(10):
    if i == 5:
        break
    print(i)

# Using break in a while loop:
count = 0
while count < 10:
    if count == 5:
        break
    print(count)
    count += 1

Continue

The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration of the loop.

# Using continue in a for loop:
for i in range(10):
    if i % 2 == 0:  # Skip even numbers
        continue
    print(i)

# Using continue in a while loop:
count = 0
while count < 10:
    count += 1
    if count % 2 == 0:  # Skip even numbers
        continue
    print(count)

Pass

The pass statement in Python is used as a placeholder in loops, functions, classes, or conditional statements. It does nothing and is used to ensure syntactical correctness when a statement is required but no action is needed.

# Using pass in a for loop:
for i in range(10):
    if i % 2 == 0:
        pass  # Placeholder for future code
    else:
        print(i)

# Using pass in a while loop:
count = 0
while count < 10:
    if count % 2 == 0:
        pass  # Placeholder for future code
    else:
        print(count)
    count += 1

# Using pass in a function:
def my_function():
    pass  # Placeholder for future code

# Using pass in a class:
class MyClass:
    pass  # Placeholder for future code