【发布时间】: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')