Control flow statements in Python are used to control the order in which the program’s code executes. Here are some of the most common ones:
If, Elif, and Else
if
, elif
, and else
are used for conditional execution, i.e., to execute a certain block of code if a certain condition is met.
- if: The
if
statement is used to test a specific condition. If the condition isTrue
, the block of code under it is executed.
x = 10
if x > 5:
print("x is greater than 5")
- elif: The
elif
(short for else if) statement is used to check multiple expressions forTrue
and execute a block of code as soon as one of the conditions evaluates toTrue
.
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
- else: The
else
statement is used to catch anything which isn’t caught by the preceding conditions.
x = 10
if x > 10:
print("x is greater than 10")
elif x < 10:
print("x is less than 10")
else:
print("x is equal to 10")
Loops
Loops are used to repeatedly execute a block of code. Python has two types of loops - for
and while
.
- for: The
for
loop is used for iterating over a sequence (like a list, tuple, dictionary, string, or set) or other iterable objects. Iterating over a sequence is called traversal.
# Example of for loop
for i in range(5):
print(i)
- while: The
while
loop is used to repeatedly execute a block of code as long as a condition isTrue
.
# Example of while loop
i = 0
while i < 5:
print(i)
i += 1