Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop, run forever or count down

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.

like image 669
reox Avatar asked Jul 18 '14 08:07

reox


2 Answers

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.

like image 65
James Mills Avatar answered Oct 10 '22 07:10

James Mills


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
like image 34
Emanuele Paolini Avatar answered Oct 10 '22 08:10

Emanuele Paolini