Is there a better solution to write a while loop that runs forever if the argument is 0 or just runs n times if the argument is an arbitrary n larger 0 than this:
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
you can probably combine the lambda into:
check = lambda x: True if x > 0 or options.num == 0 else False
but then you will still have to count down x, unless you put a if before that.
How about:
n = options.num
while (options.num == 0) or (n > 0):
print("Hello World")
n -= 1
Essentially we have an infinite loop if x == 0
or we only run n
times.
I think this is quite expressive:
if x==0:
x = float("inf") # user says 0 but means infinity
while x>0:
print "something"
x -= 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With