Check out this video for an overview of the article. Then, read the article and solve exercises to strengthen your understanding.
- The conditional statements:
if
,elif
,else
. - How to create loops.
- How to select between the
for
loops and thewhile
loops.
In “Python” programming, you can control the flow of your code using the following concepts:
- Conditional statements like
if
,elif
, andelse
- Loops using
while
orfor
with keywords such asbreak
andcontinue
.
Conditional statements allow you to execute certain blocks of code based on specific conditions. Loops let you repeat a block of code multiple times. The break
keyword is used to exit a loop prematurely, while continue
skips the rest of the code inside a loop and starts the next iteration. Understanding and mastering these tools will help you write a more dynamic and efficient “Python” code.
1 Conditional Statements
Conditional statements are used to perform different actions based on conditions. There are three main types of conditional statements in “Python” language: if
, elif
, and else
.
1.1 The if
Statement
The if
statement is used to check if a condition is satisfied or not. If the condition is True
, the code inside the if
block will be executed. If the condition is False
, the code inside the if
block will be skipped.
# Example of if statement
x = 10
if x > 5:
print("x is greater than 5")
x is greater than 5
2 The elif
Statement
The elif
statement is short for “else if” and is used after the if
statement. If the condition in the if
statement is False
, the condition in the elif
statement will be checked. If that condition is True
, the code inside the elif
block will be executed.
# Example of elif statement
y = 0
if y < 0:
print("y is negative")
elif y == 0:
print("y is zero")
y is zero
3 The else
Statement
The else
statement is used to execute a block of code when none of the conditions in the if
and elif
statements are True
.
In the above example code of the elif
statement, you can not handle the case when y
is positive. To include the case, I added the else
statement.
# Example of else statement
y = 3
if y < 0:
print("y is negative")
elif y == 0:
print("y is zero")
else:
print("y is positive")
y is positive
Since y
is a positive value, the block in the else
statement will be executed.
You can add multiple elif
statements.
# Get the percentage from the user
percentage = 72
# Determine the grade based on the percentage
if percentage >= 90:
grade = "A"
elif percentage >= 80:
grade = "B"
elif percentage >= 70:
grade = "C"
elif percentage >= 60:
grade = "D"
else:
grade = "F"
# Output the grade to the user
print(f"Your grade is: {grade}")
Your grade is: C
4 Loops
Loops are used to execute a block of code repeatedly until a certain condition is met. There are two main types of loops in “Python” language: for
loops and while
loops.
4.1 The for
Loops
You can use the for
loop to iterate over a sequence (e.g., list, tuple, string).
NOTE
To tell the truth, you can loop over other objects called iterable. However, you don’t need to care about them for now.
The for
loop executes a block of code for each item in the sequence until there are no more items left.
# Example of for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
Let me explain this code.
fruits = ["apple", "banana", "cherry"]
: This line initializes a list called fruits
containing three strings: "apple"
, "banana"
, and "cherry"
.
for fruit in fruits:
: This line introduces a for
loop that iterates over each item in the fruits
list. In each iteration, the current item is assigned to the variable fruit
.
print(fruit)
: Inside the loop, this line prints the value of fruit
. During the first iteration, fruit
will be "apple"
, then "banana"
in the second iteration, and "cherry"
in the third iteration.
When the loop finishes iterating over all items in the fruits
list, the loop exits.
Therefore, when you run this code, it will output each fruit in the list fruits
on a new line.
If you want to get the index of each item in the loop, enumerate()
is useful.
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(f"Fruit index {i}: {fruit}")
Fruit index 0: apple
Fruit index 1: banana
Fruit index 2: cherry
The enumerate()
function is used along with a for
loop to iterate over the fruits
list while keeping track of the index of each element. During each iteration, enumerate(fruits)
returns a pair of the index (i
) and the value (fruit
) of the current element from the list.
If you want to run loops based on indices, you can use range()
function:
for i in range(0, 10):
print(i)
0
1
2
3
4
5
6
7
8
9
The first line for i in range(0, 10):
starts a for loop. The range(0, 10)
generates a sequence of numbers starting from 0
up to (but not including) 10
. So, the loop will iterate over the numbers 0
, 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, and 9
. During each iteration, the loop assigns the current number from the sequence to the variable i
.
Then, print(i)
prints the value of i
to the console. For the first iteration, i
will be 0
, and for subsequent iterations, i
will take on the values 1
, 2
, 3
, …, and 9
.
You can also iterate through items in a dictionary.
stocks = {"apple": 5, "banana": 3, "orange":8}
for fruit, num in stocks.items():
print(f"{fruit}: {num}")
apple: 5
banana: 3
orange: 8
This for
loop iterates over the items of the stocks
dictionary using the items()
method, which returns each key-value pair in the dictionary. The loop unpacks each key-value pair from the dictionary into the variables fruit
and num
, where fruit
holds the fruit name (key) and num
holds the quantity (value).
4.2 The while
loops
The while
loop is used to execute a block of code as long as a specified condition is True
. It repeats the code inside the loop until the condition becomes False
.
# Example of while loop
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Let’s break this code down into snippets:
count = 0
: This line initializes a variable count
with a value of 0
. This variable will track the current count within the while
loop.
while count < 5:
: The while
statement is a type of loop that continues executing as long as the condition specified after the while
keyword is True
. Here, the loop will continue as long as the value of count
is less than 5
.
print(f"Count is: {count}")
: Inside the while
loop, this line prints the current value of the count
variable using an f-string to format the output dynamically.
count += 1
: This line increments the value of the count
variable by 1
in each iteration of the loop. It’s important to update this variable within the loop to ensure that the loop condition (count < 5
) will eventually become False
to exit the loop.
When the value of count
reaches 5
, the condition count < 5
becomes False
, and the loop exits, ending the program execution.
TIPS:
for
loop? orwhile
loop?Choosing between
for
loops andwhile
loops may be your question. We often handle data in sequences such as lists. Then you can usefor
loops because you can easily access each item in the list. When you do not know the number of iterations in advance or need to loop until a specific condition is met, then usewhile
loop.In a nutshell, choose the
for
loop first, and if it can not be used, then choose thewhile
loop.
4.3 The break
and continue
statements
Using the break
statement allows you to stop the loops when a certain condition is met.
# Using break to exit loop early
fruits = ["apple", "banana", "cherry", "", "elderberry"]
for fruit in fruits:
if fruit == "":
print("Empty data found!")
break
print(fruit)
apple
banana
cherry
Empty data found!
In this example, the loop will iterate over the fruits
list and print each fruit. If the loop encounters an empty data ""
, then the break
statement is executed, causing the loop to exit.
Within loops, you can use the continue
statement to skip the current iteration and proceed to the next iteration without executing the remaining code inside the loop.
# Using continue to skip specific iteration
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0: # Skip even numbers
continue
print(num)
1
3
5
7
9
In this example, the loop iterates over the numbers
list and uses the continue
statement to skip printing even numbers. When the condition in the if
statement is True
, continue
is executed, and the loop proceeds to the next iteration without executing the remaining code inside the loop.
TIPS
- The
break
statement is used to exit the current loop and terminate the loop entirely.- The
continue
statement is to skip the current iteration and proceed to the next one without executing the remaining code in the loop body.
5 Exercises