Repetition in Python
Introduction to Loops in Python
Purpose of Loops:
Loops are fundamental structures in programming that allow for the execution of a sequence of code multiple times without the need to manually duplicate that code. This capability is crucial for efficiency, particularly when dealing with repetitive tasks that would be cumbersome and error-prone otherwise. Loops enable the automation of tasks such as iterating through data collections, performing calculations repeatedly, and responding to user inputs dynamically.
While Loops
Definition:
A while loop is a control structure that continuously executes a block of code as long as a specified condition evaluates to True. This makes it particularly useful for scenarios where the number of iterations is not predetermined.
Syntax:
The general syntax of a while loop is as follows:
while <expression>:
# code block to executeAll code to be executed must be indented and follows the colon after the while statement.
Boolean Expressions:
In the context of while loops, the expressions used must evaluate to either True or False. Logical conditions, including comparisons, drive the loop's iteration.
Example of a While Loop:
Counting Example: This example demonstrates how to count numbers from 1 to 10 using a while loop:
a = 0
while a < 10:
a = a + 1
print(a)Output: 1 2 3 4 5 6 7 8 9 10
Structure Components:
Keyword: while indicates the beginning of the loop.
Boolean Expression: a < 10 which checks whether a is less than 10.
Colon (:): signals the end of the while statement.
Indented Block: The instructions within the loop to be executed repeatedly.
Important Points:
Consistent indentation is crucial for the correct functioning of the loop, as Python relies on indentation to determine code blocks.
The condition is evaluated before each iteration, and if it evaluates to False, the loop terminates immediately.
Comparison Operators in Boolean Expressions:
Some common operators used in while loops include:
==: equal to!=: not equal to<: less than<=: less than or equal to>: greater than>=: greater than or equal to
More Examples of While Loops
Basic Example:
Here, we demonstrate a simple countdown:
b = 100
while b > 1:
print(b)
b = b - 10Output: 100 90 80 70 60 50 40 30 20 10
User Input Example:
This example illustrates a while loop that processes user input to generate a sequence:
output_text = ""
num = 0
target = int(input("Enter maximum number: "))
while num < target:
num = num + 1
output_text = output_text + str(num) + " "
print(output_text)Output Example: If the user inputs 5: 1 2 3 4 5
For Loops
Definition:
A for loop is a control structure that iterates over each element in a specified list or sequence of values. It is especially useful when the number of iterations is known in advance, such as the length of a list or a range of numbers.
Syntax:
The syntax for a for loop can be structured as:
for <element> in <list>:
# code block to executeStructure:
Keyword: for signifies the start of the loop.
Variable Name: This is the placeholder (often referred to as the element) that will hold each value from the list during iteration.
Keyword: in indicates which list or collection is being iterated.
List of Values: This could be any iterable object such as a list, tuple, or even a string.
Colon (:): This concludes the for statement, followed by an indented code block that will execute for each item in the list.
How it Works:
During the execution of the for loop, the element variable gets assigned values from the list one by one for each iteration, allowing for processing of each element in turn.
Examples of For Loops
Basic Example:
Here’s a simple example that prints numbers from a defined list:
for number in [1, 2, 3, 4]:
print(number)Output: 1 2 3 4
Using range() Function:
The range() function can be utilized to generate a sequence of numbers. For instance:
for n in range(1, 10):
print(n, "times 10:", n * 10)Output:1 times 10: 102 times 10: 203 times 10: 304 times 10: 405 times 10: 506 times 10: 607 times 10: 708 times 10: 809 times 10: 90
Iterating Through a List:
The following example iterates through a list of shopping items:
shopping = ['Milk', 'Bread', 'Butter', 'Cheese', 'Apples']
for i in shopping:
print("Item:", i)Output:Item: MilkItem: BreadItem: ButterItem: CheeseItem: Apples