I kinda use this:
while 1:
[body]
a lot...
But I've also read that it's not a good idea to be doing so even if you put add some way to break from the loop within the body... Any alternatives, please?
I kinda use this:
while 1:
[body]
a lot...
But I've also read that it's not a good idea to be doing so even if you put add some way to break from the loop within the body... Any alternatives, please?
There is no reason to avoid it, it's a standard construct in python which means 'repeat indefinitely'. You can use while True:
which is semantically better, but it doesn't change much.
Sometimes I have used:
always=True
while always:
# code
Sometimes when there is meaningful starting value for finishing condition you can use:
value=' '
while value:
value = raw_input('Give value or empty line to finish: ')
# process value
Repeating until break is OK, but the way you arrange to break out, continue, return (in function) or quit/exit (finish program) from inside must be well organized.
Of course there is the style of functional programming, if you prefer:
from string import digits
def my_input(msg, valid):
value = raw_input(msg).strip() # input in Python 3
if any(v not in valid for v in value):
print('Invalid entry, give again')
return my_input(msg,valid)
else:
return value
def input_and_process():
number1 = int(my_input('Give integer number 1: ', digits))
number2 = int(my_input('Give integer number 2: ', digits))
return 'Sum of %i and %i is %i' % (number1,number2,number1+number2)
print(input_and_process())
while True
, or any indefinite loop is integral to Python. All programs written in Python should have at least one of them.
Yeah. I had to move to Python to avoid that all well written C programs should have at least one GOTO. ;)
I prefer to choose Lisp style over BASIC GOTO 10's as there is not much use for TI58C key codes of Z80 assembler (check your flags). Of course there is Pascal, but Python has destroyed my ;'s and ^'s.
The most important thing is not too little and not too much documentation in code and preferably some document about the design of the program: clear entering and exits in code.
There is no reason to avoid it, it's a standard construct in python which means 'repeat indefinitely'. You can use
while True:
which is semantically better, but it doesn't change much.
I was asking because I thought it deviates from standard...
Although some constructs are more Pythonic than others, while True:
is good Pythonic code: Here it is used in a tutorial: http://docs.python.org/py3k/tutorial/controlflow.html#pass-statement . Note: Python 3.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.