[Tutor] Program

Noah Hall enalicho at gmail.com
Thu May 19 20:45:57 CEST 2011


On Thu, May 19, 2011 at 7:23 PM, Johnson Tran <aznjonn at me.com> wrote:
> So I figured out how to use the loop method, thanks. I still cannot seem to figure out how to use Len() to show the output of my answers (from all my googling Len() seems to be used to count characters?) Also, I am not really sure I understand how to use the append method of the list.

That's true, that's exactly what len does (note, len, not Len). The
function you're looking for to sort the output is sorted().

append adds an item to the list, for example -
>>> names = ['John']
>>> names.append('Katie')
>>> names
['John', 'Katie']

> Here's my best guess so far:
>
>
> def CollectNames():
>
>    for attempt in range(1,6):
>        word=raw_input("Name #%d" % attempt)
>        list.append("new")

You need to create a list to append to, before you can do this.
If you want to use some form of validation, then this is where you
want len with set usage, for example

>>> names = ['Fred', 'Tom', 'Jake', 'Tom', 'Harry']
>>> names
['Fred', 'Tom', 'Jake', 'Tom', 'Harry']
>>> len(names)
5
>>> names_set = set(names)
>>> names_set
set(['Harry', 'Tom', 'Jake', 'Fred'])
>>> len(names_set)
4

Because "Tom" is in the list twice, and set has unique items only, the
length of the set is 4, not 5. This is where you can call whatever
validation you want (I suggest using a while loop).

>    print "All the names in alphabetical order are ", len(L);

This isn't where you want len. There's also nothing called "L" - is
this what you called your list? Also, L is a bad name for a variable.
Try to use descriptive names where possible.

>
> And just to recap, I was trying to get all the names outputted after the last name was collected (and sort them in alphabetical order. Took my sort commands out until I could figure out how to get any output first....

HTH.


More information about the Tutor mailing list