[Tutor] Help on Python Looping Please
Dave Angel
davea at ieee.org
Thu Feb 24 17:22:10 CET 2011
On 01/-10/-28163 02:59 PM, pyhx0r wrote:
> Dear All,
>
>
> <snip>
> multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
> for suffix in SUFFIXES[multiple]:
> size /= multiple
> if size< multiple:
> return '{0:.1f} {1}'.format(size, suffix)
> <snip>
>
> I’ve shorted the code be:
>
>
>>>> SUFFIXES = {1000: ['KB','MB','GB'],
>
> 1024: ['KiB','MiB','GiB']}
>>>> multiple = 1000
>>>> size = 2300
>>>> for suffix in SUFFIXES[multiple]:
> size /= multiple
> if size< multiple:
> '{0:.1f} {1}'.format(size, suffix)
>
> <snip>
>
>
> *Why do in my code, it loops to all values and not in Mark Pilgrim’s code?*
>
(Is there a reason you double-spaced all that code? It makes it very
hard to read, and quite difficult to quote, since I had to delete every
other line.)
You wrote your code inline, and not as a function. And you omitted the
return statement. So the loop won't return, it'll run to completion.
Another way to exit a loop early is to use the break statement.
DaveA
More information about the Tutor
mailing list