loops¶
for and for else loop¶
- In Python,
for
loops provide a concise way to iterate over sequences (likelists
,tuples
, orstrings
) and execute a block of code for each item in the sequence. Additionally,for
loops can have an optionalelse
clause that executes only if the loop completes normally (without encountering abreak
statement).
In [ ]:
Copied!
# Basic for Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Basic for Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
- This loop iterates over the
fruits
list. - In each iteration, the variable
fruit
takes on the value of the current item in the list ("apple", "banana", "cherry" in this case). - The indented code block (printing the fruit name) is executed for each item.
In [ ]:
Copied!
# Looping with Index
numbers = [1, 2, 3, 4]
for index, number in enumerate(numbers):
print(f"Index: {index}, Number: {number}")
# Looping with Index
numbers = [1, 2, 3, 4]
for index, number in enumerate(numbers):
print(f"Index: {index}, Number: {number}")
- This example uses
enumerate(numbers)
to get both the index (position) and the value in each iteration. index
takes on the index of the current item, whilenumber
holds the actual value.
In [ ]:
Copied!
# Looping over a Range
for i in range(5): # Range from 0 (inclusive) to 5 (exclusive)
print(i)
# Looping over a Range
for i in range(5): # Range from 0 (inclusive) to 5 (exclusive)
print(i)
- The
range(n)
function generates a sequence of numbers from 0 (inclusive) to n-1 (exclusive). - This loop iterates 5 times, printing each number from 0 to 4.
In [ ]:
Copied!
# for-else Loop
found = False
for number in range(10):
if number == 5:
found = True
break
if found:
print("Number 5 found in the list!")
else:
print("Number 5 not found.")
# for-else Loop
found = False
for number in range(10):
if number == 5:
found = True
break
if found:
print("Number 5 found in the list!")
else:
print("Number 5 not found.")
- The
else
clause is optional and only executes if the loop completes normally (withoutbreak
). - In this example, if
number
is 5,found
becomes True, and the loop breaks usingbreak
. - Since the loop didn't complete normally, the
else
block doesn't execute. - If
number
never reaches 5, the loop finishes iterating, and theelse
block prints that 5 wasn't found. - Key Points
- Use
for
loops to efficiently iterate over sequences and process items one by one. - You can optionally include an index along with the item in each iteration.
range(n)
is useful for iterating a specific number of times.- The
else
clause provides a way to execute code only when the loop completes normally (nobreak
).
- Use
while loop¶
- A while loop in Python is a control flow statement that repeatedly executes a block of code as long as a certain condition is true.
while condition: # code to be executed while the condition is true
while
keyword- This keyword marks the beginning of the while loop.
condition
- This is a Boolean expression that determines whether the loop continues to execute.
- The loop keeps running as long as the condition evaluates to True. Once the condition becomes False, the loop terminates.
- Indented block
- The code you want to execute repeatedly goes here.
- The indentation level defines the code block that belongs to the loop.
- Make sure all the code you want to repeat is indented at the same level.
- Common Uses of While Loops
- Iterating a specific number of times (using a counter variable).
- Reading user input until a specific condition is met (e.g., entering a valid value).
- Processing data from a file line by line as long as there's more data to read.
- Simulating games or other interactive applications where the loop continues until a specific event occurs (e.g., winning or losing a game).
In [ ]:
Copied!
count = 0
while count < 5:
print("Count:", count)
count += 1 # Increment count by 1
count = 0
while count < 5:
print("Count:", count)
count += 1 # Increment count by 1
- Explanation
- The loop variable
count
is initialized to 0. - The
while
condition checks ifcount
is less than 5 (count < 5
). - As long as the condition is
True
(initially and untilcount
reaches 4), the indented code block executes. - Inside the block,
count
is printed, and then incremented by 1 usingcount += 1
. - After each iteration, the condition is checked again. Once
count
becomes 5, the condition becomesFalse
, and the loop terminates.
- The loop variable
break, continue, pass¶
- These three (
break
,continue
, andpass
) are control flow statements that influence the execution flow within loops (and conditionally in the case ofpass
) in Python. break
: Thebreak
statement abruptly terminates the loop it's within, regardless of the loop condition's state (even if it's stillTrue
). Control jumps to the statement following the loop's complete execution- Below code iterates from 0 to 9, but upon reaching 5, the break statement exits the loop, printing only numbers 0 to 4.
In [ ]:
Copied!
for number in range(10):
if number == 5:
print("Found 5, breaking out of the loop!")
break
print(number)
for number in range(10):
if number == 5:
print("Found 5, breaking out of the loop!")
break
print(number)
continue
: Thecontinue
statement skips the current iteration of the loop and immediately jumps to the beginning of the next iteration. The remaining code within the current iteration is not executed.- Below code loop iterates from 0 to 9. The
continue
statement skips even numbers, resulting in only odd numbers being printed (1, 3, 5, 7, 9).
- Below code loop iterates from 0 to 9. The
In [ ]:
Copied!
for number in range(10):
if number % 2 == 0: # Skip even numbers
continue
print(number)
for number in range(10):
if number % 2 == 0: # Skip even numbers
continue
print(number)
pass
: Thepass
statement acts as a placeholder, essentially doing nothing. It's used syntactically when a statement is required but you don't want any action to occur at that point.- Below code
pass
fills the empty block, allowing the loop to function correctly without any action within the loop itself.
- Below code
In [ ]:
Copied!
for number in range(5):
pass # Placeholder, no action
print("Loop finished!")
for number in range(5):
pass # Placeholder, no action
print("Loop finished!")
- Points to remember
break
exits the entire loop.continue
skips the current iteration and moves to the next.pass
is a null statement, acting as a placeholder.- These statements are most commonly used within loops, but
pass
can also be used in conditional statements (likeif
statements) in specific situations.