Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
While Loops | Loops
Introduction to Python Video Course
course content

Contenido del Curso

Introduction to Python Video Course

Introduction to Python Video Course

1. Getting Started
2. Variables and Types
3. Conditional Statements
4. Other Data Types
5. Loops
6. Functions

While Loops

while loops are the key tool for handling indefinite iteration, which is useful in scenarios where the number of iterations isn't known in advance, like monitoring inventory levels until they meet a specific threshold.

Watch as Alex demonstrates how to use while loops to handle dynamic situations:

A while loop in Python continuously runs a block of code as long as a specified condition remains True.

Syntax

To start a while loop, you define a counter variable and follow it with the while keyword and a boolean condition. The condition is followed by a colon :, which indicates the start of the loop's code block.

The loop will execute repeatedly until the condition becomes False. Typically, the counter variable is updated inside the loop to eventually make the condition False and stop the loop.

Take this while loop for example:

1234567891011
# Handling a queue at a grocery store checkout queue_length = 5 # Initial number of people in the queue while queue_length > 0: # Start the `while` loop as long as the queue isn't empty print(f"Current queue size: {queue_length}") # Simulate serving a customer print("Serving the next customer...") # Decrease the queue length by 1 as a customer leaves # The `-=` operator is a shortcut for `queue_length = queue_length - 1` queue_length -= 1
copy

In this example, queue_length acts as our counter variable, starting at 5. With each loop iteration, the value of queue_length decreases by 1 until it reaches 0. At that point, the loop ends because the condition 0 > 0 evaluates to False.

Note

It is crucial to update the counter variable inside the loop to eventually meet the condition for stopping the loop. Without this, the loop will run infinitely, preventing any further code from executing.

Example Application

Imagine you're managing the milk stock in a grocery store. You need to ensure the stock doesn't drop below a certain level, and when it does, you should reorder to maintain the stock level.

A while loop is useful in this situation because it allows you to restock milk in increments over several iterations until the stock reaches the desired level. Without a while loop, you'd need to calculate the exact amount of milk to reorder all at once.

For instance, consider that a store worker can only restock a fixed amount of milk in one trip (e.g., 20 packs per restock). If the stock isn't fully replenished, the worker returns to the warehouse to bring another batch of milk.

123456789101112131415161718
# Initial amount of milk in stock milk_stock = 15 # Minimum stock level before reordering is necessary min_stock = 50 # Quantity a worker can restock at one time reorder_quantity = 20 # Start the loop to restock milk until the stock exceeds the minimum required level while milk_stock < min_stock: # If the loop is running, the condition is `True`, indicating we need more milk print(f"Milk stock is low: {milk_stock} units remaining.") # Simulate the process of reordering milk print("Restocking milk...") # Increase the stock by the quantity the worker can bring in one trip milk_stock += reorder_quantity # Output the final stock level after restocking is complete print(f"Milk stock updated: {milk_stock} units, which is now sufficient.")
copy

Note

milk_stock += reorder_quantity is equivalent to milk_stock = milk_stock + reorder_quantity. It's simply a more concise and readable way to express the same operation.

The flowchart above illustrates the logic behind the while loop used for managing the milk inventory. Notice how the counter variable milk_stock, starting at 15, is incremented by the reorder_quantity with each loop iteration.

The loop keeps running until milk_stock surpasses the min_stock threshold of 50, at which point it stops.

Tarea

In this task, you will manage grocery store inventory by using loops to restock products until they meet their minimum stock levels, similar to the previous example.

This time, you will set up loops for three items — Bread, Eggs, and Apples — and update their stock using the restock quantities stored in the dictionary, alongside current stock and minimum stock. After restocking, you will print the updated inventory.

  1. Use a while loop to check if "Bread"'s stock is below the required minimum. If it is, restock by adding the specified restock quantity.
  2. Similarly, use a while loop to check and restock "Eggs" if needed, adding the restock quantity when the stock is below the minimum.
  3. Apply the same logic to restock "Apples" with a while loop.
  4. After all items are restocked, print the final inventory with updated stock levels. Ensure you correctly unpack the dictionary values in the for loop when printing.

Note

