[Tutor] Entering a list of numbers
Remco Gerlich
scarblac@pino.selwerd.nl
Tue, 6 Jun 2000 13:11:02 +0200
On Mon, Jun 05, 2000 at 06:42:59AM -0700, doubletwist@spack.nu wrote:
> I'm still fairly early in the program but have gotten stuck. I created a
> function to do the initial roll of the dice with no problem.
> Now I'm trying to make a function for the input of which dice the user
> wants to roll again. [ie enter which dice [1-6] they want to re-roll]
>
> I'd like to have the user just enter the numbers separated by commas. The
> only way I've figured out to do it is have the input entered into a tuple,
> then transcribed to a list, but if they just enter one number [and thus no
> comma] the conversion to a list fails with:
>
> Traceback (innermost last):
> File "temp.py", line 40, in ?
> rerolled = rollagain()
> File "temp.py", line 25, in rollagain
> while count < len(entered):
> TypeError: len() of unsized object
That's because simply "1" is an integer, not a tuple. "1," works.
But this is a silly way to do it, see below.
> Is there an easier way of doing this? Or would I just be better off using
> a loop of some sort and just having them enter each number followed by a
> return?
>
> My code as it stands follows... the function is called with :
>
> rerolled = rollagain()
>
> Thanks,
> Doubletwist
>
> ---CODE BELOW----
>
> def rollagain():
> elist = []
> entered = ()
> count = 0
> print "Which dice would you like to re-roll?"
> print "Separate with commas. Enter 99 to keep all dice"
> entered = input()
> while count < len(entered):
> elist.append(entered[count])
> count = count + 1
> return elist
input() should only be used to enter any Python expression, like in
the interpreter. It doesn't really have a place in normal programs, imo.
People can enter any expression - including commands that wipe all your
files, and so on...
Use raw_input() to get a string, then get the info you want from that.
def rollagain()
print "Which dice would you like to re-roll?"
entered = raw_input("Separate with commas. Enter 99 to keep all dice.")
import string
# Split on comma - "3,4,5" results in ["3","4","5"]
elist = string.split(entered, ",")
# Turn all elements into integers
elist = map(int, elist)
return elist
Something like that will work better.
Btw, if you want to turn a tuple into a list, just use elist = list(entered).
And even if you did want a loop for it,
for e in entered:
elist.append(e)
Is a bit more Pythonic than using a count and a while loop :-)
--
Remco Gerlich, scarblac@pino.selwerd.nl