如何限制python中用户的选择?
How to restrict the choice of a user in python?
所以我有这个程序,我需要用户为 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
尝试:
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)
您无法控制用户输入的内容。您可以控制是否要求不同的输入。
使用无限循环和显式 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
您可以用 print
语句替换 pass
,解释为什么之前的选择无效。
所以我有这个程序,我需要用户为 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
尝试:
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)
您无法控制用户输入的内容。您可以控制是否要求不同的输入。
使用无限循环和显式 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
您可以用 print
语句替换 pass
,解释为什么之前的选择无效。