【问题标题】:Breaking out of an inner loop Python打破内部循环Python
【发布时间】:2021-03-02 16:07:14
【问题描述】:

我正在为计算机安全课程编写的一段代码苦苦挣扎。

我正在尝试编写一段测试代码,根据解决时间来测试 4 位密码。

我想从 4 个全 0 的数字开始。对于每个数字,测试从 0 到 9 的数字。

如果我从大于 0.2 秒的函数中得到响应,则使用该数字更改 pw 列表,然后移至下一个。

但是我的代码没有在列表中递增。 我尝试在 if 语句之后简单地插入一个 break,但意识到我还必须打破我们的外部“for 循环”,我尝试在这里插入一个 break,但仍然无法让我的代码工作。

我错过了什么?

import time
import sys # ignore

sys.path.insert(0,'.') # ignore
real_password = '2234'

#This function cannot be changed
def check_password(password): # Don't change it
    if len(password) != len(real_password):
        return False
    for x, y in zip(password, real_password):
        time.sleep(0.1) # Simulates the wait time of the safe's mechanism
        if int(x) != int(y):
            return False
    return True



def crack_password():
    pw = [0,0,0,0]
    cnt = 0
    if cnt < 3:
        for i in range (0,9):
            pw[cnt] = i
            start = time.time()
            check_password(create_string(pw))
            stop = time.time()
            t_time = stop - start
            print(pw[cnt], t_time)
            #Struggling with my code here!


#Creates a string from the list
def create_string(pw_list):
    string = ''
    for char in pw_list:
        string += str(char)
    return string

我在crack_password函数中的打印语句提供:

0 0.10016393661499023
1 0.10017132759094238
2 0.1006174087524414
3 0.10022568702697754
4 0.1002652645111084
5 0.20053935050964355
6 0.10025167465209961
7 0.10107183456420898
8 0.10021018981933594

因此我知道密码的第一个数字是 5,因为它大于 0.2。然后我怎样才能打破这个循环并移动到 pw 整数的下一次迭代?

【问题讨论】:

  • 这能回答你的问题吗? How to break out of multiple loops?
  • 我之前读过这篇文章,但它并没有真正帮助我,我认为我正在为我的实施而苦苦挣扎。
  • 所以我意识到不是循环破坏了我的代码,而是我的 if 语句时机。所以跳出循环的链接是正确的。

标签: python loops security


【解决方案1】:
def test_pw():
    pw = [0,0,0,0]
    for i in range(4):
        for x in range(0,10):
            pw[i] = x
            pw_test = create_string(pw)
     start_t = time.time()
     check_password(pw_test)
     end_t = time.time()
     t_results = end_t - start_t
     if t_results > 0.2:

【讨论】:

  • 这行不通,因为我首先需要检查 x 的每次迭代,只有当 x 的迭代大于 0.2 时,我才需要移动到 pw 列表中的下一个整数。跨度>
猜你喜欢
  • 1970-01-01
  • 2012-12-07
  • 2021-01-19
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多