Strong Password Detection in PythonCheck a string for any occurrences of certain character classesRegex password strength testPassword generator in Python 3Python 3.4 password generatorPython username and password programPython's str.isAlpha(), reimplemented without Unicode supportFind the minimum number of characters to add to make password strongPassword generator in Python 3.7Strong Password DetectionStrong password checker in Python

Is this more than a packing puzzle?

Why doesn't Anakin's lightsaber explode when it's chopped in half on Geonosis?

how to generate correct single and double quotes in tex

Was adding milk to tea started to reduce employee tea break time?

(algebraic topology) question about the cellular approximation theorem

Align by center of symbol

What impact would a dragon the size of Asia have on the environment?

Postgresql numeric and decimal is automatically rounding off

Hot object in a vacuum

Can I capture stereo IQ signals from WebSDR?

What is the English equivalent of 干物女 (dried fish woman)?

What is this old "lemon-squeezer" shaped pan

Can a pizza stone be fixed after soap has been used to clean it?

Why hasn't the U.S. government paid war reparations to any country it attacked?

Absconding a company after 1st day of joining

GPIO and Python - GPIO.output() not working

Why does the Earth have a z-component at the start of the J2000 epoch?

Are L-functions uniquely determined by their values at negative integers?

Are there any double stars that I can actually see orbit each other?

What exactly is the Tension force?

Could the crash sites of the Apollo 11 and 16 LMs be seen by the LRO?

Is `curl something | sudo bash -` a reasonably safe installation method?

Are villager price increases due to killing them temporary?

Confused about 誘われて (Sasowarete)



Strong Password Detection in Python


Check a string for any occurrences of certain character classesRegex password strength testPassword generator in Python 3Python 3.4 password generatorPython username and password programPython's str.isAlpha(), reimplemented without Unicode supportFind the minimum number of characters to add to make password strongPassword generator in Python 3.7Strong Password DetectionStrong password checker in Python






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


This is a problem from "Automate the boring stuff".




Write a function that uses regular expressions to make sure the password
string it is passed is strong. A strong password is defined as one that is at
least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.




How to improve this code?



#! /usr/bin/python3

import re

def uppercase_check(password):
if re.search('[A-Z]', password): #atleast one uppercase character
return True
return False

def lowercase_check(password):
if re.search('[a-z]', password): #atleast one lowercase character
return True
return False

def digit_check(password):
if re.search('[0-9]', password): #atleast one digit
return True
return False


def user_input_password_check():
password = input("Enter password : ")
#atleast 8 character long
if len(password) >= 8 and uppercase_check(password) and lowercase_check(password) and digit_check(password):
print("Strong Password")
else:
print("Weak Password")

user_input_password_check()









share|improve this question











$endgroup$







  • 3




    $begingroup$
    Please give some feedback to the authors of "Automate the boring stuff" that their task is misguided. Hopefully they will remove it then.
    $endgroup$
    – Roland Illig
    Jul 6 at 15:05










  • $begingroup$
    obXKCD
    $endgroup$
    – Barmar
    Jul 6 at 17:09






  • 4




    $begingroup$
    Aside: Obligatory Security.SE question about above XKCD. Also an article about how NIST changed their recommendations on the matter as well. In brief, this mindset about password "strength" is rapidly being outdated. Your question is fine, though, since you're given a problem and asking for a review of the solution. Just realize that this is a toy problem and not something that you should be implementing in production code. (Note that password security is more often done wrong than right, as well.)
    $endgroup$
    – jpmc26
    Jul 7 at 2:44











  • $begingroup$
    @jpmc26 Welp, it's better to have such a check than no check at all. Otherwise 2-character passwords are allowed too.
    $endgroup$
    – Mast
    Jul 7 at 18:49










  • $begingroup$
    @Mast Have a length check. That's the minimum. If you're going to do more, filter out common passwords (like at least the 10000 most common) and maybe some patterns or keywords that make the password easier to guess. Put visible recommendations for random passwords and 2-factor auth in your app. The kinds of requirements here actually reduce the password space and encourage poor password choice.
    $endgroup$
    – jpmc26
    Jul 8 at 5:33


















