π¦ 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
Leave a Reply