[Tutor] Help on Python Looping Please
pyhx0r
pyhx0r at gmail.com
Thu Feb 24 15:52:12 CET 2011
Dear All,
I’m new in programming and I’m studying Python now. I use Python 3.1.2 and
learn from Dive Into Python 3 book (Mark Pilgrim, Thank you very much for
him). I’ve learned list, tuple, set, dictionary and little bit about
looping. I’m so confused about looping in first Python Program in that book
(humanize.py), it’s the code:
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, a_kilobyte_is_1024_bytes=True):
'''Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000
Returns: string
'''
if size < 0:
raise ValueError('number must be non-negative')
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)
raise ValueError('number too large')
if __name__ == '__main__':
print(approximate_size(1000000000000, False))
print(approximate_size(1000000000000))
Result:
1.0 TB
931.3 GiB
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)
'2.3 KB'
'0.0 MB'
'0.0 GB'
>>>
*Why do in my code, it loops to all values and not in Mark Pilgrim’s code?*
Best Regards,
[ pyhx0r - hx0r-labs.org ]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110224/1afdc6e9/attachment-0001.html>
More information about the Tutor
mailing list