Write a Python program that uses the random module to generate a random password of a given length consisting of uppercase and lowercase letters, digits, and special characters. The function generate_password(length) should return a random password of length length.
Example 1:
Input: generate_password(10) Output: A random password of 10 characters, e.g. "Xk2#s7&Z9$"
Example 2:
Input: generate_password(15) Output: A random password of 15 characters, e.g. "7aS#2lP$5xQ&8rZ"
Use the random.choice() function from the random module.
import random
import string
def generate_password(length):
all_characters = string.ascii_letters + string.digits + string.punctuation
password = "".join(random.choice(all_characters) for _ in range(length))
return password
# Test the function
print(generate_password(10))
print(generate_password(15))
Unlock AI & Data Science treasures. Log in!