4












$begingroup$


This is a problem from "Automate the boring stuff".




Write a function that uses regular expressions to make sure the password
string it is passed is strong. A strong password is defined as one that is at
least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.




How to improve this code?



#! /usr/bin/python3

import re

def uppercase_check(password):
if re.search('[A-Z]', password): #atleast one uppercase character
return True
return False

def lowercase_check(password):
if re.search('[a-z]', password): #atleast one lowercase character
return True
return False

def digit_check(password):
if re.search('[0-9]', password): #atleast one digit
return True
return False


def user_input_password_check():
password = input("Enter password : ")
#atleast 8 character long
if len(password) >= 8 and uppercase_check(password) and lowercase_check(password) and digit_check(password):
print("Strong Password")
else:
print("Weak Password")

user_input_password_check()









share|improve this question











$endgroup$







  • 3




    $begingroup$
    Please give some feedback to the authors of "Automate the boring stuff" that their task is misguided. Hopefully they will remove it then.
    $endgroup$
    – Roland Illig
    Jul 6 at 15:05










  • $begingroup$
    obXKCD
    $endgroup$
    – Barmar
    Jul 6 at 17:09






  • 4




    $begingroup$
    Aside: Obligatory Security.SE question about above XKCD. Also an article about how NIST changed their recommendations on the matter as well. In brief, this mindset about password "strength" is rapidly being outdated. Your question is fine, though, since you're given a problem and asking for a review of the solution. Just realize that this is a toy problem and not something that you should be implementing in production code. (Note that password security is more often done wrong than right, as well.)
    $endgroup$
    – jpmc26
    Jul 7 at 2:44











  • $begingroup$
    @jpmc26 Welp, it's better to have such a check than no check at all. Otherwise 2-character passwords are allowed too.
    $endgroup$
    – Mast
    Jul 7 at 18:49










  • $begingroup$
    @Mast Have a length check. That's the minimum. If you're going to do more, filter out common passwords (like at least the 10000 most common) and maybe some patterns or keywords that make the password easier to guess. Put visible recommendations for random passwords and 2-factor auth in your app. The kinds of requirements here actually reduce the password space and encourage poor password choice.
    $endgroup$
    – jpmc26
    Jul 8 at 5:33














4












4








4





$begingroup$


This is a problem from "Automate the boring stuff".




Write a function that uses regular expressions to make sure the password
string it is passed is strong. A strong password is defined as one that is at
least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.




How to improve this code?



#! /usr/bin/python3

import re

def uppercase_check(password):
if re.search('[A-Z]', password): #atleast one uppercase character
return True
return False

def lowercase_check(password):
if re.search('[a-z]', password): #atleast one lowercase character
return True
return False

def digit_check(password):
if re.search('[0-9]', password): #atleast one digit
return True
return False


def user_input_password_check():
password = input("Enter password : ")
#atleast 8 character long
if len(password) >= 8 and uppercase_check(password) and lowercase_check(password) and digit_check(password):
print("Strong Password")
else:
print("Weak Password")

user_input_password_check()









share|improve this question











$endgroup$




This is a problem from "Automate the boring stuff".




Write a function that uses regular expressions to make sure the password
string it is passed is strong. A strong password is defined as one that is at
least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.




How to improve this code?



#! /usr/bin/python3

import re

def uppercase_check(password):
if re.search('[A-Z]', password): #atleast one uppercase character
return True
return False

def lowercase_check(password):
if re.search('[a-z]', password): #atleast one lowercase character
return True
return False

def digit_check(password):
if re.search('[0-9]', password): #atleast one digit
return True
return False


def user_input_password_check():
password = input("Enter password : ")
#atleast 8 character long
if len(password) >= 8 and uppercase_check(password) and lowercase_check(password) and digit_check(password):
print("Strong Password")
else:
print("Weak Password")

