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:

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.
Python: Tips of the Day
Get Current Process Id:
import os os.getpid()
21423
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook