[英]Random Password Generator using Python
我正在创建一个随机密码生成器。 第一个我必须向用户询问密码的长度,它必须至少有 8 位到最多 16 位。 我创建的一个是要求用户输入密码本身,然后从那里检查长度。 首先,我希望用户输入密码的长度,例如:7 或 9 等。 如果用户键入小于 8 且大于 16 的数字,则必须显示“必须至少有 8 位到最多 16 位”。 请参考下面的代码,如果不清楚,请参考这两个图像。 谢谢你。
输入
import random
import string
print('hello, Welcome to Password generator!')
l = False
while not l:
length = input('\nEnter the length of password: ')
if len(length) < 8 :
print('You password length is too short(must be more than 8 character)')
print(len(length), "is the length of your password")
elif len(length) > 16:
print('You password length is too long(must be less than 17 character)')
print(len(length), "is the length of your password")
else:
print('You password length looks good')
break
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
all = lower + upper + num + symbols
temp = random.sample(all,length)
password = "".join(temp)
print(password)
OUTPUT
hello, Welcome to Password generator!
Enter the length of password: 9
You password length is too short(must be more than 8 character)
1 is the length of your password
Enter the length of password: 9
You password length is too short(must be more than 8 character)
1 is the length of your password
input()
的返回类型是str
或 string。 当您检查分配给length
的返回值的长度时,它会计算字符串中的字符数,而不是检查给定数字是大于还是小于另一个。 要解决此问题,请在length
上调用 integer 构造函数int()
或将其放在对input
的调用周围,以便在检查之前将字符串转换为数字类型。
length = int(input('\nEnter the length of password: '))
此外,由于length
现在是 integer,因此您无需调用len
即可直接执行检查。 例如
if length < 8:
...
你应该这样写:
lenght = int(input('insert lenght: '))
在 Python 中, int
内置 function (也)用于将str
转换为 integer ( int
) 变量。
然后你必须这样改变你的代码:
print(lenght, "is the length of your password")
我会建议一些其他的改进。
all = lower + upper + num + symbols #Here you are overwriting the all built-in function
...或者...
while True: #Instead of "while not l"
if (condition_that_will_end_the_loop):
break
内置len
function 返回一个int
,并以这种方式使用:
>>> len([1, 2, 3, 'hey'])
4
>>> len('string')
6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.