The code introduces new ways of formatting strings for better readability:

  • Inside f-strings, single quotes ' can be used within double-quoted strings. For example: f"Bread stock is low: {inventory['Bread'][0]} units.". The outer string uses double quotes, while 'Bread' uses single quotes to avoid conflicts.
  • You can insert a new line in the output using the escape sequence \n, like "First line.\nSecond line." which will split the output into two lines.

Tarea

In this task, you will manage grocery store inventory by using loops to restock products until they meet their minimum stock levels, similar to the previous example.

This time, you will set up loops for three items — Bread, Eggs, and Apples — and update their stock using the restock quantities stored in the dictionary, alongside current stock and minimum stock. After restocking, you will print the updated inventory.

  1. Use a while loop to check if "Bread"'s stock is below the required minimum. If it is, restock by adding the specified restock quantity.
  2. Similarly, use a while loop to check and restock "Eggs" if needed, adding the restock quantity when the stock is below the minimum.
  3. Apply the same logic to restock "Apples" with a while loop.
  4. After all items are restocked, print the final inventory with updated stock levels. Ensure you correctly unpack the dictionary values in the for loop when printing.

Note

The code introduces new ways of formatting strings for better readability:

  • Inside f-strings, single quotes ' can be used within double-quoted strings. For example: f"Bread stock is low: {inventory['Bread'][0]} units.". The outer string uses double quotes, while 'Bread' uses single quotes to avoid conflicts.
  • You can insert a new line in the output using the escape sequence \n, like "First line.\nSecond line." which will split the output into two lines.

Cambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones

¿Todo estuvo claro?

Sección 5. Capítulo 2
toggle bottom row

While Loops

while loops are the key tool for handling indefinite iteration, which is useful in scenarios where the number of iterations isn't known in advance, like monitoring inventory levels until they meet a specific threshold.

Watch as Alex demonstrates how to use while loops to handle dynamic situations:

A while loop in Python continuously runs a block of code as long as a specified condition remains True.

Syntax

To start a while loop, you define a counter variable and follow it with the while keyword and a boolean condition. The condition is followed by a colon :, which indicates the start of the loop's code block.

The loop will execute repeatedly until the condition becomes False. Typically, the counter variable is updated inside the loop to eventually make the condition False and stop the loop.

Take this while loop for example:

1234567891011
# Handling a queue at a grocery store checkout queue_length = 5 # Initial number of people in the queue while queue_length > 0: # Start the `while` loop as long as the queue isn't empty print(f"Current queue size: {queue_length}") # Simulate serving a customer print("Serving the next customer...") # Decrease the queue length by 1 as a customer leaves # The `-=` operator is a shortcut for `queue_length = queue_length - 1` queue_length -= 1
copy

In this example, queue_length acts as our counter variable, starting at 5. With each loop iteration, the value of queue_length decreases by 1 until it reaches 0. At that point, the loop ends because the condition 0 > 0 evaluates to False.

Note

It is crucial to update the counter variable inside the loop to eventually meet the condition for stopping the loop. Without this, the loop will run infinitely, preventing any further code from executing.

Example Application

Imagine you're managing the milk stock in a grocery store. You need to ensure the stock doesn't drop below a certain level, and when it does, you should reorder to maintain the stock level.

A while loop is useful in this situation because it allows you to restock milk in increments over several iterations until the stock reaches the desired level. Without a while loop, you'd need to calculate the exact amount of milk to reorder all at once.

For instance, consider that a store worker can only restock a fixed amount of milk in one trip (e.g., 20 packs per restock). If the stock isn't fully replenished, the worker returns to the warehouse to bring another batch of milk.

123456789101112131415161718
# Initial amount of milk in stock milk_stock = 15 # Minimum stock level before reordering is necessary min_stock = 50 # Quantity a worker can restock at one time reorder_quantity = 20 # Start the loop to restock milk until the stock exceeds the minimum required level while milk_stock < min_stock: # If the loop is running, the condition is `True`, indicating we need more milk print(f"Milk stock is low: {milk_stock} units remaining.") # Simulate the process of reordering milk print("Restocking milk...") # Increase the stock by the quantity the worker can bring in one trip milk_stock += reorder_quantity # Output the final stock level after restocking is complete print(f"Milk stock updated: {milk_stock} units, which is now sufficient.")
copy

