Define variable in while loop - python

I going through a python course and am stuck at trying to use a while loop properly in my code
My code is supposed to check a password if it has min length =6 and max length =14, it will also check if the password only has numbers or letters. If it has a combination of both its supposed to print "strong password" if it only has numbers or letters it will print "weak password".
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
while password_length >= MIN_PASSWORD_LENGTH or password_length <= MAX_PASSWORD_LENGTH:
password_length = len(password)
password = input("Enter your password: ")
if password.isalpha():
print("Your password is weak!")
elif password.isnumeric():
print("Your password is weak!")
else:
print("Your password is strong!")
print("Number of characters used in password: ", password_length,"the min length expected is: ",MIN_PASSWORD_LENGTH,
"the max length is: ", MAX_PASSWORD_LENGTH)
When I run my code, it comes with error message: 'name password_length is not defined'. I am not sure what to do? Is my code even correct? Am I supposed to put the password_length outside the while loop?

You have, more or less, the right idea. It's just that you need to assign a value to password_length outside your loop.
Think about this: when your code is run, the interpreter hits the while loop and attempts to make a comparison involving password_length. However, at that point password_length doesn't exist yet, since the first time it gets a value is inside the loop. Therefore, you should initialise it to a sensible value, such as 0, before entering the loop.
Two supplementary points:
You're calculating the password length of the previous password, so if you enter a too-short/long password and then an acceptable one, the length printed will be of the unacceptable one.
In general, prefer f-strings or str.format calls to string concatenation, so, for your print, this might be better:
print(f'Number of characters used in password: {password_length}; '
'the min length expected is {MIN_PASSWORD_LENGTH} and the '
'max length expected is {MAX_PASSWORD_LENGTH}.')

Immediately before the while loop, initialize with something like "password_length = MAX_PASSWORD_LENGTH" or else the while loop cannot start. The first line inside the while loop is "password_length = len(password)", which will set the value of password_length correctly, but the while loop needs something to start with so that you can reach that point.

The problem is your calling password before the code knows what it is.
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
# password must be defined before you use it.
password = input("Enter your password: ")
while password_length >= MIN_PASSWORD_LENGTH or password_length <= MAX_PASSWORD_LENGTH:
password_length = len(password)
if password.isalpha():
print("Your password is weak!")
elif password.isnumeric():
print("Your password is weak!")
else:
print("Your password is strong!")
print("Number of characters used in password: ", password_length,"the min length expected is: ",MIN_PASSWORD_LENGTH,
"the max length is: ", MAX_PASSWORD_LENGTH)

You're using password and password_length variables before they are defined.
Also you can use function and rewrite it more structured:
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
def checkPass():
password = input("Enter your password: ")
password_length = len(password)
if password.isalpha():
print("Your password is weak!")
elif password.isnumeric():
print("Your password is weak!")
else:
print("Your password is strong!")
return password_length >= MIN_PASSWORD_LENGTH or password_length <= MAX_PASSWORD_LENGTH
while checkPass():
continue
print("Number of characters used in password: ", password_length,"the min length expected is: ",MIN_PASSWORD_LENGTH, "the max length is: ", MAX_PASSWORD_LENGTH)
Online demo

Here is a version based on what I understood
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
password = ""
atLeast1Apha = False
atLeast1Numeric = False
while True:
password = input("Enter your password: ")
if len(password) > MAX_PASSWORD_LENGTH or len(password) < MIN_PASSWORD_LENGTH:
print("Password could be between %s and %s long" %(MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH))
continue
for char in password:
if char.isalpha():
atLeast1Apha = True
if char.isdigit():
atLeast1Numeric = True
break
if atLeast1Apha and atLeast1Numeric:
print("Your password is strong!")
else:
print("Your password is weak!")

Conditions in the while loop are wrong. You may try:
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
password = input("Enter your password: ")
password_length = len(password)
while password_length < MIN_PASSWORD_LENGTH or password_length > MAX_PASSWORD_LENGTH:
print("Password length", password_length, "incorrect. Required between", MIN_PASSWORD_LENGTH, "and", MAX_PASSWORD_LENGTH)
password = input("Enter your password again: ")
password_length = len(password)
if password.isalpha() or password.isnumeric():
print("Your password is weak!")
else:
print("Your password is strong!")
print("Number of characters used in password:", password_length,". The min length expected is:",MIN_PASSWORD_LENGTH, ". The max length is: ", MAX_PASSWORD_LENGTH)

Related

My second IF statement in this password checker isn't working and I'm unsure why

