[英]My ussername checker keeps saying all names are available, despite if/else test
I'm attempting to make a simple, small, practice program for checking usernames using if-elif-else statements.我正在尝试制作一个简单、小巧的练习程序,用于使用 if-elif-else 语句检查用户名。
current_users = ['Enrique', 'Jose', 'Pablo', 'John', 'Jake']
new_users = ['Mike', 'Tom', 'Bowser', 'John', 'Howard', 'Ben']
'''for user in current_users:
user = user.lower()
print(user)
for user in new_users:
user = user.lower()
print(user)
'''
for user in new_users:
if user.lower() == current_users:
print(f"{user}: That username is taken.")
else:
print(f"{user}: That username is available.")
I expect for it to print the message "That username is taken" for a username that's on both the new_user list and the current_user list, but instead, they all evaluate the True when I run them in the Sublime text editor.我希望它为 new_user 列表和 current_user 列表中的用户名打印消息“该用户名已被占用”,但是相反,当我在 Sublime 文本编辑器中运行它们时,它们都评估为 True。
I know it's a logic error because no actual error message is given, but I can't quite see it yet.我知道这是一个逻辑错误,因为没有给出实际的错误消息,但我还不太清楚。
I've tried inverting the loop by starting with checking if a username from the new_users list is NOT from the current_users list.我尝试通过检查 new_users 列表中的用户名是否不是 current_users 列表开始来反转循环。
As you can see, I've tried changing all of the usernames to lowercase to see if it would help, but it doesn't.如您所见,我已尝试将所有用户名更改为小写,以查看是否有帮助,但没有帮助。
When you look for values in a list use "in" operator.当您在列表中查找值时,请使用“in”运算符。
current_users = ['Enrique', 'Jose', 'Pablo', 'John', 'Jake']
new_users = ['Mike', 'Tom', 'Bowser', 'John', 'Howard', 'Ben']
for user in new_users:
if user in current_users:
print(f"{user}: That username is taken.")
else:
print(f"{user}: That username is available.")
The problem is you were comparing a string to a list of strings user.lower() = current_user
.问题是您将字符串与字符串列表
user.lower() = current_user
。
Moreover, you are comparing user.lower()
to user
.此外,您正在将
user.lower()
与user
进行比较。
example means "Jhon".lower() == "Jhon"
will give you False
示例意味着
"Jhon".lower() == "Jhon"
会给你False
TRY THIS:尝试这个:
create a temporary list of current_user
with all the name in lower case then check if it already has taken or available.创建一个
current_user
的临时列表,所有名称都为小写,然后检查它是否已经被占用或可用。
current_users = ['Enrique', 'Jose', 'Pablo', 'John', 'Jake']
new_users = ['Mike', 'Tom', 'Bowser', 'John', 'Howard', 'Ben']
t_current_user = [x.lower() for x in current_users]
for user in new_users:
if user.lower() in t_current_user:
print(f"{user}: That username is taken.")
else:
print(f"{user}: That username is available.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.