Note

milk_stock += reorder_quantity is equivalent to milk_stock = milk_stock + reorder_quantity. It's simply a more concise and readable way to express the same operation.

The flowchart above illustrates the logic behind the while loop used for managing the milk inventory. Notice how the counter variable milk_stock, starting at 15, is incremented by the reorder_quantity with each loop iteration.

The loop keeps running until milk_stock surpasses the min_stock threshold of 50, at which point it stops.

Tarea

In this task, you will manage grocery store inventory by using loops to restock products until they meet their minimum stock levels, similar to the previous example.

This time, you will set up loops for three items — Bread, Eggs, and Apples — and update their stock using the restock quantities stored in the dictionary, alongside current stock and minimum stock. After restocking, you will print the updated inventory.

  1. Use a while loop to check if "Bread"'s stock is below the required minimum. If it is, restock by adding the specified restock quantity.
  2. Similarly, use a while loop to check and restock "Eggs" if needed, adding the restock quantity when the stock is below the minimum.
  3. Apply the same logic to restock "Apples" with a while loop.
  4. After all items are restocked, print the final inventory with updated stock levels. Ensure you correctly unpack the dictionary values in the for loop when printing.

Note

The code introduces new ways of formatting strings for better readability:

  • Inside f-strings, single quotes ' can be used within double-quoted strings. For example: f"Bread stock is low: {inventory['Bread'][0]} units.". The outer string uses double quotes, while 'Bread' uses single quotes to avoid conflicts.
  • You can insert a new line in the output using the escape sequence \n, like "First line.\nSecond line." which will split the output into two lines.

Tarea

In this task, you will manage grocery store inventory by using loops to restock products until they meet their minimum stock levels, similar to the previous example.

This time, you will set up loops for three items — Bread, Eggs, and Apples — and update their stock using the restock quantities stored in the dictionary, alongside current stock and minimum stock. After restocking, you will print the updated inventory.

  1. Use a while loop to check if "Bread"'s stock is below the required minimum. If it is, restock by adding the specified restock quantity.
  2. Similarly, use a while loop to check and restock "Eggs" if needed, adding the restock quantity when the stock is below the minimum.
  3. Apply the same logic to restock "Apples" with a while loop.
  4. After all items are restocked, print the final inventory with updated stock levels. Ensure you correctly unpack the dictionary values in the for loop when printing.

Note

The code introduces new ways of formatting strings for better readability:

  • Inside f-strings, single quotes ' can be used within double-quoted strings. For example: f"Bread stock is low: {inventory['Bread'][0]} units.". The outer string uses double quotes, while 'Bread' uses single quotes to avoid conflicts.
  • You can insert a new line in the output using the escape sequence \n, like "First line.\nSecond line." which will split the output into two lines.

Cambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones

¿Todo estuvo claro?

Sección 5. Capítulo 2
toggle bottom row

While Loops

while loops are the key tool for handling indefinite iteration, which is useful in scenarios where the number of iterations isn't known in advance, like monitoring inventory levels until they meet a specific threshold.

Watch as Alex demonstrates how to use while loops to handle dynamic situations:

A while loop in Python continuously runs a block of code as long as a specified condition remains True.

Syntax

To start a while loop, you define a counter variable and follow it with the while keyword and a boolean condition. The condition is followed by a colon :, which indicates the start of the loop's code block.

The loop will execute repeatedly until the condition becomes False. Typically, the counter variable is updated inside the loop to eventually make the condition False and stop the loop.

Take this while loop for example:

1234567891011
# Handling a queue at a grocery store checkout queue_length = 5 # Initial number of people in the queue while queue_length > 0: # Start the `while` loop as long as the queue isn't empty print(f"Current queue size: {queue_length}") # Simulate serving a customer print("Serving the next customer...") # Decrease the queue length by 1 as a customer leaves # The `-=` operator is a shortcut for `queue_length = queue_length - 1` queue_length -= 1
copy

In this example, queue_length acts as our counter variable, starting at 5. With each loop iteration, the value of queue_length decreases by 1 until it reaches 0. At that point, the loop ends because the condition 0 > 0 evaluates to False.

Note

It is crucial to update the counter variable inside the loop to eventually meet the condition for stopping the loop. Without this, the loop will run infinitely, preventing any further code from executing.

