用if语句和b终止While循环

2024-10-01 00:16:39 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我现在在我创建的加密中添加了一些复杂的东西。 我正在实现While循环,从我创建的字典中生成大量字符。然后在将字符添加到变量时进行检查,然后在达到所需字符数后终止while循环。由于某些原因,while循环从不终止,即使我使用return0或break等。你知道吗

Alphabet = ["a", "b", "c", "d", "e", "f" "g", "h", "i", "j", "k", "l",      "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", '/', '.', ',', '\'', ';', '\\', ']', '[', '{', '}', '|', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '-', '0', '0', '2', '3', '4', '5', '6', '7', '8', '9']

while True:
    generaterandom = random.SystemRandom.choice() 
    calc0 = len(generaterandom)
    print(generaterandom)
    calc02 = 10
    if generaterandom == "10":
        break

Tags: truelen字典原因random字符breakchoice
2条回答

试着像这样重构While循环:

Alphabet = ["a", "b", "c", "d", "e", "f" "g", "h", "i", "j", "k", "l",      "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", '/', '.', ',', '\'', ';', '\\', ']', '[', '{', '}', '|', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '-', '0', '0', '2', '3', '4', '5', '6', '7', '8', '9']
bool = 1
while bool == 1:
    generaterandom = random.SystemRandom.choice() 
    calc0 = len(generaterandom)
    print(generaterandom)
    calc02 = 10
    if len(generaterandom) == "10":
        bool = 0
if generaterandom == "10":

这是您的问题,您正在检查generaterandom是否是一个值为10的字符串。您要做的是让它在到达10个字符时结束,因此您需要将if语句更改为:

if len(generaterandom) == 10:
    break

这将更改它以检查变量generaterandom中的字符数是否等于10,当它等于10时,循环将中断。你知道吗

如果不起作用,请重新构造循环,使其对变量起作用,例如:

loop = True
while loop:

开始和结束:

if len(generaterandom) == 10:
    loop = False

相关问题 更多 >