Control Flow in Python – If Statements and Loops

Introduction to Control Flow

Control flow is the order in which your program executes its code. In Python, you can control the flow of your program using if statements and loops. These tools allow you to make decisions and repeat actions based on certain conditions.


If Statements

An if statement allows you to execute a block of code only if a certain condition is true. You can also use elif (short for “else if”) and else to handle multiple conditions.

Example: Age Checker

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

In this example:

  • If the age is 18 or older, the program prints "You are an adult."
  • Otherwise, it prints "You are a minor."

Loops in Python

Loops allow you to repeat a block of code multiple times. Python supports two types of loops: for loops and while loops.

1. For Loops

for loop is used to iterate over a sequence (e.g., a list, string, or range of numbers).

Example: Counting Numbers

 for i in range(5):
    prin(f"Number: {i}")

This loop prints numbers from 0 to 4.

2. While Loops

while loop repeats a block of code as long as a condition is true.

Example: Countdown

python

Copy

count = 5
while count > 0:
    print(f"Count: {count}")
    count -= 1

This loop prints a countdown from 5 to 1.


Conclusion

Control flow is a fundamental concept in Python programming. By mastering if statements and loops, you can write more dynamic and efficient programs. Practice these concepts by creating your own programs and experimenting with different conditions.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *