Introduction
Control flow is the foundation of any programming language, and Python is no exception. Whether you’re making decisions with if
, repeating tasks with for
, or looping until a condition is met with while
, mastering these structures helps you write clear, efficient code. This article will walk you through the essentials of Python’s control flow.
Using if Statements for Decision Making
The if
statement allows you to execute code conditionally. You can combine it with elif
and else
to handle multiple cases:
score = 85
if score >= 90:
print("Excellent")
elif score >= 70:
print("Good")
else:
print("Needs improvement")
Iterating with for Loops
for
loops are used to iterate over sequences like lists, tuples, or strings. Here’s a basic example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
You can also use range()
to loop a specific number of times:
for i in range(5):
print("Number:", i)
Repeating with while Loops
A while
loop continues as long as the condition is true:
count = 0
while count < 3:
print("Counting:", count)
count += 1
Break and Continue
Python provides break
to exit a loop early, and continue
to skip to the next iteration:
for i in range(5):
if i == 3:
break # stops the loop at 3
print(i)
for i in range(5):
if i == 2:
continue # skips 2
print(i)
Conclusion
Understanding how to control the flow of your Python program is a fundamental skill. By using if
, for
, and while
effectively, you can create smarter, more dynamic scripts. Practice these structures regularly, and you’ll soon find them second nature.
Comment