In the for statement, often include an if statement (exception handling, etc.) + break
.
At that time, I would like to know if it was break
or ended normally (it goes around all the elements).
When it ends with break
, you can write the process in the if statement.
On the contrary, how to write the process when all the elements are visited?
Reference URL: http://docs.python.jp/3.4/reference/compound_stmts.html
When a break statement is executed in the first suite, it exits the loop without executing the suite in the else clause. When the continue statement is executed in the first suite, it skips the execution of the remaining statements in the suite and moves on to the next element, or if there are no more elements, it goes to the else clause. I will move.
The suite here is the processing in the for statement (probably) If you don't look at everything when you learn the basics, you will overlook this. If you use else when the for statement ends, it will be executed when it ends normally. How to use is the same as if-else.
The code below is a code that outputs whether the num_list contains a string (useless) The first list I passed for testing included a string.
check_num.py
import random
def num_check(num_list):
print(repr(num_list))
for i in num_list:
if type(i) == str:
print('Contains characters')
break
else: print('Does not contain characters.')
if __name__ == '__main__':
num_check([random.randint(-1, 100) if i != 5 else str(i) for i in range(10)])
num_check([random.randint(-1, 100) for _ in range(10)])
output.
$ python check_num.py
[78, 3, 2, 82, 52, '5', 20, 41, 66, 98]
Contains characters.
[96, 10, 92, 72, 95, 9, 64, 60, 92, 77]
Does not contain characters.
If you use else, you can process when it ends normally. By the way, even in the while statement, the processing when the loop is exited in the first conditional statement can be expressed using else in the same way.
Recommended Posts