繁体   English   中英

我的Python代码未输出任何内容?

[英]My Python code is not outputting anything?

我目前正在尝试使用Eric Matthes撰写的《 Python崩溃教程 》( Python Crash Course)一书来教自己使用Python,关于使用if测试测试空列表,我似乎在练习 5-9时遇到困难。

这是问题:

5-9。 No Users:向hello_admin.py添加if测试,以确保用户列表不为空。

•如果列表为空,则打印消息我们需要找到一些用户!

•从列表中删除所有用户名,并确保打印正确的消息。

这是来自hello_admin.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!")

是否有人对我的代码未输出的原因有任何反馈:“我们需要找到一些用户!” 感谢您的时间。 :)

它不输出任何内容,因为您的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列表中的最后一个用户usernames

第一个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!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM