I have a small problem with a function that should potentially generate a random 6-digit code. The code in itself is absolutely straightforward, using python 3 I do it like this:
def secret_code(num=6):
numbers = string.digits
code = ''
for _ in range(num):
code += random.choice(numbers)
return int(code)
Now, there is a gazillion way to do this but I am not questioning the validity of this method, in particular, against others, my issue is that sometimes this function returns a 5-digit code.
I have tried a for loop with 1000 cycles to test how often this happens, in this way:
for _ in range(1000):
code = secret_code() # calling the function above
if len(code) < 6:
count += 1
ratio = count/1000
print(ratio*100) # at this point the test has given back 0% all the times
and it always comes back 0% of the time.
However, when applied to a website, for example, I am using it to generate random verification codes to send to new users, sometimes (I don't mean 50% of the times, of course, but it's not even 0) it comes out with 5 digits instead of 6 and, for the life of me, I can't figure out why.
Does somebody have any idea why this occurs? and more importantly, why doesn't it show up in the "for loop test"?
Thanks
Aucun commentaire:
Enregistrer un commentaire