Skip to main content
 首页 » 编程设计

python之for循环中嵌套if语句中的特定缩进错误

2025年05月04日16shangdawei

我有以下代码,在登录功能中,输出是错误的(逻辑错误)。它基本上打印“无效的用户名和密码”,直到找到正确的用户名和密码,然后打印“正确的登录”。

错误输出:

例如,测试数据:user3和pass3,输出为:

*****LOGIN SCREEN****** 
Username: user3 
Password: pass3 
invalid username or password 
invalid username or password 
correct login 
>>>  

这是有问题的代码,引用了 LOGIN 函数:

usernames=["user1","user2","user3"] 
passwords=["pass1","pass2","pass3"] 
 
def main(): 
   mainmenu() 
 
 
def mainmenu(): 
   print("****MAIN MENU****") 
   print("=======Press L to login :") 
   print("=======Press R to register :") 
   choice1=input() 
   if choice1=="L" or choice1=="l": 
      login() 
   elif choice1=="R" or choice1=="r": 
      register() 
   else: 
      print("please make a valid selection") 
 
usernames=["user1","user2","user3"] 
passwords=["pass1","pass2","pass3"] 
 
def login(): 
  print("*****LOGIN SCREEN******") 
  username=input("Username: ") 
  password=input("Password: ") 
  for index_of_current_user, current_user in enumerate(usernames): #enumerate allows to you to go throw the list and gives to you the current element, and the index of the current element 
    if username == current_user and passwords[index_of_current_user] == password: #since the two list are linked, you can use the index of the user to get the password in the passwords list 
      print("correct login") 
    else: 
      print("invalid username or password") 
 
def register(): 
  print("*****REGISTRATION****") 
  username=input("Enter a username:") 
  password=input("Enter a password:") 
  users_pass[username] = password 
  answer=input("Do you want to make another registration?") 
  if answer=="y": 
    register() 
  else: 
    registration_details() 
 
def registration_details(): 
   print(usernames) 
   print(passwords) 
 
main() 

我在找 a) 问题的解决方案和修复,以便它只在找到正确的用户名和密码对时打印一次“正确登录”,而不是循环打印每个用户名和密码

b) 解释为什么这里的缩进或任何错误在这里不起作用 - 因为逻辑(在像 VB.Net 这样的语言中)是合理的。

如果问题可以在没有额外代码的情况下解决(并且非常简单的修复),我会更喜欢它,但也许最优雅的解决方案是一个标志。也就是说,如果问题不仅仅是缩进或我错过的类似问题。

请您参考如下方法:

您可以利用异常以这种方式编写登录。

def login(): 
  print("*****LOGIN SCREEN******") 
  username=input("Username: ") 
  password=input("Password: ") 
  try: 
    index = usernames.index(username) 
    if password == passwords[index]: 
      print("correct login") 
    else: 
      print("invalid username or password") 
  except: 
    print("invalid username or password")