Newbie getting desperate with for
orgnut at yahoo.com
Thu Feb 17 23:15:57 EST 2011
On 02/17/2011 12:27 AM, Werner wrote:
> I have a trivially simple piece of code called timewaster.py:
> while True:
> i = 0
> for i in range(10):
> It runs fine with Eric but when I try to run it from shell...
> ./timewaster.py: line 4: syntax error near unexpected token `('
> ./timewaster.py: line 4: ` for i in range(10):'
> I've tried this on openSuse 11.3 and Kubuntu 10.04, both use Python
> version 2.6.5, both show the above.
> Before I tear out my hair any more (only 3 left) I thought I'd ask here
> what I am doing wrong.
> Best Regards
> Werner Dahn
A true time waster indeed -- it's an infinite loop that will _never_ end.
Others have already about the need of the shebang line to run as a python script, but I'm
surprised no one mentioned how truly useless this code is.
The i = 0 line is totally unnecessary. The variable i is created and set to zero by the first
iteration of the for loop. The break will abort the for loop (NOT the while loop) in the first
iteration, and the 2nd through the 10th iterations will be skipped altogether.
This effectively leaves your code as:
pass # Do nothing, forever
An empty loop as a time delay can occasionally be useful, but as a practical matter, a for loop
with only 10 (empty/pass) iterations is probably too short for anything useful. Instead of
being empty, do some more complex (but ignored) operation -- say math.sqrt() or math.sin() for
example -- and a much larger repetition count. But it's likely that does use up processor
cycles unnecessarily, although it can give you delays of fractions of seconds. If you want
delays greater than a second, check out the time.sleep() function.
-=- Larry -=-
More information about the Python-list