user_input_password_check()






python beginner python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 6 at 13:50









Reinderien

6,21610 silver badges29 bronze badges




6,21610 silver badges29 bronze badges










asked Jul 6 at 7:12









codercoder

1,0621 gold badge15 silver badges42 bronze badges




1,0621 gold badge15 silver badges42 bronze badges







  • 3




    $begingroup$
    Please give some feedback to the authors of "Automate the boring stuff" that their task is misguided. Hopefully they will remove it then.
    $endgroup$
    – Roland Illig
    Jul 6 at 15:05










  • $begingroup$
    obXKCD
    $endgroup$
    – Barmar
    Jul 6 at 17:09






  • 4




    $begingroup$
    Aside: Obligatory Security.SE question about above XKCD. Also an article about how NIST changed their recommendations on the matter as well. In brief, this mindset about password "strength" is rapidly being outdated. Your question is fine, though, since you're given a problem and asking for a review of the solution. Just realize that this is a toy problem and not something that you should be implementing in production code. (Note that password security is more often done wrong than right, as well.)
    $endgroup$
    – jpmc26
    Jul 7 at 2:44











  • $begingroup$
    @jpmc26 Welp, it's better to have such a check than no check at all. Otherwise 2-character passwords are allowed too.
    $endgroup$
    – Mast
    Jul 7 at 18:49










  • $begingroup$
    @Mast Have a length check. That's the minimum. If you're going to do more, filter out common passwords (like at least the 10000 most common) and maybe some patterns or keywords that make the password easier to guess. Put visible recommendations for random passwords and 2-factor auth in your app. The kinds of requirements here actually reduce the password space and encourage poor password choice.
    $endgroup$
    – jpmc26
    Jul 8 at 5:33













  • 3




    $begingroup$
    Please give some feedback to the authors of "Automate the boring stuff" that their task is misguided. Hopefully they will remove it then.
    $endgroup$
    – Roland Illig
    Jul 6 at 15:05










  • $begingroup$
    obXKCD
    $endgroup$
    – Barmar
    Jul 6 at 17:09






  • 4




    $begingroup$
    Aside: Obligatory Security.SE question about above XKCD. Also an article about how NIST changed their recommendations on the matter as well. In brief, this mindset about password "strength" is rapidly being outdated. Your question is fine, though, since you're given a problem and asking for a review of the solution. Just realize that this is a toy problem and not something that you should be implementing in production code. (Note that password security is more often done wrong than right, as well.)
    $endgroup$
    – jpmc26
    Jul 7 at 2:44











  • $begingroup$
    @jpmc26 Welp, it's better to have such a check than no check at all. Otherwise 2-character passwords are allowed too.
    $endgroup$
    – Mast
    Jul 7 at 18:49










  • $begingroup$
    @Mast Have a length check. That's the minimum. If you're going to do more, filter out common passwords (like at least the 10000 most common) and maybe some patterns or keywords that make the password easier to guess. Put visible recommendations for random passwords and 2-factor auth in your app. The kinds of requirements here actually reduce the password space and encourage poor password choice.
    $endgroup$
    – jpmc26
    Jul 8 at 5:33








3




3




$begingroup$
Please give some feedback to the authors of "Automate the boring stuff" that their task is misguided. Hopefully they will remove it then.
$endgroup$
– Roland Illig
Jul 6 at 15:05




$begingroup$
Please give some feedback to the authors of "Automate the boring stuff" that their task is misguided. Hopefully they will remove it then.
$endgroup$
– Roland Illig
Jul 6 at 15:05












$begingroup$
obXKCD
$endgroup$
– Barmar
Jul 6 at 17:09




$begingroup$
obXKCD
$endgroup$
– Barmar
Jul 6 at 17:09




4




4




