return
がループの動作を制御することに重大な影響を与えています。その代わりに、return
が関数に適用され、主に関数を終了することによって、ループが途中で終了することがあります。
break
を使用して、for
ループの動作を機能自体から独立して制御できます。さらに、特定の条件(たとえば、my_func1
など)に応じて、どのアクションを取るべきかに応じて、関数内に複数のreturn
ステートメントを含めることができます。
import random
def my_func1(my_list, entry):
'''
Search a list for a specific entry. When found, terminate search
and return the list index immediately
Return False if not found
'''
print "\n Starting func1"
index = 0
for item in my_list:
if item != entry:
print "Not found yet at index: {}".format(index)
index += 1
else:
print "found item, at index {}".format(index)
print "Terminating function AND loop at same time"
return index
print "########### ENTRY NOT IN LIST. RETURN FAlSE #############"
return False
a = my_func1(['my', 'name', 'is', 'john'], 'is')
b = my_func1(['my', 'name', 'is', 'john'], 'harry')
def my_func2(my_list):
''' Iterate through a list
For first 4 items in list, double them and save result to a list that will
be returned, otherwise terminate the loop
Also, return another list of random numbers
'''
print '\n starting func2'
return_list = []
for i in range(len(my_list)):
if i < 4:
print 'Value of i is {}'.format(i)
return_list.append(my_list[i] * 2)
else:
print 'terminating for loop, but ** keep the function going **'
break
other_list = [random.randint(1, 10) for x in range(10)]
print 'Returning both lists'
return return_list, other_list
c = my_func2([x for x in range(10)])
2番目のバージョンの 'for'ループ反復の残りの部分には、*到達する瞬間がありますか? –
これは、Pythonで何がブロックになるかを理解することになります。どのようにインデントが 'for'ループの一部か' product_list'関数を決定するのか理解していますか? –
'return'は関数の実行を停止させ、通常は' for'ループを使用してコードを複数回実行します。 'for'ループの内側に' return'を置くと、コードは最初の 'for'繰り返しの直後に実行を停止するので、' for'ループの外側に置いておきたいのです。 – ov1d1u