i am trying to check if the user is putting a alpha character for the input and if they don't it prints a string. this whole program is for the user to pick if they want letter, numbers or special characters in there password.
this is my code that works but once i get to the special_characters while loop there is a logical error. when i type y i get the print("Invalied input, Try again! not y or n") in the else statement but if i enter n or anything else i get what the code does! i am very confused:
import string
alphabets = list(string.ascii_letters)
digits = list(string.digits)
special_characters = list("!@#$%^&*()")
PasswordCharacters = []
a = True
while a:
x = True
y = True
z = True
while x:
alphabets_2 = input("Would you like to include letters in your password?: ")
if alphabets_2.isalpha():
if alphabets_2 == "y":
PasswordCharacters.append(alphabets)
x = False
elif alphabets_2 == 'n':
x = False
else:
print("Invail Input, Try Again! not y or n")
if not alphabets_2.isalpha():
print("Invaild input! Try again, not a letter")
continue
while y:
digits_2 = input("Would you like to include digits in your password?: ")
if digits_2.isalpha():
if digits_2 == 'y':
PasswordCharacters.append(digits)
y = False
elif digits_2 == 'n':
y = False
else:
print("Invaild Input, Try Again! not y or n")
if not digits_2.isalpha():
print("Invaild input! Try Again! not a letter")
continue
while z:
special_characters_2 = input("would you like to include special characters in your password?: ")
if special_characters_2.isalpha():
if special_characters == 'y':
PasswordCharacters.append(special_characters)
z = False
elif special_characters_2 == 'n':
z = False
else:
print("Invaild input, Try again! not y or n")
if not special_characters_2.isalpha():
print("Invaild input, Try again! not a letter")
continue
a = False
i get a logical error that when i enter y i get the print statement for the else block
CodePudding user response:
A typo:
if special_characters == 'y':
Should be special_characters2
.
And you dont actually need to convert string.ascii_letters and etc. to a list because it is basically.. a list already
CodePudding user response:
You have a typo:
if special_characters_2.isalpha():
if special_characters == 'y': # should be special_characters_2
It's easy to have typos like this when you have a lot of copied and pasted code. Consider putting this question-and-answer loop in a function:
def ask_y_or_n(question):
while True:
answer = input(question)
if answer == "y":
return True
if answer == "n":
return False
if answer.isalpha():
print("Invaild Input, Try Again! not y or n")
else:
print("Invaild input! Try Again! not a letter")
Then you can replace the entirety of the x/y/z section of the code with:
for desc, characters in [
("letters", alphabets),
("digits", digits),
("special characters", special_characters),
]:
if ask_y_or_n(f"Would you like to include {desc} in your password?: "):
PasswordCharacters.append(characters)