Explore the for loop and the while loop.
1. Explain when to use these different types of loops.
2. How do you include a ‘loop’ structure programming in Python?
3. How do you control a loop?
4. Provide sample code to demonstrate loops
. When to Use for
vs. while
Loops:
for
Loop:
for
loop when you know in advance how many times you need to iterate.while
Loop:
while
loop when you need to repeat a block of code until a certain condition is met.2. How to Include Loop Structures in Python:
for
Loop:
for
loop uses the for
keyword, followed by a variable name, the in
keyword, and the iterable object.for variable in iterable:
while
Loop:
while
loop uses the while
keyword, followed by a condition.while condition:
3. How to Control a Loop:
break
Statement:
break
statement immediately terminates the loop, regardless of whether the loop’s condition is still true.continue
Statement:
continue
statement skips the rest of the current iteration and moves to the next iteration of the loop.while
loop, the condition that controls the loop must eventually become false. This is typically done by modifying a variable that is part of the conditional statement.for
loop, the loop control is managed by the iterable object.4. Sample Code Demonstrations:
# for loop example: iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# for loop example: using range() to repeat a task
for i in range(5): # range(5) generates numbers 0, 1, 2, 3, 4
print("Iteration:", i)
# while loop example: repeating until a condition is met
count = 0
while count < 5:
print("Count:", count)
count += 1
# while loop example: with user input and break
while True:
user_input = input("Enter 'exit' to quit: ")
if user_input.lower() == "exit":
break
print("You entered:", user_input)
# for loop example: with continue
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print("Odd number:", i)
# while loop example with break
number = 0
while number <10:
number += 1
if number == 5:
break;
print(number)
Key takeaways from the examples:
for
loop is excellent for iterating through collections.range()
function is very useful to create a sequence of numbers for a for
loop.while
loop continues as long as its condition remains true.break
and continue
provide fine-grained control over loop execution.while
loops will eventually end.