【发布时间】: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 的长度。
标签: python python-3.x loops if-statement brute-force