Skip to content
Advertisement

Building a password generator

I have recently built a password generator but wanted to include an aspect where if the user types in a letter instead of a number when defining the length of the password and number of passwords then the output would be to loop back in. If not the password generator would continue if numbers were inputted.

This is my code so far:

import random

char = "abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!@£$%^&*"

while True:

   
        password_length = input("how long do you want your password? ")
        password_count = input("how many passwords do you want? ")


        if password_length and password_count != type(int):

            print("Please can you enter a number")

        elif password_length and password_count == type(int):

            for x in range(0,int(password_count)):

                password = ""
                    
                for y in range(0,int(password_length)):

                    random_letters = random.choice(char)
                    password += random_letters

                print(password)

Advertisement

Answer

Python offers a better way to check if a string is a digit or not.

From w3:

The isdigit() method returns True if all the characters are digits, otherwise False.

import random

char = "abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!@£$%^&*"
while True:
   password_length = input("how long do you want your password? ")
   password_count = input("how many passwords do you want? ")

   if password_count.isdigit() and password_length.isdigit(): 
     password_int = int(password_count)
     password = ""
     for x in range(0,password_int):
         for y in range(0,int(password_length)):
            random_letters = random.choice(char)
            password += random_letters
           
     print(password)
   else: 
      print("Please enter a valid input in numbers")

Output:

how long do you want your password? 8
how many passwords do you want? 1

ABZEG66j
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement