Python Functions, Files, and Dictionaries5: while statement

 

  • 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?

image showing a rectangle with "code block" written on it on top. Then, text that read "while {condition}": followed by an indented block with "..." written on it. break is then written and another indented block is placed after the phrase break, which has "... (skipped)" written on it. Finally, an unindented block belonging to code outside the while loop is at the bottom. It says "code block". An arrow points from the word break to the unindented block at the bottom and the phrase "break out of the loop" is written.

image showing a rectangle with "code block" written on it on top. Then, text that read "while {condition}": followed by an indented block with "..." written on it. continue is then written and another indented block is placed after the phrase continue, which has "... (skipped)" written on it. Finally, an unindented block belonging to code outside the while loop is at the bottom. It says "code block". An arrow points from the word continue to the while conditional statement at the top of the while loop. The phrase "continue at the start of the loop" is written.

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

 

コメント