[Tutor] help with random.randint

spir denis.spir at free.fr
Wed Feb 3 11:19:18 CET 2010


On Wed, 03 Feb 2010 11:21:56 +0800
David <ldl08 at gmx.net> wrote:

> Hello list,
> 
> I thought this was easy even for me, but I was wrong, I guess.
> Here is what I want to do: take two random numbers between 1 and 99, and 
> put them into a list.
> 
> import random
> terms =  []
> for i in range(2):
> 	terms = random.randint(1, 99)
> print terms
> 
> This prints just one number (the last one generated in the loop?)

Yo, terms now refers to a simple integer. What you want is instead:
for i in range(2):
	term = random.randint(1, 99)
        terms.append(term)	# put new item at end of list
print terms


> So I tried to change line 4 to the following:
> 	terms += random.randint(1, 99)

This is equivalent to
   terms = terms + random.randint(1, 99)
Because the first operand is a list, python won't do an addition (yes, the operator can be misleading, I would personly prefer eg '++' to avoid ambiguity), but a so-called "concatenation" (yes, that word is ugly ;-). This "glues" together 2 sequences (lists or strings). In this case, you get an error because the second operand is not a sequence.

Denis
________________________________

la vita e estrany

http://spir.wikidot.com/


More information about the Tutor mailing list