Python generate random number and string

Published on Aug. 22, 2023, 12:16 p.m.

To generate a random number in Python, you can use the random module. The random module provides various functions for generating random numbers of different types. Here is an example code that generates a random integer between 1 and 100:

import random

random_number = random.randint(1, 100)
print(random_number)

This will output a random integer between 1 and 100.

To generate a random string in Python, you can use the string and random modules. The string module provides various string constants, such as letters, digits, and punctuation. The random module provides various functions for generating random elements from a sequence.

Here is an example code that generates a random string of length 8, consisting of lowercase letters:

import random
import string

random_string = ''.join(random.choice(string.ascii_lowercase) for i in range(8))
print(random_string)

This will output a random string of length 8, consisting of lowercase letters.

Note that the secrets module can also be used to generate cryptographically secure random numbers and strings in Python.

Tags: