As others have explained, random.sample is the best way to do what you want.
To explain why your source code didn't work:
First problem: there is a logical error with your while - it will end as soon as the two elements are different (for example, 'a' == 'a' == 'b' will be True and the loop will end), to fix this, There are several ways:
while not (key1 != key2 != key3):
Alternatively, set can only contain unique elements, so when the length of set([key1, key2, key3]) is 3, all three values ββare different:
while len(set([key1, key2, key3]) != 3:
The second problem and the reason why the code refuses to run:
key1 key2 key3 defined as global variables ( key1 = ' ' are at the top-level of your .py`, not in a function)
You can search for a global variable in a function without problems (for example, when you did while key1 == key2 ... ). The error arises because you are also trying to assign key1 in your loop - this confuses the Python parser because you are viewing the global variable in the while key1 == ... , but trying to create a new local function variable on the next line, therefore he helps make a mistake.
The tail, to fix this, looks like this:
key1 = ' ' key2 = ' ' key3 = ' ' def nodupchoice(): global key1 global key2 global key3 while not (key1 != key2 != key3): key1 = random.choice(word_drills.keys()) key2 = random.choice(word_drills.keys()) key3 = random.choice(word_drills.keys())
Then it will work as you planned, but do not do this - global variables will use them , but this is not the case.
Instead of using a global variable, you can easily return multiple values ββfrom a function:
def nodupchoice(): key1 = ' '
Oh, and even better, you can pass in word_drills as an argument:
def nodupchoice(things): key1 = ' '
... and you wrote a function almost identical to the random.sample(word_drills, 3) function random.sample(word_drills, 3) !