How to generate a random 4 digit number not starting with 0 and having unique digits?

后端 未结 12 1901
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 12:48

This works almost fine but the number starts with 0 sometimes:

import random
numbers = random.sample(range(10), 4)
print(\'\'.join(map(str, numbers)))
         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 12:53

    Just loop until you have something you like:

    import random
    
    numbers = [0]
    while numbers[0] == 0:
        numbers = random.sample(range(10), 4)
    
    print(''.join(map(str, numbers)))
    

提交回复
热议问题