Issue
I am creating a random password generator. 1st i have to ask the user for the length of the password and it must have a minimum of 8 digits to a maximum of 16 digits. The one i created is asking the user to key in the password itself and from there its checking the length. First i want the user to key the the length of the password, EG: 7 or 9 or so on. if the user keyed in the digit which is less than 8 and more than 16 it must show "must have a minimum of 8 digits to a maximum of 16 digits". Pls refer below for the code, if its not clear do refer to the both images. thank you.
INPUT
import random
import string
print('hello, Welcome to Password generator!')
l = False
while not l:
length = input('\nEnter the length of password: ')
if len(length) < 8 :
print('You password length is too short(must be more than 8 character)')
print(len(length), "is the length of your password")
elif len(length) > 16:
print('You password length is too long(must be less than 17 character)')
print(len(length), "is the length of your password")
else:
print('You password length looks good')
break
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
all = lower + upper + num + symbols
temp = random.sample(all,length)
password = "".join(temp)
print(password)
OUTPUT
hello, Welcome to Password generator!
Enter the length of password: 9
You password length is too short(must be more than 8 character)
1 is the length of your password
Enter the length of password: 9
You password length is too short(must be more than 8 character)
1 is the length of your password
Solution
The return type for input()
is str
or string. When you check the length of the return value, assigned to length
, it is counting the number of characters in the string and not checking if the given number is greater or smaller than another. To fix the issue, call the integer constructor int()
on length
or place it around the call to input
so that the string is converted into a numeric type before the check.
length = int(input('\nEnter the length of password: '))
Additionally, since length
is now an integer, you would perform the check directly without calling len
. e.g.
if length < 8:
...
Answered By - Cresht
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.