Understanding Loops in Python
Next Topic(s):
Created:
7th of August 2024
05:56:51 PM
Modified:
24th of September 2024
04:01:39 PM
Understanding Loops in Python
In the previous section, we learned how to get input from users and display output. Now, let's dive deeper into a fundamental concept in programming: loops. Loops allow us to execute a block of code repeatedly, making tasks like generating multiplication tables much more efficient.
Types of Loops
Python supports two main types of loops: for loops and while loops. These loops can be further categorised into entry-controlled and exit-controlled loops based on when the condition is checked.
Entry-Controlled Loops
In entry-controlled loops, the condition is checked before executing the loop body. If the condition is true, the loop body is executed; otherwise, the loop terminates. The for loop and the while loop in Python are both entry-controlled loops.
Exit-Controlled Loops
In exit-controlled loops, the loop body is executed at least once before the condition is checked. Python does not have a built-in exit-controlled loop, but this behaviour can be mimicked using a while loop with a specific structure.
Example: Printing Multiplication Tables
Let's use different types of loops to print the multiplication table for a number provided by the user.
Using a for Loop
# Using a for loop to print the multiplication table
number = int(input("Enter a number to print its multiplication table: "))
print(f"Multiplication table for {number} using for loop:")
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
What is the 'f' in Python F-Strings?
The f
in f"{number} x {i} = {number * i}"
denotes an f-string, which is a feature introduced in Python 3.6.
Explanation
F-strings, or formatted string literals, provide a way to embed expressions inside string literals, using curly braces {}
.
Example
In the example:
print(f"{number} x {i} = {number * i}")
- f
indicates that the string is an f-string.
- {number}
, {i}
, and {number * i}
are expressions that are evaluated at runtime, and their values are inserted into the string at the respective places.
Hint
If number
is 5
and i
is 3
, the output will be:
5 x 3 = 15
Using a while Loop
# Using a while loop to print the multiplication table
number = int(input("Enter a number to print its multiplication table: "))
print(f"Multiplication table for {number} using while loop:")
i = 1
while i <= 10:
print(f"{number} x {i} = {number * i}")
i += 1
Using a Simulated Exit-Controlled Loop
# Using a simulated exit-controlled loop to print the multiplication table
number = int(input("Enter a number to print its multiplication table: "))
print(f"Multiplication table for {number} using simulated exit-controlled loop:")
i = 1
while True:
print(f"{number} x {i} = {number * i}")
i += 1
if i > 10:
break
Exercise: Looping Through a String
Let's apply our understanding of loops to work with strings. These exercises will help reinforce your knowledge of looping constructs.
Exercise 1: Print Each Character
# Print each character in the string "Python"
string = "Python"
print("Printing each character using a for loop:")
for char in string:
print(char)
Hint: Use a for
loop to iterate through each character in the string.
Exercise 2: Count Vowels in a String
# Count the number of vowels in a string
string = input("Enter a string: ")
vowel_count = 0
vowels = "aeiouAEIOU"
for char in string:
if char in vowels:
vowel_count += 1
print(f"Number of vowels: {vowel_count}")
Hint: Use a for
loop and an if
statement to check if each character is a vowel.
Explanation
- for Loop: The
for
loop iterates over a sequence of numbers from 1 to 10, multiplying the user-provided number by each of these values and printing the result. - while Loop: The
while
loop continues to execute as long as the condition (i <= 10
) is true. It prints the multiplication result and increments the counteri
in each iteration. - Simulated Exit-Controlled Loop: This
while
loop ensures that the loop body is executed at least once before checking the condition. After printing the result, it checks if the counter has exceeded 10 and breaks the loop if true.
Summary
Loops are powerful constructs that help us perform repetitive tasks efficiently. By understanding the differences between entry-controlled and exit-controlled loops, and knowing when to use each type, we can write more effective and efficient code. Whether using a for
loop, a while
loop, or a simulated exit-controlled loop, Python provides the flexibility to handle various looping scenarios with ease.
Key Takeaways
In this section, we learned about:
- Types of loops: entry-controlled and exit-controlled loops.
- Using
for
loops andwhile
loops in Python. - Printing multiplication tables using different types of loops.
- Looping through strings to print characters and count vowels.
By practising these concepts and exercises, you will become more proficient in using loops to solve problems efficiently.