我正在尝试检查用户是否为输入输入了一个阿尔法字符,如果没有,则会打印一个字符串。这整个程序是为用户选择,如果他们想要字母,数字或特殊字符的密码。
这是我的代码,但一旦进入special_characterswhile循环,就会出现逻辑错误。当我输入y时,我会在else语句中得到print("无效输入,重试!不是y或n"(,但如果我输入n或其他任何内容,我会得到代码的作用!我很困惑:
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
我得到一个逻辑错误,当我输入y时,我得到了其他块的打印语句
打字错误:
if special_characters == 'y':
应为special_characters2
。
实际上,您不需要将字符串、ascii字母等转换为列表,因为它基本上是。。一个已经的列表
您有一个打字错误:
if special_characters_2.isalpha():
if special_characters == 'y': # should be special_characters_2
当你有很多复制粘贴的代码时,很容易出现这样的拼写错误。考虑将这个问答循环放在一个函数中:
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")
然后,您可以将代码的整个x/y/z部分替换为:
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)