Python password generator
On this page password generator In Python.
Writing the code requires a basic understanding of Python coding and the built-in String and Random modules.
If you’re new to Python coding, check out this tutorial first.
Let’s begin.
We use Python version 3.10+ and PyCharm (IDE).
plan
This calculator has three parts:
- module import
- creation function
- main function
The calculator asks the user to enter the password length (an integer). As output, the program generates a randomly generated password.
module import
This section is very simple.
First we need to import the built-in library.
import random import string
that much random The module includes a character generator and string The module provides string manipulation.
creation function
The second part covers the ability to generate random passwords.
First, define all letters (lowercase and uppercase), numbers (0-9) and punctuation marks and store them in variables. It then randomly selects characters from the three constant packs above and combines them (without spaces). All are within the password length range you selected. Returns the last generated password.
def generate_password(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) return password
main function
The last section concerns the main features. This feature includes entering the required user password length. Implement try/exclude tests to catch invalid input (whether the input is of length less than 0 or is not an integer).
def main(): try: length = int(input("Enter the length of the password you want to generate: ")) if length <= 0: print("Please enter a positive integer greater than 0.") return password = generate_password(length) print("Generated Password:", password) except ValueError: print("Invalid input. Please enter a valid integer.")
Finally, we implement a script execution mechanism.
if __name__ == "__main__": main()
yes
Here is an example of the password generator results:
Full code for password generator
Here is the full Python code for the password generator.
import random import string def generate_password(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for _ in range(length)) return password def main(): try: length = int(input("Enter the length of the password you want to generate: ")) if length <= 0: print("Please enter a positive integer greater than 0.") return password = generate_password(length) print("Generated Password:", password) except ValueError: print("Invalid input. Please enter a valid integer.") if __name__ == "__main__": main()
Previous: GUI Age Calculator using Python