Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Choosing Between for and while Loops in Python | Sektion
Pythonloopar

Choosing Between for and while Loops in Python

Svep för att visa menyn

Loops are essential tools for repetitive tasks in Python, but deciding whether to use a for loop or a while loop depends on the nature of the task. Both have unique strengths that suit different scenarios.

A for loop is ideal when you know the exact number of iterations or are iterating through a sequence like a list, tuple, string, or range.

Iterating Over Sequences

When you need to process each element in a list, tuple, or string.

1234
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] for city in travel_list: print(city)

Fixed Number of Iterations

When the number of iterations is predetermined.

12
for i in range(5): print('Trip', i + 1)

When to Use while Loops

A while loop is better suited for situations where the number of iterations is unknown in advance, and the loop depends on a condition.

Condition-Based Iteration

When you want the loop to continue until a specific condition is met.

123456789
budget = 1000 travel_costs = [300, 150, 200, 400, 100] total_cost = 0 i = 0 while total_cost + travel_costs[i] <= budget: total_cost += travel_costs[i] print('Trip', i + 1, 'cost:', travel_costs[i]) i += 1

Infinite Loops with Exit Conditions

When you need an ongoing process that stops based on a condition.

while True:
    city = input("Enter a city (or 'stop' to end): ")
    if city == "stop":
        break
    print(f"City added: {city}")
Note
Note

The f before the quotation marks creates an f-string. It lets you insert variables into text using curly brackets, like {city}. You may see f-strings in other Python examples.

question mark

Modify the code to stop the loop prematurely when a single trip exceeds $400. Where should you add the break statement?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 12

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Choosing Between for and while Loops in Python

Loops are essential tools for repetitive tasks in Python, but deciding whether to use a for loop or a while loop depends on the nature of the task. Both have unique strengths that suit different scenarios.

A for loop is ideal when you know the exact number of iterations or are iterating through a sequence like a list, tuple, string, or range.

Iterating Over Sequences

When you need to process each element in a list, tuple, or string.

1234
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] for city in travel_list: print(city)

Fixed Number of Iterations

When the number of iterations is predetermined.

12
for i in range(5): print('Trip', i + 1)

When to Use while Loops

A while loop is better suited for situations where the number of iterations is unknown in advance, and the loop depends on a condition.

Condition-Based Iteration

When you want the loop to continue until a specific condition is met.

123456789
budget = 1000 travel_costs = [300, 150, 200, 400, 100] total_cost = 0 i = 0 while total_cost + travel_costs[i] <= budget: total_cost += travel_costs[i] print('Trip', i + 1, 'cost:', travel_costs[i]) i += 1

Infinite Loops with Exit Conditions

When you need an ongoing process that stops based on a condition.

while True:
    city = input("Enter a city (or 'stop' to end): ")
    if city == "stop":
        break
    print(f"City added: {city}")
Note
Note

The f before the quotation marks creates an f-string. It lets you insert variables into text using curly brackets, like {city}. You may see f-strings in other Python examples.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 12
some-alt