Ok, below is my code and I'm just puzzled as to why it can't validate if the password is all letter or numbers. The else statement works fine. Thank you for any help, I really appreciate it!
import datetime
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 10
password = input("Please create a password: ")
password_length = len(password)
PASSWORD_LOG_FILE = open('password_log.txt', "w")
while password_length < MIN_PASSWORD_LENGTH or password_length > MAX_PASSWORD_LENGTH:
if password_length < MIN_PASSWORD_LENGTH:
current_date_and_time = datetime.datetime.now()
error = (f"{current_date_and_time}, password < 6")
PASSWORD_LOG_FILE.write(error)
PASSWORD_LOG_FILE.write("\n")
elif password_length > MAX_PASSWORD_LENGTH:
current_date_and_time = datetime.datetime.now()
error = (f"{current_date_and_time}, password > 10")
PASSWORD_LOG_FILE.write(error)
PASSWORD_LOG_FILE.write("\n")
print(f"Your password is {password_length} characters long, but it should be between 6-10.")
password = input("Please create a valid password: ")
password_length = len(password)
PASSWORD_LOG_FILE.close()
if password.isdigit():
message = "Password weak - contains only numbers."
elif password.isalpha():
message = "Password weak - contains only letters."
else:
message = "Password strong"
print(f"Your password is {password_length} characters long. {message}")
PASSWORD_LOG_FILE = open('password_log.txt', 'r')
for line in PASSWORD_LOG_FILE:
print(line, end='')
PASSWORD_LOG_FILE.close()
Your indentation is wrong, the print statement falls into else: so it only print when password is strong.
You should move the print statement
if password.isdigit():
message = "Password weak - contains only numbers."
elif password.isalpha():
message = "Password weak - contains only letters."
else:
message = "Password strong"
print(f"Your password is {password_length} characters long. {message}")
The last block of code was in the else:, so the message wasn't printed for the isdigit() or isalpha() cases. Also, I can see that you are having some irregular indentation in your code. Kindly fix that.
import datetime
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 10
password = input("Please create a password: ")
password_length = len(password)
PASSWORD_LOG_FILE = open('password_log.txt', "w")
while password_length < MIN_PASSWORD_LENGTH or password_length > MAX_PASSWORD_LENGTH:
if password_length < MIN_PASSWORD_LENGTH:
current_date_and_time = datetime.datetime.now()
error = (f"{current_date_and_time}, password < 6")
PASSWORD_LOG_FILE.write(error)
PASSWORD_LOG_FILE.write("\n")
elif password_length > MAX_PASSWORD_LENGTH:
current_date_and_time = datetime.datetime.now()
error = (f"{current_date_and_time}, password > 10")
PASSWORD_LOG_FILE.write(error)
PASSWORD_LOG_FILE.write("\n")
print(f"Your password is {password_length} characters long, but it should be between 6-10.")
password = input("Please create a valid password: ")
password_length = len(password)
PASSWORD_LOG_FILE.close()
if password.isdigit():
message = "Password weak - contains only numbers."
elif password.isalpha():
message = "Password weak - contains only letters."
else:
message = "Password strong"
print(f"Your password is {password_length} characters long. {message}")
PASSWORD_LOG_FILE = open('password_log.txt', 'r')
for line in PASSWORD_LOG_FILE:
print(line, end='')
PASSWORD_LOG_FILE.close()
like people mentiond in the comments, the print statement you are expecting is inside the else block, change it into this:
if password.isdigit():
message = "Password weak - contains only numbers."
elif password.isalpha():
message = "Password weak - contains only letters."
else:
message = "Password strong"
print(f"Your password is {password_length} characters long. {message}")

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)
Try this:
while True:
try:
password_length = int(input("how long do you want your password? "))
except:
print("Invalid input")
else:
break
while True:
try:
password_count = int(input("how many passwords do you want? "))
except:
print("Invalid input")
else:
break
And then you can go on with the rest of your code
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

The simplest way to check for UPPERCASES

