我的Python代码没有输出任何东西?

2024-04-26 19:13:00 发布

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

我目前正试图通过Eric Matthes的Python速成班自学Python,我似乎在练习5-9时遇到了一些困难,比如使用if测试来测试空列表。你知道吗

问题是:

第5-9页。无用户:向hello添加if测试_管理员.py以确保用户列表不为空。你知道吗

•如果列表为空,请打印我们需要查找某些用户的消息!你知道吗

•从列表中删除所有用户名,并确保打印的消息正确无误。你知道吗

这是我的代码_管理员.py:

usernames = ['admin', 'user_1', 'user_2', 'user_3', 'user_4']

for username in usernames:

    if username is 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + username + ", thank you for logging in again.")

下面是我的5-9代码,它没有输出任何内容:

usernames = []

for username in usernames:

    if username is 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + username + ", thank you for logging in again.")
    if usernames:
        print("Hello " + username + ", thank you for logging in again.")
    else:
        print("We need to find some users!")

有没有人对我的代码为什么不输出有任何反馈:“我们需要找到一些用户!”谢谢你抽出时间。:)


Tags: to代码用户inyouhello列表for
2条回答

第一个if-else应该进入for循环。第二个if-else街区应该在外面。你知道吗

usernames = []

for username in usernames:

    if username is 'admin':
        print("Hey admin")
    else:
        print("Hello " + username + ", thanks!")

if usernames:
    print("Hello " + username + ", thanks again.")
else:
    print("Find some users!")

它没有输出任何东西,因为你的ifelse块在for循环中,循环在usernames上。因为usernames是一个空列表,它不会迭代任何内容,因此不会到达任何条件块。你知道吗

您可能希望改为:

usernames = []
for username in usernames:
    if username is 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + username + ", thank you for logging in again.")

if usernames:
    print("Hello " + username + ", thank you for logging in again.")
else:
    print("We need to find some users!")

不过,这将打印usernames列表中的最后一个用户名两次。你知道吗

相关问题 更多 >