Control Flow in Python: If Statements, Loops, and More
When writing code, you'll often need to make decisions and control how the program flows based on different conditions. This is known as control flow, and Python offers various ways to implement it. In this article, we’ll explore Python's control flow tools: conditional statements like if
, else
, and elif
, as well as loops. These structures allow your program to execute specific sections of code only when certain conditions are met or repeat actions multiple times.
If Statement
The if
statement is the most basic control flow tool. It allows you to run a block of code only when a specified condition is true. Think of it like a decision-making process: "If this happens, do that."
Here’s a simple example:
x = 10
if x > 5:
print("x is greater than 5")
In this case, the program checks if x
is greater than 5. Since the condition is true, it prints the message "x is greater than 5"
.
Indentation Matters
One thing to note in Python is the importance of indentation. The code that should run when the condition is true must be indented. Without proper indentation, Python will throw an error. Indentation in Python is typically four spaces or a single tab.
Python if...else
Statement
Sometimes, you’ll want your program to do something if the condition is true and something else if it’s false. That’s where the else
statement comes in. The else
block allows you to run a section of code when the if
condition isn’t met.
Example:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
Here, the condition x > 5
is false, so the code inside the else
block runs instead, printing "x is 5 or less"
.
Python if...elif...else
Statement
What if you have more than two conditions to check? That’s where elif
(short for "else if") comes in handy. It allows you to check multiple conditions and execute the appropriate block of code for the first condition that’s true.
For example:
x = 10
if x > 20:
print("x is greater than 20")
elif x > 5:
print("x is greater than 5 but less than or equal to 20")
else:
print("x is 5 or less")
In this code, the program first checks if x
is greater than 20. Since that condition is false, it checks the next condition, x > 5
, which is true. So, the second block of code runs, and the program prints "x is greater than 5 but less than or equal to 20"
.
Syntax of if...elif...else
Here’s the general structure of an if...elif...else
statement:
if condition1:
# code for condition1
elif condition2:
# code for condition2
else:
# code if none of the conditions are true
The elif
clause can be repeated as many times as needed to check multiple conditions.
Python Nested if
Statements
You can also nest if
statements inside other if
statements for more complex decision-making. This allows you to create multiple layers of conditions.
Example:
x = 15
if x > 10:
if x % 2 == 0:
print("x is greater than 10 and even")
else:
print("x is greater than 10 and odd")
Here, the first if
statement checks whether x
is greater than 10. If true, the program then checks whether x
is even or odd by using another if
statement inside the first. If x
is odd, it prints "x is greater than 10 and odd"
. Nested if
statements can be useful for handling multi-level logic, but be careful not to overuse them, as too much nesting can make your code harder to read.
Python Loops: For and While
Control flow isn’t just about making decisions; sometimes, you need your program to repeat actions. That’s where loops come into play.
The for
Loop
A for
loop lets you iterate over a sequence (like a list, tuple, or range) and execute a block of code for each item in that sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
In this example, the loop will print each fruit in the list, one by one. Loops are incredibly useful when you need to perform repetitive tasks, like processing every item in a list or generating a range of numbers.
The while
Loop
The while
loop repeats a block of code as long as a certain condition is true. It’s like the if
statement, but it keeps executing until the condition becomes false.
Example:
x = 0
while x < 5:
print(x)
x += 1 # This increments x by 1 each time
This loop will print numbers from 0 to 4. Each time through the loop, x
increases by 1, and once x
reaches 5, the loop stops.
Avoid Infinite Loops
Always ensure that your while
loop has a condition that eventually becomes false. Otherwise, you’ll create an infinite loop, where the code runs forever. For example, the following code will result in an infinite loop because the condition x < 5
is always true (since we’re not changing x
):
x = 0
while x < 5:
print(x)
Let’s Practice
Try writing a Python program that checks if a number is:
Positive
Negative
Zero
Use an if...elif...else
structure to handle the different conditions.
Next, write a for
loop to print all the even numbers between 1 and 10. For an extra challenge, write a while
loop that asks the user for input repeatedly until they type "exit"
.
Test Your Knowledge
What is the purpose of the
else
clause in anif
statement?How does a
for
loop differ from awhile
loop in Python?Write a nested
if
statement that checks whether a number is positive, even, or odd.Explain the difference between
if
,elif
, andelse
.Create a Python script that uses both
for
andwhile
loops.
Conclusion
Understanding control flow in Python is crucial to writing programs that can make decisions and repeat actions. Whether you're using simple if
statements, looping through data with for
or while
loops, or nesting conditions, control flow structures allow your programs to behave dynamically based on the inputs they receive. Practice writing conditional statements and loops to gain mastery over Python’s control flow capabilities!
Subscribe to my newsletter
Read articles from Arnav Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Arnav Singh
Arnav Singh
A 16 y/o trying to get into a college :<