Here, I am trying to validate a password and check to see if there are capitals and numbers in the password before saving it as a different variable. Using functions, is it possible for me to do so. The indents have changed on the format, so please help me with other aspects.
def length(long):
while len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
if password.isupper() = True:
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
This is what I have now done:
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
errors = []
print("Welcome to this student interface")
username = input("Please enter a username")
password = input("Please enter a strong password")
length(password)
bool Capcheck = False
bool DigCheck = False
while CapCheck = False or CapCheck = False:
length(password)
if not any(x.isupper() for x in password):
errors.append("Your password needs at least 1 capital.")
else:
CapCheck = True
break
if not any(x.islower() for x in password):
errors.append("......... Why?")
if not any(x.isdigit() for x in password):
errors.append("You need to have at least 1 digit")
else:
DigCheck = True
break
if errors:
print(" ".join(errors))
password = input("Please enter a stronger password")
Apparently there is an error with my boolean here, please help
def length(long):
bool LengthCheck = False
if len(long) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(long) + " characters long")
else:
LengthCheck = True
Try using islower():
password.islower()
This returns True if there are no Uppercases in the password.
Now if you want to check if it has number i it, you have to follow #jubnvz:
any(i.isdigit() for i in password)
or a more specific way:
any(map(str.isdigit, password))
And for your password entries, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
break
If you want to and a confirm password too, try:
while True:
password = input(""Please enter a strong password:")
if not any(x.isupper() for x in password):
print("Your password needs at least 1 upper case.")
elif not any(x.isdigit() for x in password):
print("You need to have at least 1 digit")
elif not any(x.islower() for x in password):
print("Your password needs at least 1 lower case.")
elif len(password) < 10:
print("Please make your password longer, up to at least 10 characters.")
print("Your password is only " + str(len(password)) + " characters long")
else:
passwordcon = input(""Please confirm your password:")
if passwordcon == password:
break
else:
print("Your passwords do not match, try again'")
any([p.isupper() for p in password])

Python: Problems with final result of password strength program

Lately, I was presented with a challenge exercise, aiming to create a program which checks the length of a password and then assesses it strength based on it being mixed case and containing numbers.
The part which determines whether the length of the password is suitable works absolutely fine, however the rest of the program seems to not work. I am unsure whether this is a logical or syntax error of some sort. I hope you can help me in some way.
import re
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
Password = ""
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
else:
#defines function for checking for presence of numbers in password
def hasNumbers(s):
return any(i.isdigit() for i in s)
#checks if password is all upper case
Is_upper = Password.isupper()
if Is_upper == "True":
Score = Score - 1
else:
Score = Score + 1
#checks if passwords is all lower case
Is_lower = Password.islower()
if Is_lower == "False":
Score = Score - 1
else:
Score = Score + 1
#checks if password contains a number
Number_presence = hasNumbers(Password)
if Number_presence == "True":
Score = Score + 1
else:
Score = Score - 1
#checks if password is just numbers
Only_numbers = Password.isdigit()
if Only_numbers == "True":
Score = Score - 1
#outputs weak, medium or strong to user based on score value
if Score <= 0:
print("Your password is absolutely rubbish!")
if Score == 1:
print("Your password is weak, you should try again.")
elif Score == 2:
print("Your password is medium, it should be OK.")
elif Score == 3:
print("Your password is strong, it is absolutely fine.")
else:
print("The program has experienced a problem. Please try again!")
exit()
Python has some pre-defined statements that are part of it. One of these is Boolean : True and False
When you call the built in isupper() function in python, it doesn't return a string, it returns a Boolean, and so does most other similar functions.
True and "True" are very different things. True is a Boolean type value, while "True" is just a string. This is a common mistake all new python programmers make, due to the fact that in python, you don't have to specify different value types like you do in c++ or Java. It is still important to know about data types as to avoid such fatal errors and to further advance your knowledge in Python :)
To read more about Data Types: http://developer.rhino3d.com/guides/rhinopython/python-datatypes/
I have looked at your code and fixed some mistakes ( not tested ):
import re
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
Password = ""
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
else:
#defines function for checking for presence of numbers in password
def hasNumbers(s):
return any(i.isdigit() for i in s)
#checks if password is all upper case
Is_upper = Password.isupper()
if Is_upper == True:
Score = Score - 1
else:
Score = Score + 1
#checks if passwords is all lower case
Is_lower = Password.islower()
if Is_lower == False:
Score = Score - 1
else:
Score = Score + 1
#checks if password contains a number
Number_presence = hasNumbers(Password)
if Number_presence == True:
Score = Score + 1
else:
Score = Score - 1
#checks if password is just numbers
Only_numbers = Password.isdigit()
if Only_numbers == True:
Score = Score - 1
#outputs weak, medium or strong to user based on score value
if Score <= 0:
print("Your password is absolutely rubbish!")
if Score == 1:
print("Your password is weak, you should try again.")
elif Score == 2:
print("Your password is medium, it should be OK.")
elif Score == 3:
print("Your password is strong, it is absolutely fine.")
else:
print("The program has experienced a problem. Please try again!")
exit()
*As a sidenote, you can make your program less verbose by just completley removing the == True and == False from your code. By default, if and while statements will check if a value is True or False, and run the code indented under them if it is True

How to replace a double while loop?

The program, which assesses password strength, initially checks whether the length of the password is correct (6-12) and whether the password contains extented ASCII characters, i.e. 127-255.
The problem I have is that if the user first inputs a password which is too short or too long, the program then doesn't check for extended characters in the next password, inputted by the user and vice-versa, with checking for extended characters first.
I implemented a double while loop, if that's the correct way of calling it, however it still didn't bring the desired effect.
import re
import time
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
#list for improvements to password printed out with score at the end
Improvements = []
Password = ""
#defines function for checking for presence of extended characters (i.e. ascii 128-255)
def hasExtended(s):
return any(ord(i) > 127 for i in s)
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
Extended_presence = hasExtended(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
#checks if password contains extended characters
#double while loops to allow for two conditions simultaneously
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
else:
#defines function for checking for presence of numbers
def hasNumbers(s):
return any(i.isdigit() for i in s)
#defines function for checking for presence of letters
def hasLetters(s):
return any(i.isalpha() for i in s)
#defines function for checking for presence of special characters
def hasSpecial(s):
return any(ord(i) < 48 for i in s)
#checks if password contains letters
Letter_presence = hasLetters(Password)
if not Letter_presence:
Score = Score - 1
Improvements.append("letters")
else:
Score = Score + 1
#checks if password is all upper case
Is_upper = Password.isupper()
if not Is_upper:
Score = Score + 1
else:
Score = Score - 1
Improvements.append("upper and lower case letters")
#checks if passwords is all lower case
Is_lower = Password.islower()
if not Is_lower:
Score = Score + 1
else:
Score = Score - 1
Improvements.append("upper and lower case letters")
#checks if password contains a number
Number_presence = hasNumbers(Password)
if not Number_presence:
Score = Score + 0
Improvements.append("numbers")
else:
Score = Score + 1
#checks if password is just numbers
Only_numbers = Password.isdigit()
if not Only_numbers:
Score = Score + 0
else:
Score = Score - 1
Improvements.append("other characters")
#checks if password contains special characters
Special_presence = hasSpecial(Password)
if not Special_presence:
Score = Score + 0
Improvements.append("special characters, such as '$'")
else:
Score = Score + 1
#outputs weak, medium or strong password to user and suggest improvements
if Score <= 2:
print("The program is processing your password...")
time.sleep(2)
print("Your password isn't acceptable! Please try again.")
print("Next time, remember to include", Improvements)
if Score == 3:
print("The program is processing your password...")
time.sleep(2)
print("Your password is weak, you should try again.")
print("Next time, remember to include", Improvements)
elif Score == 4:
print("The program is processing your password...")
time.sleep(2)
print("Your password is medium, it should be OK.")
print("Next time, remember to include", Improvements)
elif Score == 5:
print("The program is processing your password...")
time.sleep(2)
print("Your password is strong, it is absolutely fine.")
I would suggest you to write validator, a function that looks like this:
def validate_password(password):
... # check score, symbols and other, print whatever you want
return score
And then call it in a way like that one:
pass = input('Enter your password')
score = validate_password(pass)
while score <= 3:
pass = input('Enter another password')
score = validate_password(pass)
You can implement such scenario like below:
check_pass function will check for length of function
def hasExtended(s):
return any(ord(i) > 127 for i in s)
check_pass = lambda x: x>=6 and x<=12 # check for range of input value
password=input("Password: ")
if check_pass(len(password)) and not hasExtended(password):
print("Valid password")
else:
print("Do not use extended ascii characters, use password with minimum length of 6 and maximum length of 12")
to be more precise about error you can use nesting in below way:
if check_pass(len(password)) and not hasExtended(password):
print("Valid password")
elif check_pass(len(password)) and hasExtended(password):
print("do not use extended ascii character")
elif not check_pass(len(password)) and hasExtended(password):
print("password length should be between 6 to 12")
similarly if you want to check for invalid length of minimum lenght and maximum length separately.
If you wish to check all condition separately and then show success or failure you can do like below:
def verify_password(password):
if len(password) < 6:
print("require minimum 6 characters")
if len(password) > 12:
print("can not use more then 12 characters")
if hasExtended(password):
print("use only valid ascii characters")
else:
print("valid password")
return True
while not verify_password(password): # loop will never stops unless valid password or used break statement within
password = input("Password: ")
The function will check for three different condition if condition satisfied message will be printed else it will continue executing, at the end if it is valid password instead of printing anything it will print valid password and return True instead of None.
Try this code , and instead of while just use if in first checking codition of Extended_presence , You don't need while there because its already in the scope of previous while loop :
import re
print([chr(i) for i in range(127,200)])
import re
import time
#score variable, responsible for later defining if passwords is weak, medium or strong
Score = 0
#list for improvements to password printed out with score at the end
Improvements = []
Password = ""
#defines function for checking for presence of extended characters (i.e. ascii 128-255)
def hasExtended(s):
return any(ord(i) > 127 for i in s)
#inputs password
Password = input("Please enter a password:")
Password_length = len(Password)
Extended_presence = hasExtended(Password)
#checks password length (6-12), asks user to re-input until password is within boundaries
#checks if password contains extended characters
#double while loops to allow for two conditions simultaneously
while Password_length < 6 or Password_length > 12:
if Password_length < 6:
Outputted_length = "too short"
Outputted_criteria = "no shorter than 6 characters"
else:
Outputted_length = "too long"
Outputted_criteria = "no longer than 12 characters"
print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".")
Password = input("Please enter a password:")
Password_length = len(Password)
if Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
while Extended_presence:
print("Your password contains characters from the extended ASCII list. Please don't use these.")
Password = input("Please enter a password:")
Extended_presence = hasExtended(Password)
output:
Please enter a password:hel¢
Your password is too short . It has to be no shorter than 6 characters .
Please enter a password:hello¢
Your password contains characters from the extended ASCII list. Please don't use these.
Please enter a password:hello¢
Your password contains characters from the extended ASCII list. Please don't use these.
Please enter a password:hellllo#
Why don't you delegate your password check to a function and separate the user input from checking the password? That way you can ask the user as many times as you want without complex jumps. Something like:
def validate_password(password):
if len(password) < 6:
return 0, "Your password is too short, it has to be no shorter than 6 characters."
elif len(password) > 12: # why, tho?
return 0, "Your password is too long, it has to be no longer than 12 characters."
# these can be optimized but I'll leave that as an exercise for you
if any(ord(i) > 127 for i in password): # again, why?!
return 0, ("Your password contains characters from the extended ASCII list. "
"Please don't use these.")
score = 0
improvements = []
if any(i.isalpha() for i in password):
score += 1
if password.isupper() or password.islower():
score -= 1
improvements.append("upper and lower case letters")
else:
score += 1
else:
score -= 1
improvements.append("letters")
if any(i.isdigit() for i in password):
score += 1
if password.isdigit():
score -= 1
improvements.append("other characters")
else:
# score -= 1 # are you sure you don't want to reduce the score?
improvements.append("numbers")
if any(ord(i) < 48 for i in password):
score += 1
else:
# score -= 1 # are you sure you don't want to reduce the score?
improvements.append("special characters such as '$'")
return score, "Next time remember to include: {}".format(", ".join(improvements))
And now you can call it from wherever you want, as many times as you need:
while True:
candidate = input("Please enter a password: ")
print("The program is processing your password...") # why? this happens in an instant
score, message = validate_password(candidate)
time.sleep(2) # why are we making people wait for no reason?
if score <= 1:
print(message)
print("Please try again.")
elif score == 2:
print("Your password is weak, you should try again.")
print(message)
elif score == 3:
print("Your password is medium, it should be OK.")
print(message)
break
elif score == 4:
print("Your password is strong, it is absolutely fine.")
break
print("Accepted password: " + candidate)
And you can get an output as:
Please enter a password: dfld
The program is processing your password...
Your password is too short, it has to be no shorter than 6 characters.
Please try again.
Please enter a password: dfldsadlslads
The program is processing your password...
Your password is too long, it has to be no longer than 12 characters.
Please try again.
Please enter a password: dflds°
The program is processing your password...
Your password contains characters from the extended ASCII list. Please don't use these.
Please try again.
Please enter a password: ddlllsd
The program is processing your password...
Next time remember to include: upper and lower case letters, numbers, special characters
such as '$'
Please try again.
Please enter a password: ddlllsd12
The program is processing your password...
Next time remember to include: upper and lower case letters, special characters such as '$'
Please try again.
Please enter a password: Ddlllsd12
The program is processing your password...
Your password is medium, it should be OK.
Next time remember to include: special characters such as '$'
Accepted password: Ddlllsd12

Categories