Conditional statements are used to perform different actions based on different conditions.
The primary conditional statements in Python are if, elif, and else.
if condition:
# code to execute if condition is true
# 'if' checks the condition. If it's true, the block of code indented under it executes.
elif another_condition:
# code to execute if another_condition is true
# 'elif' is short for "else if". It's checked if the previous 'if' condition was false.
else:
# code to execute if none of the above conditions are true
# 'else' is executed if all the above conditions are false.
# Example:
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
# For Loop
# A 'for' loop is used for iterating over a sequence (like a list, tuple, dictionary, set, or string).
for item in iterable:
# code to execute for each item in the iterable
# The loop will iterate over each item in the iterable and execute the block of code within it.
# Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# While Loop
# A 'while' loop repeats a block of code as long as its condition is true.
while condition:
# code to execute as long as condition is true
# The loop will continue to execute the block of code as long as the condition remains true.
# Example:
count = 0
while count < 5:
print(count)
count += 1
# Break
# The 'break' statement is used to exit a loop prematurely.
for item in iterable:
if some_condition:
break
# rest of the loop code
# When 'break' is executed, it exits the loop and continues with the next statement after the loop.
# Example:
for num in range(10):
if num == 5:
break
print(num)
# Continue
# The 'continue' statement is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
for item in iterable:
if some_condition:
continue
# rest of the loop code
# When 'continue' is executed, it skips the remaining code inside the loop for the current iteration.
# Example:
for num in range(10):
if num % 2 == 0:
continue
print(num)
# Pass
# The 'pass' statement does nothing and is used as a placeholder for future code.
if condition:
pass # do nothing
# 'pass' is useful in scenarios where a statement is syntactically required, but you do not want any code to execute.
# Example:
def placeholder_function():
pass # This function does nothing