[Tutor] Program

Alan Gauld alan.gauld at btinternet.com
Wed May 18 16:57:08 CEST 2011


"Johnson Tran" <aznjonn at me.com> wrote

> I had a couple questions about my program:
>
> def CollectNames():
>    answer_set=set([])
>    sorted_list = sorted(answer_set)

This creates an empty set then sorts it and stores
the result as an empty list. I'm not sure what you
think it does but I'm guessing that's not it...

>    word=raw_input("Name #1: ")
>    word=raw_input("Name #2: ")
>    word=raw_input("Name #3: ")
>    word=raw_input("Name #4: ")
>    word=raw_input("Name #5: ")

Do you know about loops yet?
Any time you find yourself repeating code like
this think about a loop. A for loop could be
used here:

for attempt in range(1,6):
    word = raw_input("Name #%d" % attempt)

Although storing all the names in the same variable
is also probably not what you want. You need to
add word to your list using the list append() method.

>    print "Your answers sorted: ", ','.join(sorted_list)

And this is where you probably want to call sorted()...

> 1.) how do i add each answer given to the list so it is printed at 
> the end?

Use the append method of the list

> 2.) also im trying to modify the program so if the
> user puts in the same name, it will give an make
> them try again until they have 5 completely different
> names.

A combination of a while loop and a set and the len() function
might work here. Keep adding to the set while the length of the
set is <5.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list