【问题标题】:Python four-digit password finderPython 四位密码查找器
【发布时间】:2021-07-13 22:23:56
【问题描述】:

我正在尝试创建一个程序,您可以在其中输入 4 位或 3 位数字密码,并且 for 循环总是将“i”增加一到密码的数量,这一切都有效,但如果我写例如 0001 for 循环进入无穷大,因为它从 0 而不是从 0000 开始,而如果我写 1234 密码是 1234 我该怎么做才能确保:0000、0001、0011、0111 不进行 for 循环去无穷大,但是是 0000 或 0001 等等

# import only system from os
from os import system, name
  
# define our clear function
def clear():
  
    # for windows
    if name == 'nt':
        _ = system('cls')
  
    # for mac and linux(here, os.name is 'posix')
    else:
        _ = system('clear')

strpw = input()

#check if the number is 4-digit or 3-digit
if len(strpw) <= 4 and len(strpw) >= 3:
    i = 0
    #add 1 to i until i equals strpw
    while i != strpw:
        print(i)
        clear()
        i = i + 1
        if str(i) == strpw:
            print("the password is: " + str(i))
            break
else:
    print("the password is too short or too long")

【问题讨论】:

  • 你为什么会有这个:_ = system('cls')你可以很容易地离开这个:system('cls')
  • @Matiiss 我不知道它在教程中说要这样做(我今天是新手,是我使用 python 的第一天)
  • 有趣,无论如何这毫无意义,因为system() 返回None 所以该变量无论如何都没有任何用处,但是这是一个“一次性变量”,意味着它不可访问 -它被删除了 - 所以双重没有用,以这种方式使用这种方式毫无意义,所以还不如只使用system('cls')

标签: python for-loop passwords


【解决方案1】:

您可以将密码保存为整数。当您需要显示它时,才将其转换为所需的字符串格式。这将简化一切。一个最小的例子:

strpw = "0003"

pass_length = len(strpw)
pw = int(strpw)

i = 0

while i != pw: # keep as int for comparint and incrementing
    # convert to string for printing
    print(str(i).zfill(pass_length))
    i += 1

打印:

0000
0001
0002

【讨论】:

    【解决方案2】:

    从代码strpw = int(input()) 的这一行开始,您将输入string 并将其转换为int。这导致了问题。 例如

    如果我们将输入0111 转换为int,它将变为111。而如果我们将其保留为string,它仍然是0111

    因此您只需将密码保存为字符串格式。

    【讨论】:

    • 我去掉了password变量,通过去掉int()直接把strpw转成字符串,但是问题依旧。我在问题中写了脚本,修改了问题
    • 所以你基本上什么都没解决?是这样吗,就像你想象的如何增加字符串?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多