0
a broken password generator
Hi everybody, pls help me optimize this code : def password (): downletters = "abcdefghijklmnopqrstuvwxyz" upleeters="ABCDEFGHIJKLMNOPQRSTUVWXYZ" symbols = "~!:;,$*^)=+#°£$ç_\&(-\_?./§µ%¨" digits = "0123456789" str="" for x in range (3): x1=choice(downletters) str=str + x1 if len(str)>9: break x2 = choice (upleeters) str=str + x2 if len(str)>9: break x3 = choice (symbols) str=str + x3 if len(str)>9: break x4 = choice ( digits ) str=str + x4 if len(str)>9: break print ("the random password is : ",str)
3 Respostas
+ 2
Here is a suggestion:
------------------------------------------------------------------------------------
from random import choice
import string
def password (numOfDigits):
xs = (
string.ascii_letters,
string.punctuation,
string.digits
)
_str = ""
for _ in range (numOfDigits):
x = choice(choice(xs))
_str += x
return _str
print ("the random password is : ", password(10))
------------------------------------------------------------------------------------
What I have done:
- used letters, digits and symbols from string lib
- added parameter for pw length (numOfDigits)
- choose the category of x randomly
- made for loop of range 0 ... numOfDigits
- therefore <<if len(str)>> is no longer necessary
- changed name str to _str (no redefinition of class str)
- changed x in for loop to _ (as it is not used)
- made the function return the pw, rather than printing it
- _str += x instead of _str = _str +x
https://code.sololearn.com/cDvS16z3aOdU/?ref=app
0
Thanks for all your answers
0
:)