Python:如何在“中显示错误”;创建有效密码";并指出第一个字符是否为字母?
我正在尝试创建一个具有典型要求的密码,如至少有1个大写/小写等。如果根据要求密码无效,我们必须显示错误,以便用户再次尝试更正 我从一个while循环开始,这样最终用户可以选择是否继续进行另一个测试。这些是我做的一般步骤 最后,如果确定用户的文本输入无效,我必须显示他/她的错误。这是我现在的主要问题。建议之后代码会更好。现在我只需要以某种方式显示错误 下面是我的代码是如何运行的Python:如何在“中显示错误”;创建有效密码";并指出第一个字符是否为字母?,python,if-statement,passwords,counter,program-slicing,Python,If Statement,Passwords,Counter,Program Slicing,我正在尝试创建一个具有典型要求的密码,如至少有1个大写/小写等。如果根据要求密码无效,我们必须显示错误,以便用户再次尝试更正 我从一个while循环开始,这样最终用户可以选择是否继续进行另一个测试。这些是我做的一般步骤 最后,如果确定用户的文本输入无效,我必须显示他/她的错误。这是我现在的主要问题。建议之后代码会更好。现在我只需要以某种方式显示错误 下面是我的代码是如何运行的 while True: pw = input('Enter password to be tested if va
while True:
pw = input('Enter password to be tested if valid or not: ')
correct_length = False
uc_letter = False
lc_letter = False
digit = False
no_blanks = True
first_letter = False
if len(pw) >= 8:
correct_length = True
for ch in pw:
if ch.isupper():
uc_letter = True
if ch.islower():
lc_letter = True
if pw.isalnum():
digit = True
if pw[:1].isalpha():
first_letter = True
if not pw.find(' '):
no_blanks = True
if correct_length and uc_letter and lc_letter and digit and first_letter and no_blanks:
valid_pw = True
else:
valid_pw = False
#This is the part where I'm suppose to display the errors if the user gets it wrong.
#Initially, in the test for ch. above, I put in an else: with a print statement but because of the for- statement, it prints it out for every single character.
answer = input('Try another password input? y/n ')
if answer == 'y'
answer = True
else:
break
isdigit
仅返回True
或False
if ch.isdigit():
如果要检查前两个字符是否为数字,请在循环外执行:
if pw[:2].isdigit():
digit = True
for ch in pw:
...
并检查字符串中是否有空格:
if not pw.find(' '):
no_blanks = True
或者,如果要转义所有类型的空格和空格,包括换行符:
import string
...
if not any(c in string.whitespace for c in pw):
no_blanks = True
for ch in pw:
...
isdigit
仅返回True
或False
if ch.isdigit():
如果要检查前两个字符是否为数字,请在循环外执行:
if pw[:2].isdigit():
digit = True
for ch in pw:
...
并检查字符串中是否有空格:
if not pw.find(' '):
no_blanks = True
或者,如果要转义所有类型的空格和空格,包括换行符:
import string
...
if not any(c in string.whitespace for c in pw):
no_blanks = True
for ch in pw:
...
对于我将使用的空白(不要忘记导入字符串): 这将检查所有类型的空白,例如空格和制表符 对于For循环之前我将定义的数字
dig_count=0
在for循环中:
if ch.isdigit():
dig_count += 1
if dig_count >= 2:
digit = True
在for循环之后:
if ch.isdigit():
dig_count += 1
if dig_count >= 2:
digit = True
对于我将使用的空白(不要忘记导入字符串): 这将检查所有类型的空白,例如空格和制表符 对于For循环之前我将定义的数字
dig_count=0
在for循环中:
if ch.isdigit():
dig_count += 1
if dig_count >= 2:
digit = True
在for循环之后:
if ch.isdigit():
dig_count += 1
if dig_count >= 2:
digit = True
非常感谢。我用你的建议来调整我的代码。效果好多了。在问题要求用户继续之前,当密码已确定为有效时,我仍然无法显示用户的错误。很高兴听到这有帮助!你可以吗?:)对不起,链接错误。修正了,接受按钮在问题的左侧:)嗯。。我认为这是一个与此不同的问题。发布一个新问题,并准确说明“显示用户错误”的含义。谢谢!我用你的建议来调整我的代码。效果好多了。在问题要求用户继续之前,当密码已确定为有效时,我仍然无法显示用户的错误。很高兴听到这有帮助!你可以吗?:)对不起,链接错误。修正了,接受按钮在问题的左侧:)嗯。。我认为这是一个与此不同的问题。发布一个新问题,并准确地说明“显示用户错误”是什么意思,这是一个很好的解决方案!使用
string.whitespace非常简洁+1很好的解决方案!使用string.whitespace非常简洁+1.