所以我有这个程序,我需要用户在python中为密钥选择长度,但我希望用户的选择仅限于所提供的长度,我不太知道如何做到这一点
available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
length = int(input("[+]:Select the length you want for your key: "))
我想这样做,如果用户输入一个在列表中不可用的长度;请选择一个有效的长度";并带他回去输入长度
我试过:
while True:
length = int(input("[+]:Select the length you want for your key: "))
if 5 <= length <= 21:
break
您无法控制用户输入的内容。您可以控制是否请求不同的输入。
用一个无限循环和一个显式的break
语句对此进行建模。
available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
while True:
length = int(input("[+]:Select the length you want for your key: "))
if length in availble_len:
break
虽然您可以使用赋值表达式来缩短它,但我发现这种方法更清晰。
available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
while (length := int(input("[+]:Select the length you want for your key: "))) not in available_len:
pass
您可以将pass
替换为print
语句,以解释上一个选择无效的原因。
尝试:
available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
length = -1
while length not in available_len:
length = int(input("[+]:Select the length you want for your key: "))
输出:
[+]:Select the length you want for your key: 7
[+]:Select the length you want for your key: 30
[+]:Select the length you want for your key: 14
只需循环,直到收到想要的答案:
available_len = [5 , 10 , 14 , 12 , 15, 16 , 18 , 20 , 21]
length = -1
while length not in available_len:
length = int(input("[+]:Select the length you want for your key: "))
if length not in available_len:
print("Length not accepted, try again")
print(length)