为什么字符串“andy”没有打印请输入新用户名?

2024-05-20 10:45:45 发布

您现在位置:Python中文网/ 问答频道 /正文

current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user = current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

Andy正在打印,因为用户名可用。 另外,请帮助我简化,因为我正在学习python


Tags: innewforderekcurrentusersprintandy
3条回答

您应该尝试在列表中使用in

current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [i.lower() for i in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

单个等号用于为变量赋值,而两个连续的等号用于检查两个表达式是否给出相同的值

=是赋值运算符

==是一个相等运算符

current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user == current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

您可以使用列表理解current_users中的用户名转换为lowercase。其次,您必须检查new_user是否已经存在于current_users中。要做到这一点,您必须使用in关键字

in关键字

tests whether or not a sequence contains a certain value.

这是代码

current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [user.lower() for user in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

希望有帮助

相关问题 更多 >