【问题标题】:Python3 For loop iterating through a list won't breakPython3 For循环遍历列表不会中断
【发布时间】:2020-05-31 22:09:45
【问题描述】:

跳出 for 循环

我的代码不会跳出循环:

(我截掉了一些用于化妆品的部分)

lchars = ['', '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', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '\\', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '[', ']', '{', '}', '|', ';', ':', "'", ',', '.', '/', '<', '>', '?', '`', '¡', '™', '£', '¢', '∞', '§', '¶', '•', 'ª', 'º', '–', '≠', 'œ', '∑','´', '®', '†', '¥', '¨', 'ˆ', 'ø', 'π', '“', '‘', '«', 'å', 'ß', '∆', '˚', '¬', '…', '˜', 'µ', '≤', '≥', '÷', 'æ', 'Ω', '≈', 'ç', '√', '"', ' ']


guessThisPass = str(input("Enter the password you want the python-based brute force hacker to guess (Character limit is 4): "))
if len(guessThisPass) > 4:
    print('I SAID CHARACTER LIMIT IS 4!! I AM TRUNCATING YOUR PASSWORD NOW! ????')
    guessThisPass[0:4]
    time.sleep(5)
print("Starting...")
time.sleep(2)
start = time.time()
for d in lchars:
    for c in lchars:
        for b in lchars:
            for a in lchars:
                tryPass = str(str(a) + str(b) + str(c) + str(d)). # I know the strs are probably unnessecary.
                print(tryPass). # Outputing the attempted password
                if tryPass == guessThisPass:
                    break # This never happens

print("Whoo!")
print("That took ", time.time()-start, "seconds.")

使用此代码,假设我的密码是“a”(哪个 IRL,它是不是)。那么,逻辑上,它应该几乎可以立即摆脱它,对吧?除了它没有;它只是继续运行,而不是中断,甚至达到组合 '^Bc' 或更高。为什么不破?我需要在每个循环中添加 if 语句吗?

测试代码

另外,这是我用来测试可能组合的代码:

(也截断多余的化妆品)

# All possible combinations
lchars = ['', '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', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '\\', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '[', ']', '{', '}', '|', ';', ':', "'", ',', '.', '/', '<', '>', '?', '`', '¡', '™', '£', '¢', '∞', '§', '¶', '•', 'ª', 'º', '–', '≠', 'œ', '∑','´', '®', '†', '¥', '¨', 'ˆ', 'ø', 'π', '“', '‘', '«', 'å', 'ß', '∆', '˚', '¬', '…', '˜', 'µ', '≤', '≥', '÷', 'æ', 'Ω', '≈', 'ç', '√', '"', ' ']
# print("Also, there are ", len(lchars), "characters in our character database\n\n")
from time import time
start = time()
for d in lchars:
    for c in lchars:
        for b in lchars:
            for a in lchars:
                print(a+b+c+d)
print("Whoo!")
print("That took ", time()-start, "seconds.")

我检查了上述代码的输出。字母“a”在输出中。它应该工作。为什么它不起作用?

【问题讨论】:

  • break 仅从最内层循环中断,在本例中为 for a in lchars:。您可能希望将所有循环放在函数内并使用return 而不是break
  • 查看 itertools.product() 而不是 4 级深度嵌套循环。作为一个额外的优势,您可以有一个break 可以工作的1 级深度嵌套循环。另一个优点是,它不会硬连线 4 的长度。
  • this post

标签: python python-3.x loops if-statement brute-force


【解决方案1】:

breaking。问题是,break 只从内部循环中断;不是每个包含它的循环。最里面的循环中断,然后围绕它的循环从它停止的地方开始。

在不过多更改代码的情况下,最简单的解决方案是将该代码包装在一个函数中并从中获得return

def try_all(lchars):
    for d in lchars:
        for c in lchars:
            for b in lchars:
                for a in lchars:
                    tryPass = a + b + c + d
                    print(tryPass)
                    if tryPass == guessThisPass:
                        return tryPass

cracked_password = try_all(lchars)

还有很多其他的改进需要提到,但这里不合适。一旦代码工作并完成,您可以将其发布到Code Review 以获得一般建议。

【讨论】:

  • 那么,return 会脱离整个函数,对吗?我明白了...谢谢!
  • 是的。 return 使你无条件退出函数;无论您嵌套在什么中。我在这里使用它来一次退出所有循环。使用您拥有的嵌套循环,这确实是唯一简单的选择。像 Asocia 提到的 itertool 函数将是更简洁的选择(因为那时你根本不会有嵌套循环),但需要重新配置你的代码。
【解决方案2】:

实际上它确实会中断,但由于您有 4 个嵌套循环,它只会中断最内层的循环。你可以做几件事来解决这个问题:

  • 创建一个标志并在继续之前检查它
  • 将代码移动到函数中,找到答案后返回
  • 使用itertools.product 创建您的试用字符串。这样一来,您将只需要一个循环,因此 break 会很简单。

【讨论】:

    【解决方案3】:

    是的,break 只会让你脱离最内层的循环!我会将该代码移动到一个函数中,它可以在找到正确的函数时return tryPass

    编码愉快!

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多