attemptsRemaining = 5
if attemptsRemaining == 0:
print("Entry failed. Locking program.")
exit()
while attemptsRemaining > 0:
passwordEntry = input("Enter the password to access the data: ")
if passwordEntry == 1234:
print("test")
else:
attemptsRemaining -1
因此,我使用Python编写了一个简单的密码脚本,但是即使我输入正确,该程序也不会停止循环“输入密码”输入;当我输入错误五次时,它仍会循环。有人知道我该如何解决此问题?
谢谢。
答案 0 :(得分:3)
您的代码有3处错误。
首先,您要在输入正确的密码后中断while循环。
第二,您的else子句中有一个错字:
应该是-= 1
attemptsRemaining - 1
计算出正确的值,但没有将其分配回变量。
以下代码应为您工作
attemptsRemaining = 5
if attemptsRemaining == 0:
print("Entry failed. Locking program.")
exit()
while attemptsRemaining > 0:
passwordEntry = input("Enter the password to access the data: ")
if passwordEntry == 1234: # if you get the password correct
print("test") # print test
break # and come out of the loop
else:
attemptsRemaining -=1
第三,将用户输入的值与整数进行比较。 input()
值将被存储为字符串,因此您正在比较将始终返回False
的不同类型。您需要将passwordEntry
转换为int
,或与'1234'
字符串进行比较。
答案 1 :(得分:0)
attemptsRemaining = 5
while attemptsRemaining > 0:
passwordEntry = input("Enter the password to access the data: ")
if passwordEntry == 1234:
print("test")
break # exit loop
else:
attemptsRemaining -=1
if attemptsRemaining == 0:
print("Entry failed. Locking program.")
exit()
答案 2 :(得分:0)
问题在于您实际上并没有递减false
。
您需要执行attemptsRemaining
的等效操作。
更常见和更简洁地讲,您可以执行attemptsRemaining = attemptsRemaining - 1
。
您会发现(并且不太明显)的另一个问题是,当您调用attemptsRemaining -= 1
时,该值将被存储为String。您正在与input
进行比较,因此即使它为1234
,它也总是返回False
,并且永远不会认为您的密码正确。
最后,当密码正确时,您需要确保1234
退出break
循环。否则,您将陷入循环!
答案 3 :(得分:0)
执行if语句的正确方法。 5次错误尝试后退出
FileNotFoundError Traceback (most recent call last)
<ipython-input-111-7bf001c77c72> in <module>()
5 max_evals=30,
6 trials=Trials(),
----> 7 notebook_name= 'MNISTFashion')
2 frames
/usr/local/lib/python3.6/dist-packages/hyperas/optim.py in minimize(model, data, algo, max_evals, trials, functions, rseed, notebook_name, verbose, eval_space, return_space, keep_temp)
67 notebook_name=notebook_name,
68 verbose=verbose,
---> 69 keep_temp=keep_temp)
70
71 best_model = None
/usr/local/lib/python3.6/dist-packages/hyperas/optim.py in base_minimizer(model, data, functions, algo, max_evals, trials, rseed, full_model_string, notebook_name, verbose, stack, keep_temp)
96 model_str = full_model_string
97 else:
---> 98 model_str = get_hyperopt_model_string(model, data, functions, notebook_name, verbose, stack)
99 temp_file = './temp_model.py'
100 write_temp_files(model_str, temp_file)
/usr/local/lib/python3.6/dist-packages/hyperas/optim.py in get_hyperopt_model_string(model, data, functions, notebook_name, verbose, stack)
177 if notebook_name:
178 notebook_path = os.getcwd() + "/{}.ipynb".format(notebook_name)
--> 179 with open(notebook_path, 'r') as f:
180 notebook = nbformat.reads(f.read(), nbformat.NO_CONVERT)
181 exporter = PythonExporter()
FileNotFoundError: [Errno 2] No such file or directory: '/content/MNISTFashion.ipynb'