Python调用函数后判断返回值为True展示列表问题排查
问题排查:菜单3登录成功后不展示员工薪资列表
核心是代码存在3处明确错误,直接导致预期逻辑不生效:
- (直接引发列表不展示的核心错误)
login()函数未返回验证结果。当前代码调用authentication()拿到验证状态后,没有通过return把结果传出,Python中未显式写return语句的函数默认返回None,外层if login():的判断永远不成立,后续遍历打印员工、薪资列表的代码完全不会执行。 - 注册逻辑存在拼写错误:
new_login()函数判断输入姓名是否在员工列表时,误把列表名list_employees写为list_employee(少了末尾的s),运行时会直接触发NameError;且原逻辑下如果输入姓名不在员工列表,打印提示后不会中断流程,仍会继续执行后续注册步骤。 - 新增员工逻辑存在语法错误:
create_employee()中输入薪资的代码input('Type the employee's salary: ')外层用单引号包裹字符串,字符串内部employee's的单引号会提前截断字符串,运行时直接报语法错误。
修正后可正常运行的代码
list_login = [] list_password = [] list_employees = ['Pedro' , 'Ana', 'Carlos', 'Maria Clara', 'João Antônio'] list_salaries = [3470.00, 2200.00, 3970.34, 7450.23, 5677.33] def check(login_user): return login_user in list_login def authentication(index,user_password): if list_password[index] == user_password: print('User authenticated!') return True else: print('Incorrect Password!') return False def login(): login_user = input('Type your login: ') user_password = input('Type your password: ') if check(login_user): index = list_login.index(login_user) # 修复:返回认证结果给外层判断 return authentication(index,user_password) else: print("Login information is incorrect or does not exist.") # 修复:登录失败明确返回False return False def new_login(): name = input('Type your name: ') # 修复:修正列表名拼写,输入不合法时直接中断流程 if name not in list_employees: print('Name is not in the emplyee list, type again!') return login_user = input('Type the login you wish to register: ') if login_user in list_login: print('There is already a user registered with this login') return print('Login is available!') password_user = input('Type the password that will be registered: ') list_login.append(login_user) list_password.append(password_user) print('User registered!') print('Employee name: ', name) print('Login saved: ', login_user) print('Password saved: ', password_user) def create_employee(): name = input('Type the name of the new employee: ') # 修复:单引号冲突,改用双引号包裹外层字符串 salary = float(input("Type the employee's salary: ")) list_employees.append(name) list_salaries.append(salary) print('Employee ',name,' registered with the current salary of: ',salary) while True: choice = input( ''' MENU 1- Create Login and Password 2- Increase salary 10% 3- Report 4- Create New Employee Choose a option: ''' ) if choice == '1': new_login() if choice == '2': login() if choice == '3': if login(): for i in range(len(list_employees)): print(list_employees[i],' - ',list_salaries[i]) if choice == '4': create_employee()
内容的提问来源于stack exchange,提问作者Deivid Kutter
相关产品推荐
相关产品推荐

