- To apply the while loop for indefinite iteration
- To be able to identify while loops that are likely to be infinite loops
infinite loopしないように注意。
もし「あ、これinfinite loopしてる」と思うなら、printして進捗を見るといい。
大変だという話。
What you will notice here is that the while loop is more work for you — the programmer — than the equivalent for loop. When using a while loop you have to control the loop variable yourself. You give it an initial value, test for completion, and then make sure you change something in the body so that the loop terminates. That also makes a while loop harder to read and understand than the equivalent for loop. So, while you can implement definite iteration with a while loop, it’s not a good idea to do that. Use a for loop whenever it will be known at the beginning of the iteration process how many times the block of code needs to be executed.
こんな感じ
while statementは関数でないのでそれ自体returnいらない
eve_nums = []
counter = 0
while counter < 15:
if counter % 2 == 0:
eve_nums.append(counter)
counter = counter + 1
#return eve_nums
print(eve_nums)
これはwhileの下にreturnあるけど、関数の中にwhileがあるからそうなっている。
a listener loop
手動で0が入力されるまでwhileを繰り返す。繰り返すたび入力を求める。
if を使うとこうなる。
的確な入力が得られるまで聴き続けるコード
continue or break?
x = 12
while x < 30:
if x % 2 == 0:
x += 3
print(“x += 3”)
continue #if x % 2 == 0:に引っ掛かったらここで止まってwhileに戻る。
if x % 3 == 0: #continueがなかったら、xが6の倍数だと同時にこっちにも来る。
x += 5
print(“x += 5”)
else:
x += 1
print(“x += 1”)
print(“Done with our loop! X has the value: ” + str(x))
コメント