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
セクション 5.  3
single

single

bookWhile 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.

A simple syntax looks like this:

1234
counter = 1 while counter <= 3: print(counter) counter += 1
copy

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
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.

タスク

スワイプしてコーディングを開始

Simulate a grocery store restocking process using a while loop.

  • Use a while loop to keep restocking until the stock level reaches or exceeds the restock_goal.
  • In each iteration, increase the stock by restock_amount.
  • After the loop completes, print "Restocking complete!" and then print the final stock value.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  3
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt