Flow control in Python refers to the ability to control the execution of code based on certain conditions. There are several flow control statements in Python, including:
- if statement: It allows you to execute a block of code only if a certain condition is true. It can also be combined with else and elif statements to handle multiple conditions.
Example:
python
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
- for loop: It allows you to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence.
Example:
python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
- while loop: It allows you to repeatedly execute a block of code as long as a certain condition is true.
Example:
python
x = 0
while x < 5:
print(x)
x += 1
- break statement: It allows you to exit a loop prematurely, even if the loop condition is still true.
Example:
python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
break
print(fruit)
- continue statement: It allows you to skip the rest of the current iteration of a loop and move on to the next iteration.
Example:
python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
continue
print(fruit)
These flow control statements provide flexibility and control over the execution of code in Python.
Loading...