Why am I not getting four unique numbers returned?

Question:

I am trying to create a function that returns a 4 digit string which consists of 4 unique values.
I currently have the following code:

def generateNum():
    ValidNum = False
    while ValidNum == False:
        RanNumber = random.randint(1000, 9999)
        RanNumber = str(RanNumber)
        for number in RanNumber:
            if RanNumber.count(number) > 1:
                ValidNum = False
            else:
                ValidNum = True
                return RanNumber

print(generateNum())

Can someone explain what is wrong with this piece of code and what I can potentially do to fix it?
Thank you.

Asked By: chiraagp97

||

Answers:

import random

def generate_random():
    num = ''
    while len(num) < 4:
        random_int = random.randint(0,9)
        if str(random_int) in num:
            pass
        else:
            num += str(random_int)         
    return num      
    

print(generate_random())

This should work fine

Answered By: Benard Agustin

Following your logic, this is what would have worked:

def generateNum():
    ValidNum = False

    while True:
        RanNumber = random.randint(1000, 9999)
        RanNumber = str(RanNumber)

        for number in RanNumber:
            if RanNumber.count(number) == 1:
                ValidNum = True
                continue
            else:
                ValidNum = False
                break
        if not ValidNum:
            continue
        break
    return RanNumber
Answered By: almamy-code
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.