[Tutor] how to take user input to form a list?

Gregor Lingl glingl at aon.at
Sun Nov 14 17:52:27 CET 2004



Lin Jin schrieb:

> hello,all:
> if i want to make a function that takes user input to form a list,how
> i could do that?
> it's run like:
>
>>>> Enter 4 letters:
>>>> a
>>>> b
>>>> c
>>>> d
>>>> [a,b,c,d]
>>>
> and i write a code like this which is not working:
> def list(let1,let2,let3,let4):
> let1,let2,let3,let4=raw_input("enter 4 letters:")
> list=[let1,let2,let3,let4]
> print list
>

Hi Lin!
In priciple your code should work.
But you should tell us, how you want to
call your function list. You have to supply 4
arguments, which - however - will not be used,
when your function is executed. The values of your
parameters will be overwritten immediately by the
result of the raw_input call.

I did this, for instance:

>>> def list(let1,let2,let3,let4):
let1,let2,let3,let4=raw_input("enter 4 letters:")
list=[let1,let2,let3,let4]
print list

>>> list(1,2,3,4)
enter 4 letters:abcd
['a', 'b', 'c', 'd']
>>> list(None,None,None,None)
enter 4 letters:xyz!
['x', 'y', 'z', '!']
>>>

So you could define as well:

>>> def list():
let1,let2,let3,let4=raw_input("enter 4 letters:")
list=[let1,let2,let3,let4]
print list


>>> list()
enter 4 letters:1234
['1', '2', '3', '4']
>>>

Moreover it is not a good idea do name a
userdefined function 'list' as this is the name
of a built-in datatype/function of Python, which
you will not be able to use anymore after your
definition is executed:

>>> list
<type 'list'>
>>>

>>> def list():
let1,let2,let3,let4=raw_input("enter 4 letters:")
list=[let1,let2,let3,let4]
print list


>>> list
<function list at 0x00A7C430>

Aaah! This reminds me, that you can use the original
Python-list-type to accomplish your task (in a freshly
started Python):

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.
...
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> def makecharlist():
return list(raw_input("Enter (4) characters: "))

>>> makecharlist()
Enter (4) characters: pqrs
['p', 'q', 'r', 's']
>>> makecharlist()
Enter (4) characters: pqrstuvw!!!!
['p', 'q', 'r', 's', 't', 'u', 'v', 'w', '!', '!', '!', '!']
>>>

I think, that Alan in his reply missed, that
splitting will be done by "sequence-unpacking" in
your code. But it will work only with exactly four
characters entered, while the code he proposed will work
for strings with arbitrary length (and produce lists
of that length).

Hope that helps

Gregor

> anyone could help me on this? thx
>
> _________________________________________________________________
> Ãâ·ÑÏÂÔØ MSN Explorer: http://explorer.msn.com/lccn/
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


More information about the Tutor mailing list