views:

93

answers:

2

I have this code:

def random_answerlist(self):
    self.li = []
    self.winning_button = random.randint(0, 3)
    i = 0
    while i < 20 and len(self.li) is not 4:
        if i == self.winning_button:
            self.li.append(self.flags[self.current_flag][0])
        else:
            new_value = self.random_value()
            if self.flags[new_value][0] not in self.li:
                self.li.append(self.flags[new_value][0])
        i += 1
    return self.li

The only problem with it is that the first if-case may happen several times which should be impossible. I have searched for a good explanation to this and I can't find any.

Oh, I know the code isn't the best. But I'm kind of new to python (just a month or so) and thought this might work, but it didn't!

Do you guys know why? =)

A: 

Yes, sorry.

I were out smoking when I realized I were the one failing:

The problem is not the if-case as you guys stated. The problem is that the else case generates randomly from the same list as the first if-case does. And then the same value is getting into the list sometimes as the one in the first if-case.

You couldn't solve it since I didn't post the whole code.

Well thanks anyway :)

nattefrost
+1  A: 

One glaring problem is the usage of is not for a value comparision against len(self.li). The tests is not and != are not the same. is tests for identity (are these references to the same object?), != tests for equality (do these objects have the same value?).

Change your while to:

while i < 20 and len(self.li) != 4:

Does that address the issue?

jathanism
It wasn't the main problem. But I guess it'll help me anyway. Thank you very much for your reply. I didn't exactly know the difference between "is not" and "!=" which made me choose "is not" since I am kind of stressed out ;)
nattefrost
I will point out that, if I remember correctly, integers from -5 to 256 (inclusive, and don't ask me why they chose that range) are cached singleton objects in Python. So for integers in that range, `==` and `is` (or `!=` and `is not`) always return the same result. Of course, it's still good general practice to use `==` or `!=`, but it wouldn't make the difference in this question.
David Zaslavsky
Ok I will try to remember that. But I guess I won't use it that much (right now anyway). It's always nice to learn something new like that. I noticed it worked since it didn't address a problem for me.
nattefrost