DEV Community

NUR ARIF
NUR ARIF

Posted on • Edited on

Flow Control

Flow control is a way to control the flow of execution in a program. In Python, flow control is accomplished through statements such as if-else, for loops, and while loops. This concept allows programs to make decisions based on certain conditions and iterate through a certain sequence of items. This helps make programs more flexible and allows for more complex logic in programming.

Flow control in Python can be done using statements such as if-else, for loops, and while loops. Following are the details of each statement and a case study example:

Here's a simple example using anifstatement:

age = 18
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Enter fullscreen mode Exit fullscreen mode

In this example, the code inside the if statement will be executed if the value of age is greater than or equal to 18. If it is not, the code inside the else statement will be executed instead.

Another example of flow control in Python is the for loop, which is used to iterate over a sequence of elements and execute a block of code for each element:

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

Enter fullscreen mode Exit fullscreen mode

In this example, the code inside the for loop will be executed once for each element in the fruits list, with the variable fruit taking on the value of each element in turn.

You can also use the while loop to repeatedly execute a block of code as long as a certain condition is met:

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

Enter fullscreen mode Exit fullscreen mode

In this example, the code inside the while loop will be executed repeatedly as long as the value of count is less than or equal to 5. Each time the code is executed, the value of count is incremented by 1, so eventually the condition will no longer be met and the loop will stop.

Top comments (0)