Example Application

Imagine you're managing the milk stock in a grocery store. You need to ensure the stock doesn't drop below a certain level, and when it does, you should reorder to maintain the stock level.

A while loop is useful in this situation because it allows you to restock milk in increments over several iterations until the stock reaches the desired level. Without a while loop, you'd need to calculate the exact amount of milk to reorder all at once.

For instance, consider that a store worker can only restock a fixed amount of milk in one trip (e.g., 20 packs per restock). If the stock isn't fully replenished, the worker returns to the warehouse to bring another batch of milk.

123456789101112131415161718
# Initial amount of milk in stock milk_stock = 15 # Minimum stock level before reordering is necessary min_stock = 50 # Quantity a worker can restock at one time reorder_quantity = 20 # Start the loop to restock milk until the stock exceeds the minimum required level while milk_stock < min_stock: # If the loop is running, the condition is `True`, indicating we need more milk print(f"Milk stock is low: {milk_stock} units remaining.") # Simulate the process of reordering milk print("Restocking milk...") # Increase the stock by the quantity the worker can bring in one trip milk_stock += reorder_quantity # Output the final stock level after restocking is complete print(f"Milk stock updated: {milk_stock} units, which is now sufficient.")
copy

Note

milk_stock += reorder_quantity is equivalent to milk_stock = milk_stock + reorder_quantity. It's simply a more concise and readable way to express the same operation.

The flowchart above illustrates the logic behind the while loop used for managing the milk inventory. Notice how the counter variable milk_stock, starting at 15, is incremented by the reorder_quantity with each loop iteration.

The loop keeps running until milk_stock surpasses the min_stock threshold of 50, at which point it stops.

Tarea

In this task, you will manage grocery store inventory by using loops to restock products until they meet their minimum stock levels, similar to the previous example.

This time, you will set up loops for three items — Bread, Eggs, and Apples — and update their stock using the restock quantities stored in the dictionary, alongside current stock and minimum stock. After restocking, you will print the updated inventory.

  1. Use a while loop to check if "Bread"'s stock is below the required minimum. If it is, restock by adding the specified restock quantity.
  2. Similarly, use a while loop to check and restock "Eggs" if needed, adding the restock quantity when the stock is below the minimum.
  3. Apply the same logic to restock "Apples" with a while loop.
  4. After all items are restocked, print the final inventory with updated stock levels. Ensure you correctly unpack the dictionary values in the for loop when printing.

Note

The code introduces new ways of formatting strings for better readability:

  • Inside f-strings, single quotes ' can be used within double-quoted strings. For example: f"Bread stock is low: {inventory['Bread'][0]} units.". The outer string uses double quotes, while 'Bread' uses single quotes to avoid conflicts.
  • You can insert a new line in the output using the escape sequence \n, like "First line.\nSecond line." which will split the output into two lines.

Tarea

In this task, you will manage grocery store inventory by using loops to restock products until they meet their minimum stock levels, similar to the previous example.

This time, you will set up loops for three items — Bread, Eggs, and Apples — and update their stock using the restock quantities stored in the dictionary, alongside current stock and minimum stock. After restocking, you will print the updated inventory.

  1. Use a while loop to check if "Bread"'s stock is below the required minimum. If it is, restock by adding the specified restock quantity.
  2. Similarly, use a while loop to check and restock "Eggs" if needed, adding the restock quantity when the stock is below the minimum.
  3. Apply the same logic to restock "Apples" with a while loop.
  4. After all items are restocked, print the final inventory with updated stock levels. Ensure you correctly unpack the dictionary values in the for loop when printing.

Note

The code introduces new ways of formatting strings for better readability:

  • Inside f-strings, single quotes ' can be used within double-quoted strings. For example: f"Bread stock is low: {inventory['Bread'][0]} units.". The outer string uses double quotes, while 'Bread' uses single quotes to avoid conflicts.
  • You can insert a new line in the output using the escape sequence \n, like "First line.\nSecond line." which will split the output into two lines.

Cambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones

¿Todo estuvo claro?

while loops are the key tool for handling indefinite iteration, which is useful in scenarios where the number of iterations isn't known in advance, like monitoring inventory levels until they meet a specific threshold.

