w3resource

Python Cyber Security – Generate random passwords of specified length

Python Cyber Security: Exercise-2 with Solution

Write a Python program that defines a function to generate random passwords of a specified length. The function takes an optional parameter length, which is set to 8 by default. If no length is specified by the user, the password will have 8 characters.

Sample Solution:

Python Code:

import random
import string
def generate_password(length=8):
    # Define the characters to use in the password
    all_characters = string.ascii_letters + string.digits + string.punctuation
    
    # Use the random module to generate the password
    password = ''.join(random.choice(all_characters) for i in range(length))
    
    return password

password_length_str = input("Input the desired length of your password:")
if password_length_str:
    password_length = int(password_length_str)
else:
    password_length = 8

password = generate_password(password_length)
print(f"Generated password is: {password}")

Sample Output:

Input the desired length of your password: 
Generated password is: &bMFdgNo

Input the desired length of your password: 4
Generated password is: i$3H

Input the desired length of your password: 7
Generated password is: (`9z}Q%
 
Input the desired length of your password: 15
Generated password is: ?A5]3&h1e-:9OkR

Flowchart:

Flowchart: Generate random passwords of specified length

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Hash Password String using SHA-256 Algorithm.
Next: Check password strength.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/cybersecurity/python-cybersecurity-exercise-2.php