[Tutor] Trying to access a random value in a list
bob gailer
bgailer at gmail.com
Fri Jan 13 01:04:17 CET 2012
On 1/12/2012 5:48 PM, Claude Matherne 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.
randint returns random integer in range [a, b], including both end
points. List indexes start at 0. Sufficient?
> 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 bet you are seeing something like ['joe', pete'] since you are
printing a list. true? In general copy and paste the undesired output in
the email. Try print(','.join(names)
--
Bob Gailer
919-636-4239
Chapel Hill NC
More information about the Tutor
mailing list