Watch as Alex demonstrates how to use while loops to handle dynamic situations:

A while loop in Python continuously runs a block of code as long as a specified condition remains True.

Syntax

To start a while loop, you define a counter variable and follow it with the while keyword and a boolean condition. The condition is followed by a colon :, which indicates the start of the loop's code block.

The loop will execute repeatedly until the condition becomes False. Typically, the counter variable is updated inside the loop to eventually make the condition False and stop the loop.

Take this while loop for example:

1234567891011
# Handling a queue at a grocery store checkout queue_length = 5 # Initial number of people in the queue while queue_length > 0: # Start the `while` loop as long as the queue isn't empty print(f"Current queue size: {queue_length}") # Simulate serving a customer print("Serving the next customer...") # Decrease the queue length by 1 as a customer leaves # The `-=` operator is a shortcut for `queue_length = queue_length - 1` queue_length -= 1
copy

In this example, queue_length acts as our counter variable, starting at 5. With each loop iteration, the value of queue_length decreases by 1 until it reaches 0. At that point, the loop ends because the condition 0 > 0 evaluates to False.

Note

It is crucial to update the counter variable inside the loop to eventually meet the condition for stopping the loop. Without this, the loop will run infinitely, preventing any further code from executing.

Example Application

Imagine you're managing the milk stock in a grocery store. You need to ensure the stock doesn't drop below a certain level, and when it does, you should reorder to maintain the stock level.

A while loop is useful in this situation because it allows you to restock milk in increments over several iterations until the stock reaches the desired level. Without a while loop, you'd need to calculate the exact amount of milk to reorder all at once.

For instance, consider that a store worker can only restock a fixed amount of milk in one trip (e.g., 20 packs per restock). If the stock isn't fully replenished, the worker returns to the warehouse to bring another batch of milk.

123456789101112131415161718
# Initial amount of milk in stock milk_stock = 15 # Minimum stock level before reordering is necessary min_stock = 50 # Quantity a worker can restock at one time reorder_quantity = 20 # Start the loop to restock milk until the stock exceeds the minimum required level while milk_stock < min_stock: # If the loop is running, the condition is `True`, indicating we need more milk print(f"Milk stock is low: {milk_stock} units remaining.") # Simulate the process of reordering milk print("Restocking milk...") # Increase the stock by the quantity the worker can bring in one trip milk_stock += reorder_quantity # Output the final stock level after restocking is complete print(f"Milk stock updated: {milk_stock} units, which is now sufficient.")
copy

Note

milk_stock += reorder_quantity is equivalent to milk_stock = milk_stock + reorder_quantity. It's simply a more concise and readable way to express the same operation.

The flowchart above illustrates the logic behind the while loop used for managing the milk inventory. Notice how the counter variable milk_stock, starting at 15, is incremented by the reorder_quantity with each loop iteration.

The loop keeps running until milk_stock surpasses the min_stock threshold of 50, at which point it stops.

Tarea

In this task, you will manage grocery store inventory by using loops to restock products until they meet their minimum stock levels, similar to the previous example.

This time, you will set up loops for three items — Bread, Eggs, and Apples — and update their stock using the restock quantities stored in the dictionary, alongside current stock and minimum stock. After restocking, you will print the updated inventory.

  1. Use a while loop to check if "Bread"'s stock is below the required minimum. If it is, restock by adding the specified restock quantity.
  2. Similarly, use a while loop to check and restock "Eggs" if needed, adding the restock quantity when the stock is below the minimum.
  3. Apply the same logic to restock "Apples" with a while loop.
  4. After all items are restocked, print the final inventory with updated stock levels. Ensure you correctly unpack the dictionary values in the for loop when printing.

Note

The code introduces new ways of formatting strings for better readability:

  • Inside f-strings, single quotes ' can be used within double-quoted strings. For example: f"Bread stock is low: {inventory['Bread'][0]} units.". The outer string uses double quotes, while 'Bread' uses single quotes to avoid conflicts.
  • You can insert a new line in the output using the escape sequence \n, like "First line.\nSecond line." which will split the output into two lines.

Cambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
Sección 5. Capítulo 2
Cambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
We're sorry to hear that something went wrong. What happened?
some-alt