tips for this exercise?
larry.bates at websafe.com
Tue Mar 28 22:38:25 CEST 2006
Not a lot wrong with your code except that your
return fiveNumbers will execute the first time
through the loop because it is indented inside
the loop. Also, append does its work in place,
it doesn't return a new list.
You also might want to pass the maximum number
and return count, into the function and initialize
numbers list there. That way you can call
genNumbers(54, 5) or genNumbers(103, 7) and get
differing length lists back from your function.
def genNumbers(maxnum, retcount):
for x in range(retcount):
retNumbers = 
number = random.choice(numbers)
John Salerno wrote:
> I'm working on another exercise now about generating random numbers for
> the lottery. What I want to do is write a function that picks 5 random
> numbers from 1-53 and returns them. Here's what I have so far:
> numbers = range(1, 54)
> def genNumbers():
> for x in range(5):
> fiveNumbers = 
> number = random.choice(numbers)
> fiveNumbers = fiveNumbers.append(number)
> return fiveNumbers
> Other than being sort of ugly, this also has the side effect of actually
> editing the original list, which I don't want since I will want to
> generate more than one set of numbers.
> Is there a better way to extract a certain number of items from a list
> (so maybe I don't need the for loop)? Is a list even the right type to
> use, since it gets edited in place? Perhaps a set?
More information about the Python-list