Control Flow
Control flow in Python refers to the order in which statements are executed. It includes conditional statements, loops, and special statements like break and continue.
Conditional Statements
Conditional statements in Python allow you to execute different blocks of code based on specified conditions. The primary constructs for this are the if, elif (else if), and else statements.
The if Statement
The if statement is used to execute a block of code if a specified condition is true.
Pythonx = 10
if x > 0:
print("Positive number")
The elif Statement
The elif statement allows you to check multiple conditions after the initial if statement. It is used to provide additional alternatives if the preceding conditions are false.
Pythonx = 0
if x > 0:
print("Positive number")
elif x < 0:
print("Negative number")
else:
print("Zero")
The else Statement
The else statement is used to execute a block of code if none of the preceding conditions in the if and elif statements are true.
Pythonx = -5
if x > 0:
print("Positive number")
elif x < 0:
print("Negative number")
else:
print("Zero")
Conditional statements can be nested, allowing for more complex decision-making in your code.
Pythonx = 10
y = 5
if x > 0:
if y > 0:
print("Both x and y are positive.")
else:
print("Only x is positive.")
else:
print("x is not positive.")
Python Loops
Loops in Python allow you to repeatedly execute a block of code. There are two main types of loops: for loops and while loops.
The for Loop
The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.
Pythonfruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
#The loop sequentially print this values:
# "apple"
# "banana"
# "cherry"
The while Loop
The while loop is used to repeatedly execute a block of code as long as a specified condition is true.
Pythoncount = 1
while count < 4:
print(count)
count += 1
#The loop sequentially print this values:
# 1
# 2
# 3
Break and Continue Statements
The break statement is used to exit a loop prematurely, while the continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration.
Pythonnumbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
#The loop sequentially print this values:
# 1
# 2
# The loop be stopped by break statement when encounter number 3 and don't show the rest numbers
Pythonnumbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
#The loop sequentially print this values:
# 1
# 2
# 4
# 5
# The loop skip number 3 and don't print it