$begingroup$
Aside: Obligatory Security.SE question about above XKCD. Also an article about how NIST changed their recommendations on the matter as well. In brief, this mindset about password "strength" is rapidly being outdated. Your question is fine, though, since you're given a problem and asking for a review of the solution. Just realize that this is a toy problem and not something that you should be implementing in production code. (Note that password security is more often done wrong than right, as well.)
$endgroup$
– jpmc26
Jul 7 at 2:44





$begingroup$
Aside: Obligatory Security.SE question about above XKCD. Also an article about how NIST changed their recommendations on the matter as well. In brief, this mindset about password "strength" is rapidly being outdated. Your question is fine, though, since you're given a problem and asking for a review of the solution. Just realize that this is a toy problem and not something that you should be implementing in production code. (Note that password security is more often done wrong than right, as well.)
$endgroup$
– jpmc26
Jul 7 at 2:44













$begingroup$
@jpmc26 Welp, it's better to have such a check than no check at all. Otherwise 2-character passwords are allowed too.
$endgroup$
– Mast
Jul 7 at 18:49




$begingroup$
@jpmc26 Welp, it's better to have such a check than no check at all. Otherwise 2-character passwords are allowed too.
$endgroup$
– Mast
Jul 7 at 18:49












$begingroup$
@Mast Have a length check. That's the minimum. If you're going to do more, filter out common passwords (like at least the 10000 most common) and maybe some patterns or keywords that make the password easier to guess. Put visible recommendations for random passwords and 2-factor auth in your app. The kinds of requirements here actually reduce the password space and encourage poor password choice.
$endgroup$
– jpmc26
Jul 8 at 5:33





$begingroup$
@Mast Have a length check. That's the minimum. If you're going to do more, filter out common passwords (like at least the 10000 most common) and maybe some patterns or keywords that make the password easier to guess. Put visible recommendations for random passwords and 2-factor auth in your app. The kinds of requirements here actually reduce the password space and encourage poor password choice.
$endgroup$
– jpmc26
Jul 8 at 5:33











4 Answers
4






active

oldest

votes


















8












$begingroup$

I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply all.



rexes = ('[A-Z]', '[a-z]', '[0-9]')
# ...
if len(password) >= 8 and all(re.search(r, password) for r in rexes)):
print('Strong password')





share|improve this answer









$endgroup$








  • 2




    $begingroup$
    While it doesn't use regexps just thought it worth pointing out an alternative using unicodedata.category. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: if len(password) >= 8 and 'Ll', 'Lu', 'Nd'.issubset(unicodedata.category(ch) for ch in password)...
    $endgroup$
    – Jon Clements
    Jul 6 at 17:34











  • $begingroup$
    @JonClements True, and that approach is probably more friendly to i18n
    $endgroup$
    – Reinderien
    Jul 6 at 23:09


















5












$begingroup$

First, please note that this security measure has been thoroughly debunked (although the reasons why are complex and psychological). Any code resulting from this exercise is therefore by the standards of the security community following an anti-pattern, and should not be used no matter how polished.



That said:




  • Rather than the



    if something:
    return True
    return False


    a more readable pattern is simply return something.



  • This code would be more scriptable if it either took passwords as arguments (using argparse) or read one password per line from standard input.


  • Another way to make this more scriptable is to use the really common



    if __name__ == "__main__":
    sys.exit(main())


    pattern.







share|improve this answer











