[Tutor] Trying to access a random value in a list
Dave Angel
d at davea.name
Fri Jan 13 01:07:55 CET 2012
On 01/12/2012 06:56 PM, Nick W wrote:
> first problem: easy fix just remember that len() returns the actual
> number of items in the list but that list is indexed starting at 0 so
> just replace your line of
> pick = len(names)
> with:
> pick = len(names) - 1
> and for problem #2:
> just use string formating... like for example instead of:
> print (names[win_number], " is the winner!")
> try something along the lines of:
> print("{} is a winner".format(names[win_number]))
> HTH
> Pacific Morrowind
>
You top-posted. On lists like this one, it's proper to add your new
message after the piece you're quoting.
> On 1/12/12, Claude Matherne<cmathe7 at gmail.com> wrote:
>> Hello all,
>> I am a beginner to python and I am trying to make a simple program that
>> takes in some names as input into a list and then randomly picks a vaule
>> from that list as a winner.
>>
>> Here is the code:
>>
>> import random
>>
>> choice = None
>>
>> names = [ ]
>>
>> while choice != "0":
>> print(
>> """
>> 0 - Exit
>> 1 - Enter a name
>> 2 - Pick a winner
>> """)
>> choice = input("Choice: ")
>> print()
>>
>> if choice == "0":
>> print ("Goodbye.")
>>
>> elif choice == "1":
>> name = input("Please enter a name: ")
>> names.append(name)
>> print (names, "have been entered.")
>>
>> elif choice == "2":
>> pick = len(names)
>> win_number =random.randint(0,pick)
>> print (names[win_number], " is the winner!")
>>
>> input("/n/nPress enter to exit.")
>>
>>
>> First problem, sometimes I get a error where the value is out of range.
>> Problem becuase of the way I set up the random value.
>> Second problem, but not a big one, is when I print the lists of names as
>> they are entered, I get quotations around the name.
>>
>> I'm sur I am over thinking this, but any help would be great.
>>
>> Thanks
>>
The problem with the quotes is just the way that Python works.
print (names, "have been entered.")
You're printing a list as a whole, and when it does that, individual
items are displayed using repr(), rather than str(). If you don't like
that, write a loop, with a print statement per item, and format it any
way you like.
for name in names:
print(name, "+whatever")
--
DaveA
More information about the Tutor
mailing list