[Tutor] Need help understanding output...

Evert Rol evert.rol at gmail.com
Wed Aug 11 23:53:16 CEST 2010


> I'm learning Python and I'm currently facing an issue with a small script I'm writing.
> 
> I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, 4, 5 & 6. However, I cannot have more than 2 numbers which are the same next to each other. I came up with the following (Please ignore the fact that I'm trying to avoid an IndexError in a stupid way :)):

Ok, we'll ignore that (for now ;-D).

<snip />

> However, I wanted to look deeper in the above script and I created the following:
> 
> import random
> iteraties = 5
> cijferreeks = 6
> aantal_cijfers = iteraties * cijferreeks
> reeks = []
> while len(reeks) <= 1:
>  nummer = random.randrange(1, cijferreeks + 1, 1)
>  print 'Nummer: ', nummer
>  print 'Reeks: ', reeks
>  reeks.append(nummer)
>  print '\n'
> 
> while len(reeks) <= aantal_cijfers:
>  nummer = random.randrange(1, cijferreeks + 1, 1)
>  print 'Nummer: ',  nummer
>  print 'Voorlaatste vd reeks (-2): ', reeks[-2]
>  print 'Laatste vd reeks (-1): ', reeks[-1]
>  print 'Reeks: ', reeks
>  if nummer != reeks[-1] and nummer != reeks[-2]:
>    reeks.append(nummer)
>  else:
>    print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ', reeks[-1], '&', reeks[-2], '!'
>  print '\n'
> print reeks
> 
> When I run that, I can see there's something wrong with my if statement, it triggers the else condition even when the 2 previous numbers in my list are not the same...  I'm not sure what is happening here...

For an 'and' in a condition, only one part of the condition needs to be False for the condition to fail and skip to the else clause.
Eg, with nummer=1, reeks[-1]=1 and reeks[-2]=2, it finds that 1 != 1 is False, and immediately skips to the else part. Ditto if nummer=2 and same reeks: first part is then True, but second part False, hence skip to else.
I leave it up to you to find the correct if statement. (Hint: it's phrased in your third sentence at the top.)


Btw, tip: always code in English. It just makes things easier for yourself when using other code examples, for example. But I just find generally good practice.

Cheers,

  Evert



More information about the Tutor mailing list