Control Flow Statements in Python

🚦 What is Control Flow?

In real life, we make decisions all the time.
For example:

  • If it’s raining, take an umbrella.
  • If you finish your homework, then play.

Python does the same using control flow statements. These help the program decide what to do next.

βœ… 1. if Statement

🧠 Use: To do something only if a condition is true.

πŸ“˜ Syntax:

if condition:
    # do something

πŸ§ͺ Example:

if 5 > 2:
    print("5 is greater than 2")

βœ… 2. if...else Statement

🧠 Use: To choose between two options.

πŸ“˜ Syntax:

if condition:
    # do this if true
else:
    # do this if false

πŸ§ͺ Example:

age = 16
if age >= 18:
    print("You can vote")
else:
    print("You are too young to vote")

βœ… 3. if…elif…else

🧠 Use: To check more than two conditions.

πŸ“˜ Syntax:

if condition1:
    # do this
elif condition2:
    # do this
else:
    # do this if nothing above is true

πŸ§ͺ Example:

score = 85
if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")
else:
    print("Try harder")

πŸ” 4. while Loop

🧠 Use: To repeat as long as the condition is true.

πŸ“˜ Syntax:

while condition:
    # do this again and again

πŸ§ͺ Example:

count = 1
while count <= 3:
    print("Count is", count)
    count += 1

πŸ” 5. for Loop

🧠 Use: To loop through a list, string, or range.

πŸ“˜ Syntax:

for item in list:
    # do this for each item

πŸ§ͺ Example:

for i in range(1, 4):
    print("Number:", i)

β›” 6. break Statement

🧠 Use: To stop a loop early.

πŸ“˜ Syntax:

for i in range(5):
    if i == 3:
        break
    print(i)

πŸ§ͺ Output

0
1
2

πŸ”„ 7. continue Statement

🧠 Use: To skip one step and move to the next.

πŸ“˜ Syntax:

for i in range(5):
    if i == 3:
        continue
    print(i)

πŸ§ͺ Output

0
1
2
4

Comments

Leave a Reply

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