create a password with numbers in python

To create a password with numbers in python, we can use the string and random modules. The string module provides a constant called digits, which is a string of decimal digits. The random module provides the randint() function to generate a random integer between a specified range.

Here is an example code that generates a random password with 8 characters, including both letters and digits:

main.py
import random
import string

def generate_password(length):
    letters = string.ascii_letters
    digits = string.digits
    password = ''.join(random.choice(letters + digits) for _ in range(length))
    return password

print(generate_password(8))
250 chars
11 lines

In the above code, we first import the random and string modules. Then, we define a function called generate_password() that takes a length parameter as input. Inside the function, we create two string variables for letters and digits using the ascii_letters and digits constants from the string module. We then create a password variable and use a list comprehension with the for loop to randomly choose a character from the letters and digits strings and concatenate them to the password variable. Finally, we return the password.

We call the generate_password() function with an argument of 8 to generate a password of length 8. The output will be a randomized combination of letters and digits.

gistlibby LogSnag