Conditional Statements

Conditional statements allow you to execute different blocks of code based on certain conditions.

if Statement

The if statement is used to execute a block of code if a specified condition is true.

x = 10
if x > 5:
print("x is greater than 5")

if-else Statement

The else clause is used to specify a block of code to be executed if the condition in the if statement is false.

x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

if-elif-else Statement

The elif (short for "else if") clause is used to add additional conditions to be checked if the previous conditions were false.

x = 10
if x < 5:
print("x is less than 5")
elif x < 10:
print("x is between 5 and 10")
else:
print("x is greater than or equal to 10")

Loops

Loops are used to execute a block of code repeatedly until a certain condition is met.

for Loop

The for loop is used to iterate over a sequence (such as a list, tuple, or string).

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

while Loop

The while loop is used to execute a block of code repeatedly as long as a given condition is true.

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

break and continue Statements

The break statement is used to terminate the loop, while the continue statement is used to skip the current iteration and move to the next one.

for i in range(10):
if i == 5:
    break
print(i)
for i in range(10):
if i == 5:
continue
print(i)

pass Statement

The pass statement is a null operation that does nothing. It is often used as a placeholder in code blocks where no action is required, to avoid syntax errors.

def my_function():
pass  # Placeholder for future code