vendredi 17 novembre 2017

python - How to input distinct random numbers into a list using loop?

What I aim to do is to input 4 distinct numbers into a list called var. If 2 random numbers give the same number, it is not appended, and the loop iterates to pick a new random number. But my code will give only the list of random numbers that are not equal. For example if random numbers generated are 1,4,4,3 my list('var') will only have 1,4,3. ie, only 3 numbers in total. How to correct the code to append a total of 4 unique random numbers into the list?

import random
var=[]
end=4
for i in range(0,end,1):
 k=random.randint(0,9)
 print k
 if k not in var:
  var.append(k)
 else:
  end+=1




Aucun commentaire:

Enregistrer un commentaire