Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ while loop (2/2) | Loops
Learn Python from Scratch
セクション 6.  2
single

single

bookwhile loop (2/2)

メニューを表示するにはスワイプしてください

As we mentioned before, sometimes we don't exactly know the stopping condition. In that case, we first need to start an infinite loop and then specify the stopping condition. If you want to start an infinite loop, use while True.

There are two important commands in Python: break and continue. break will break the loop and go outside loop to the next line. continue will skip all the rest code inside loop and return at its beginning.

For example, imagine we have number 3 and want to reach number 6. All we can do - is to add 2 and subtract 1.

12345678910111213141516
# starting number a = 3 # let's construct while loop while True: # infinite loop if a == 6: # stopping condition print("Number", a, "reached") break # this will break loop elif a < 6: # if less, than add 2 a = a + 2 print("Adding 2... Reached", a) continue # returning to loop start else: # if greater, then subtract 1 a = a - 1 print("Subtracting 1... Reached", a) continue # returning to loop start
copy

If we didn't specify break in the first if, then we got an infinite loop, because 6 is not satisfying any other condition but the first one. In that case, it printed us "Number 6 reached" infinite times.

タスク

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

Using while loop and continue/break commands construct the next program:

Given number a = -7. At each step if the number is negative, you need to print "a is negative, and =" and value, and then add 4 and continue the loop. If the number is positive, you need to print "a is positive, and =" and its value after = sign. In that case you need to subtract 3 and continue the loop. If the number is zero - you need to print "Finally a is zero!" and break the loop.

解答

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

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

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

セクション 6.  2
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt