请考虑这个简单的功能:
def my_func(x):
if x > 5: print(x)
else: quit()
print('this should be printed only if x > 5')
然后如果我们循环调用这个函数:
for i in [2, 3, 4, 5, 6, 7]:
my_func(i)
预期输出:
6
this should be printed only if x > 5
7
this should be printed only if x > 5
但是
quit
实际上断开了内核的连接。
我知道以下功能可以工作,但我不想在那里打印第二个:
def my_func(x):
if x > 5:
print(x)
print('this should be printed only if x > 5')
else: pass
最后,我知道如果我将循环放在函数内,我可以使用
continue
或 break
但我更喜欢保持函数简单,而不是将函数调用放在循环中。
那么,第一个函数需要改变什么才能达到预期的输出?
确实,
quit()
将退出应用程序。 如果您想要从函数返回,return
正是这样做的:
def my_func(x):
if x > 5: print(x)
else: return
print('this should be printed only if x > 5')
for i in [2, 3, 4, 5, 6, 7]:
my_func(i)