$endgroup$




















    4












    $begingroup$

    Firstly: what @l0b0 said. This is fundamentally misguided, and you're better off doing an actual entropy measurement.



    As for your check functions, you can rewrite them as:



    def uppercase_check(password: str) -> bool:
    return bool(re.search('[A-Z]', password))


    Note that it uses proper type-hinting, and doesn't need an if.






    share|improve this answer









    $endgroup$




















      2












      $begingroup$

      • You preform multiple function calls which are all very related. You can cram each of the regex checks into one if statement.

      • You should use a main guard to ensure that the code is only running if this file is the main one, so that any programs importing this file don't have any issues.

      • You should also use docstrings. These allow potential documentation to display information about what the methods(s) are supposed to accomplish.

      • Using condensed if statements can clean up the messiness of having if: ... else: ... when there is just one statement being executed in each block.

      Here is the updated code:



      #! /usr/bin/python3

      import re

      def check(password):
      """
      Ensures password has at least one uppercase, one lowercase, and one digit
      """
      return False if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password) else True

      if __name__ == '__main__':
      password = input("Enter password: ")
      print("Strong password") if check(password) else print("Weak Password")





      share|improve this answer









      $endgroup$








      • 6




        $begingroup$
        return False if not isn't the best way to go about this. Instead, cast to bool.
        $endgroup$
        – Reinderien
        Jul 6 at 13:51






      • 2




        $begingroup$
        You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is return has_digits and has_upper and has_lower.
        $endgroup$
        – Roland Illig
        Jul 6 at 15:02










      • $begingroup$
        Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an any call.
        $endgroup$
        – jpmc26
        Jul 7 at 2:59














      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "196"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223600%2fstrong-password-detection-in-python%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      8












      $begingroup$

      I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply all.



      rexes = ('[A-Z]', '[a-z]', '[0-9]')
      # ...
      if len(password) >= 8 and all(re.search(r, password) for r in rexes)):
      print('Strong password')





      share|improve this answer









      $endgroup$








      • 2




        $begingroup$
        While it doesn't use regexps just thought it worth pointing out an alternative using unicodedata.category. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: if len(password) >= 8 and 'Ll', 'Lu', 'Nd'.issubset(unicodedata.category(ch) for ch in password)...
        $endgroup$
        – Jon Clements
        Jul 6 at 17:34











      • $begingroup$
        @JonClements True, and that approach is probably more friendly to i18n
        $endgroup$
        – Reinderien
        Jul 6 at 23:09















      8












      $begingroup$

      I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply all.



      rexes = ('[A-Z]', '[a-z]', '[0-9]')
      # ...
      if len(password) >= 8 and all(re.search(r, password) for r in rexes)):
      print('Strong password')





      share|improve this answer









      $endgroup$








      • 2




        $begingroup$
        While it doesn't use regexps just thought it worth pointing out an alternative using unicodedata.category. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: if len(password) >= 8 and 'Ll', 'Lu', 'Nd'.issubset(unicodedata.category(ch) for ch in password)...
        $endgroup$
        – Jon Clements
        Jul 6 at 17:34











      • $begingroup$
        @JonClements True, and that approach is probably more friendly to i18n
        $endgroup$
        – Reinderien
        Jul 6 at 23:09













      8












      8








      8





      $begingroup$

      I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply all.



      rexes = ('[A-Z]', '[a-z]', '[0-9]')
      # ...
      if len(password) >= 8 and all(re.search(r, password) for r in rexes)):
      print('Strong password')





      share|improve this answer









      $endgroup$



      I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply all.



      rexes = ('[A-Z]', '[a-z]', '[0-9]')
      # ...
      if len(password) >= 8 and all(re.search(r, password) for r in rexes)):
      print('Strong password')






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jul 6 at 14:05









      ReinderienReinderien

      6,21610 silver badges29 bronze badges




      6,21610 silver badges29 bronze badges







      • 2




        $begingroup$
        While it doesn't use regexps just thought it worth pointing out an alternative using unicodedata.category. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: if len(password) >= 8 and 'Ll', 'Lu', 'Nd'.issubset(unicodedata.category(ch) for ch in password)...
        $endgroup$
        – Jon Clements
        Jul 6 at 17:34











      • $begingroup$
        @JonClements True, and that approach is probably more friendly to i18n
        $endgroup$
        – Reinderien
        Jul 6 at 23:09












      • 2




        $begingroup$
        While it doesn't use regexps just thought it worth pointing out an alternative using unicodedata.category. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: if len(password) >= 8 and 'Ll', 'Lu', 'Nd'.issubset(unicodedata.category(ch) for ch in password)...
        $endgroup$
        – Jon Clements
        Jul 6 at 17:34











      • $begingroup$
        @JonClements True, and that approach is probably more friendly to i18n
        $endgroup$
        – Reinderien
        Jul 6 at 23:09







      2




      2




      $begingroup$
      While it doesn't use regexps just thought it worth pointing out an alternative using unicodedata.category. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: if len(password) >= 8 and 'Ll', 'Lu', 'Nd'.issubset(unicodedata.category(ch) for ch in password)...
      $endgroup$
      – Jon Clements
      Jul 6 at 17:34





      $begingroup$
      While it doesn't use regexps just thought it worth pointing out an alternative using unicodedata.category. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: if len(password) >= 8 and 'Ll', 'Lu', 'Nd'.issubset(unicodedata.category(ch) for ch in password)...
      $endgroup$
      – Jon Clements
      Jul 6 at 17:34













      $begingroup$
      @JonClements True, and that approach is probably more friendly to i18n
      $endgroup$
      – Reinderien
      Jul 6 at 23:09




      $begingroup$
      @JonClements True, and that approach is probably more friendly to i18n
      $endgroup$
      – Reinderien
      Jul 6 at 23:09













      5












      $begingroup$

      First, please note that this security measure has been thoroughly debunked (although the reasons why are complex and psychological). Any code resulting from this exercise is therefore by the standards of the security community following an anti-pattern, and should not be used no matter how polished.



      That said:




      • Rather than the



        if something:
        return True
        return False


        a more readable pattern is simply return something.



      • This code would be more scriptable if it either took passwords as arguments (using argparse) or read one password per line from standard input.


      • Another way to make this more scriptable is to use the really common



        if __name__ == "__main__":
        sys.exit(main())


        pattern.







      share|improve this answer











      $endgroup$

















        5












        $begingroup$

        First, please note that this security measure has been thoroughly debunked (although the reasons why are complex and psychological). Any code resulting from this exercise is therefore by the standards of the security community following an anti-pattern, and should not be used no matter how polished.



        That said:




        • Rather than the



          if something:
          return True
          return False


          a more readable pattern is simply return something.



        • This code would be more scriptable if it either took passwords as arguments (using argparse) or read one password per line from standard input.


        • Another way to make this more scriptable is to use the really common



          if __name__ == "__main__":
          sys.exit(main())


          pattern.







        share|improve this answer











        $endgroup$















          5












          5








          5





          $begingroup$

          First, please note that this security measure has been thoroughly debunked (although the reasons why are complex and psychological). Any code resulting from this exercise is therefore by the standards of the security community following an anti-pattern, and should not be used no matter how polished.



          That said:




          • Rather than the



            if something:
            return True
            return False


            a more readable pattern is simply return something.



          • This code would be more scriptable if it either took passwords as arguments (using argparse) or read one password per line from standard input.


          • Another way to make this more scriptable is to use the really common



            if __name__ == "__main__":
            sys.exit(main())


            pattern.







          share|improve this answer











          $endgroup$



          First, please note that this security measure has been thoroughly debunked (although the reasons why are complex and psychological). Any code resulting from this exercise is therefore by the standards of the security community following an anti-pattern, and should not be used no matter how polished.



          That said:




          • Rather than the



            if something:
            return True
            return False


            a more readable pattern is simply return something.



          • This code would be more scriptable if it either took passwords as arguments (using argparse) or read one password per line from standard input.


          • Another way to make this more scriptable is to use the really common



            if __name__ == "__main__":
            sys.exit(main())


            pattern.








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 6 at 7:46

























          answered Jul 6 at 7:38









          l0b0l0b0

          6,03913 silver badges30 bronze badges




          6,03913 silver badges30 bronze badges





















              4












              $begingroup$

              Firstly: what @l0b0 said. This is fundamentally misguided, and you're better off doing an actual entropy measurement.



              As for your check functions, you can rewrite them as:



              def uppercase_check(password: str) -> bool:
              return bool(re.search('[A-Z]', password))


              Note that it uses proper type-hinting, and doesn't need an if.






              share|improve this answer









              $endgroup$

















                4












                $begingroup$

                Firstly: what @l0b0 said. This is fundamentally misguided, and you're better off doing an actual entropy measurement.



                As for your check functions, you can rewrite them as:



                def uppercase_check(password: str) -> bool:
                return bool(re.search('[A-Z]', password))


                Note that it uses proper type-hinting, and doesn't need an if.






                share|improve this answer









                $endgroup$















                  4












                  4








                  4





                  $begingroup$

                  Firstly: what @l0b0 said. This is fundamentally misguided, and you're better off doing an actual entropy measurement.



                  As for your check functions, you can rewrite them as:



                  def uppercase_check(password: str) -> bool:
                  return bool(re.search('[A-Z]', password))


                  Note that it uses proper type-hinting, and doesn't need an if.






                  share|improve this answer









                  $endgroup$



                  Firstly: what @l0b0 said. This is fundamentally misguided, and you're better off doing an actual entropy measurement.



                  As for your check functions, you can rewrite them as:



                  def uppercase_check(password: str) -> bool:
                  return bool(re.search('[A-Z]', password))


                  Note that it uses proper type-hinting, and doesn't need an if.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 6 at 13:57









                  ReinderienReinderien

                  6,21610 silver badges29 bronze badges




                  6,21610 silver badges29 bronze badges





















                      2












                      $begingroup$

                      • You preform multiple function calls which are all very related. You can cram each of the regex checks into one if statement.

                      • You should use a main guard to ensure that the code is only running if this file is the main one, so that any programs importing this file don't have any issues.

                      • You should also use docstrings. These allow potential documentation to display information about what the methods(s) are supposed to accomplish.

                      • Using condensed if statements can clean up the messiness of having if: ... else: ... when there is just one statement being executed in each block.

                      Here is the updated code:



                      #! /usr/bin/python3

                      import re

                      def check(password):
                      """
                      Ensures password has at least one uppercase, one lowercase, and one digit
                      """
                      return False if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password) else True

                      if __name__ == '__main__':
                      password = input("Enter password: ")
                      print("Strong password") if check(password) else print("Weak Password")





                      share|improve this answer









                      $endgroup$








                      • 6




                        $begingroup$
                        return False if not isn't the best way to go about this. Instead, cast to bool.
                        $endgroup$
                        – Reinderien
                        Jul 6 at 13:51






                      • 2




                        $begingroup$
                        You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is return has_digits and has_upper and has_lower.
                        $endgroup$
                        – Roland Illig
                        Jul 6 at 15:02










                      • $begingroup$
                        Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an any call.
                        $endgroup$
                        – jpmc26
                        Jul 7 at 2:59
















                      2












                      $begingroup$

                      • You preform multiple function calls which are all very related. You can cram each of the regex checks into one if statement.

                      • You should use a main guard to ensure that the code is only running if this file is the main one, so that any programs importing this file don't have any issues.

                      • You should also use docstrings. These allow potential documentation to display information about what the methods(s) are supposed to accomplish.

                      • Using condensed if statements can clean up the messiness of having if: ... else: ... when there is just one statement being executed in each block.

                      Here is the updated code:



                      #! /usr/bin/python3

                      import re

                      def check(password):
                      """
                      Ensures password has at least one uppercase, one lowercase, and one digit
                      """
                      return False if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password) else True

                      if __name__ == '__main__':
                      password = input("Enter password: ")
                      print("Strong password") if check(password) else print("Weak Password")





                      share|improve this answer









                      $endgroup$








                      • 6




                        $begingroup$
                        return False if not isn't the best way to go about this. Instead, cast to bool.
                        $endgroup$
                        – Reinderien
                        Jul 6 at 13:51






                      • 2




                        $begingroup$
                        You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is return has_digits and has_upper and has_lower.
                        $endgroup$
                        – Roland Illig
                        Jul 6 at 15:02










                      • $begingroup$
                        Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an any call.
                        $endgroup$
                        – jpmc26
                        Jul 7 at 2:59














                      2












                      2








                      2





                      $begingroup$

                      • You preform multiple function calls which are all very related. You can cram each of the regex checks into one if statement.

                      • You should use a main guard to ensure that the code is only running if this file is the main one, so that any programs importing this file don't have any issues.

                      • You should also use docstrings. These allow potential documentation to display information about what the methods(s) are supposed to accomplish.

                      • Using condensed if statements can clean up the messiness of having if: ... else: ... when there is just one statement being executed in each block.

                      Here is the updated code:



                      #! /usr/bin/python3

                      import re

                      def check(password):
                      """
                      Ensures password has at least one uppercase, one lowercase, and one digit
                      """
                      return False if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password) else True

                      if __name__ == '__main__':
                      password = input("Enter password: ")
                      print("Strong password") if check(password) else print("Weak Password")





                      share|improve this answer









                      $endgroup$



                      • You preform multiple function calls which are all very related. You can cram each of the regex checks into one if statement.

                      • You should use a main guard to ensure that the code is only running if this file is the main one, so that any programs importing this file don't have any issues.

                      • You should also use docstrings. These allow potential documentation to display information about what the methods(s) are supposed to accomplish.

                      • Using condensed if statements can clean up the messiness of having if: ... else: ... when there is just one statement being executed in each block.

                      Here is the updated code:



                      #! /usr/bin/python3

                      import re

                      def check(password):
                      """
                      Ensures password has at least one uppercase, one lowercase, and one digit
                      """
                      return False if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password) else True

                      if __name__ == '__main__':
                      password = input("Enter password: ")
                      print("Strong password") if check(password) else print("Weak Password")






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 6 at 7:49









                      LinnyLinny

                      1,0871 gold badge9 silver badges27 bronze badges




                      1,0871 gold badge9 silver badges27 bronze badges







                      • 6




                        $begingroup$
                        return False if not isn't the best way to go about this. Instead, cast to bool.
                        $endgroup$
                        – Reinderien
                        Jul 6 at 13:51






                      • 2




                        $begingroup$
                        You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is return has_digits and has_upper and has_lower.
                        $endgroup$
                        – Roland Illig
                        Jul 6 at 15:02










                      • $begingroup$
                        Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an any call.
                        $endgroup$
                        – jpmc26
                        Jul 7 at 2:59













                      • 6




                        $begingroup$
                        return False if not isn't the best way to go about this. Instead, cast to bool.
                        $endgroup$
                        – Reinderien
                        Jul 6 at 13:51






                      • 2




                        $begingroup$
                        You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is return has_digits and has_upper and has_lower.
                        $endgroup$
                        – Roland Illig
                        Jul 6 at 15:02










                      • $begingroup$
                        Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an any call.
                        $endgroup$
                        – jpmc26
                        Jul 7 at 2:59








                      6




                      6




                      $begingroup$
                      return False if not isn't the best way to go about this. Instead, cast to bool.
                      $endgroup$
                      – Reinderien
                      Jul 6 at 13:51




                      $begingroup$
                      return False if not isn't the best way to go about this. Instead, cast to bool.
                      $endgroup$
                      – Reinderien
                      Jul 6 at 13:51




                      2




                      2




                      $begingroup$
                      You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is return has_digits and has_upper and has_lower.
                      $endgroup$
                      – Roland Illig
                      Jul 6 at 15:02




                      $begingroup$
                      You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is return has_digits and has_upper and has_lower.
                      $endgroup$
                      – Roland Illig
                      Jul 6 at 15:02












                      $begingroup$
                      Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an any call.
                      $endgroup$
                      – jpmc26
                      Jul 7 at 2:59





                      $begingroup$
                      Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an any call.
                      $endgroup$
                      – jpmc26
                      Jul 7 at 2:59


















                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Code Review Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223600%2fstrong-password-detection-in-python%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form