Search code examples
pythonrandomascii

How do I generate 8 different random numbers in python?


I'm trying to write an encryption program that generates 8 different random numbers and converts them to ASCII. If possible I'd like to use the 'random' function in python, but welcome other help.

So far my code for generating the numbers is to assign a value to a different run of the random.randint() function 8 different times, the problem is that this is sloppy. A friend said to use random.sample(33, 126, 8) but I can't get this to work.

Any help is extremely welcome.


Solution

  • You can pass xrange with your upper and lower bound to sample:

    from random import sample
    
    print(sample(xrange(33, 126),8))
    

    An example output:

    [49, 107, 83, 44, 34, 84, 111, 69]
    

    Or range for python3:

     print(sample(range(33, 126),8))
    

    Example output:

     [72, 70, 76, 85, 71, 116, 95, 96]
    

    That will give you unique numbers.

    If you want 8 variables:

    a, b, c, d, e, f, g, h =  sample(range(33, 126), 8)
    

    If you want ascii you can map(chr..):

    from random import sample
    
    print map(chr,sample(xrange(33, 126), 8))
    

    Example output:

    ['Z', 'i', 'v', '$', ')', 'V', 'h', 'q']