如何显示用户的错误?

时间:2013-12-02 14:57:22

标签: python validation

我的用户想要输入密码,我应该检查它是否有效。到目前为止,我已经删除了代码以检查它是否有效/无效。现在,下一步(确定它无效后)是告诉用户它无效以及为什么他们的密码不是有效选项。

while True:
   pw = input('Enter password to be tested if valid or not: ')
   correct_length = False
   uc_letter = False
   lc_letter = 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
      print('Your password to be tested is valid.')
   else:
      valid_pw = False
      print('Your password to be tested is not valid because:')
      print(----------)
      #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

2 个答案:

答案 0 :(得分:1)

嗯......我想你可以简单地加上额外的else语句,然后引发一个错误:

   if not pw.find(' '):
      no_blanks = True
   else:
      raise ValueError('Invalid input!')

与你的其他条件相似。

如果您希望循环继续,您只需打印消息,然后继续:

else:
    print("Invalid input! Please re enter it:")
    continue

希望这有帮助!

答案 1 :(得分:0)

您检查所有有效条件。正确的方法是,不是像这样检查条件是真的,

if len(pw) >= 8:
   correct_length = True

检查

if len(pw) < 8:
   correct_length = False
   print "Password not lengthy"

这有助于识别错误。基本上,找到所有评估为false的内容,以便用户可以指出这些错误。