我的程序要求用户输入密码,如果用户输入了错误的密码,他会尝试五次,然后程序会告诉它结束



我得到的输出错误。即使用户重新输入了正确的密码,循环也不会中断。当用户输入正确的密码时,它不会显示登录成功。

count = 0
password = input('Enter password: ')
while password != 'abcdefghijkl' and count <= 5:
password_renter = input('Enter the password: ')
count = count + 1
if password_renter == 'abcdefghijkl' and password == 'abcdefghijkl':
print('login successful')
break
if password_renter != 'abcdefghijkl' and count > 5:
print('Chances over')

出于同一目的使用两个不同的变量是一种不好的行为,在这种情况下,我看到了password_enterpassword_renter。我只会重用其中之一,在某些时候它会打破循环。

attempts = 6
correct = "abcdefghijkl"
while (attempts > 0):
password = input("Enter Password: ")
if password == correct:
print("login successful.")
attempts = 0 
##function to execute when logged in
else:
attempts -= 1
print("Attempts left: " + str(attempts))

您在 while 循环中输入的只有密码不等于 'abcdefghijkl'。因此,当您要在while循环中检查它以查看password_renter和密码是否相等时,它总是为False,因为右侧为False。

我建议进行最小的更改。但是,我不确定这是否是您想要的。请在您最后测试它。

count = 0
password = input('Enter password: ')
while count <= 5:
password_renter = input('Enter the password: ')
count = count + 1
if password_renter == 'abcdefghijkl' and password == 'abcdefghijkl':
print('login successful')
break
if password_renter != 'abcdefghijkl' and count > 5:
print('Chances over')

最新更新