[Python-Help] (fwd)
Steven Bethard
steven.bethard at gmail.com
Sun Dec 5 05:08:22 EST 2004
Craig Ringer wrote:
> It looks to me like you'd be better off reading each input number into a
> list.
You may also find it useful to write a generator function to read your
values in:
>>> def read_numbers():
... while True:
... number = int(raw_input('Enter a number: '))
... if number == 0:
... break
... yield number
...
>>> read_numbers()
<generator object at 0x0114CE18>
>>> for number in read_numbers():
... print number
...
<... after typing 5 ...>
5
<... after typing 6 ...>
6
<... after typing 9 ...>
9
<... after typing 0 ...>
>>>
>>> list(read_numbers())
<... after typing 2, 4, 5, 5, 8, 0 ...>
[2, 4, 5, 5, 8]
The read_numbers function creates a generator object which will query
the user for a number until it sees the number 0. Because you get a
generator object from this function, you can easily convert it to a list
if you need to, or iterate on it directly.
Also note that I use int(raw_input(...)) instead of input(...). It's a
few more keystrokes, but it's probably a good habit to get into --
input(...) has some security holes.
Steve
More information about the Python-list
mailing list