有没有更好的解决方案来编写while循环,如果参数为0则永久运行,或者如果参数是任意n大于0,则仅运行n次:
x = options.num # this is the argument (read by Optparse)
if x == 0:
check = lambda x: True
else:
check = lambda x: True if x > 0 else False
while check(x):
print("Hello World")
x -= 1
您可能可以将lambda合并为:
check = lambda x: True if x > 0 or options.num == 0 else False
但是除非您在前面加上一个if,否则您仍然必须递减x。
怎么样:
n = options.num
while (options.num == 0) or (n > 0):
print("Hello World")
n -= 1
本质上,如果x == 0
或仅运行n
时间,则我们有一个无限循环。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句