当我试图在列表中搜索时,我得到了TypeError: cannot unpack non-iterable bool object
。当我返回布尔值和我正在搜索的项目的索引值时。
def name_ser(name):
found = False
for i in range(len(names)):
if names[i] == name:
found = True
return found, names.index(name)
else:
found = False
return found,None
def main_menu():
print('Welcome!nPlease Choose from the following options...')
print('1: Create an accountn2: Login ')
opt = int(input('Enter Your Choice: '))
if opt == 1:
name_search = input('Enter Name... ')
found, _ = name_ser(name_search)
if found == True:
print("Account Already excites!")
elif found == False & len(names) == 0:
acc_creation(name_search)
print('Account created!')
错误:
Traceback (most recent call last):
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 100, in <module>
main_menu()
File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 77, in main_menu
found, _ = name_ser(name_search)
TypeError: cannot unpack non-iterable NoneType object
name_ser
可以返回3个不同的对象。
def name_ser(name):
found = False
for i in range(len(names)):
if names[i] == name:
found = True
return found, names.index(name) <== returns 2-tuple
else: <== if name[0] doesn't match,
found = False executes immediately
return found <== returns boolean
<== if names is empty, returns None
您需要一个一致的返回类型。但实际上,这个函数根本不应该存在。它试图在names
或False
中返回name
的索引。str.find
几乎就是这样。
def main_menu():
print('Welcome!nPlease Choose from the following options...')
print('1: Create an accountn2: Login ')
opt = int(input('Enter Your Choice: '))
if opt == 1:
name_search = input('Enter Name... ')
if name_search in names:
print("Account Already exists!")
else:
acc_creation(name_search)
print('Account created!')
在添加帐户之前,我还删除了name_ser
为空的复选框。如果只有一个人可以创建一个帐户,我觉得这会很奇怪。
正如前面的一些注释中所提到的,不能同时返回一个或两个值。我的建议是返回该名称的索引。或者,如果未找到,则返回值-1
。
def name_ser(name):
# Check if element is in list
if name in names:
# Return index of element
return names.index(name)
else:
# Name was not found in the list
return -1
def main_menu():
print('Welcome!nPlease Choose from the following options...')
print('1: Create an accountn2: Login ')
opt = int(input('Enter Your Choice: '))
# Create account
if opt == 1:
name_search = input('Enter Name... ')
found = name_ser(name_search)
if found >= 0:
print("Account Already exists!")
elif found == -1 & len(names) == 0:
acc_creation(name_search)
print('Account created!')
# Login to Account
if opt == 2:
# Update to use index instead of boolean