2016-08-30 49 views
1

我目前正试图教自己的Python与Python速成班书由埃里克马特斯和我似乎有练习5-9有关使用如果测试来测试空列表的困难。我的Python代码不输出任何东西?

这里有一个问题:

5-9。无用户:将一个if测试添加到hello_admin.py以确保用户列表不为空。

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

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

下面是从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!") 

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

+1

欢迎来到StackOverflow。将来,您可以通过缩进四个空格来格式化您的代码。请参阅[格式化帮助主题](http://stackoverflow.com/help/formatting)。否则,在第一个问题上做得很好。 –

+0

@FrankTan,在这里格式化代码时,我经常发现手动为每一行添加缩进的麻烦。有没有简单的方法来快速添加四个空格而无需复制并粘贴四个空格? –

+0

除非你的代码在这里粘贴之前还没有缩进,当你将代码置于大括号之间时,是不是会根据你的代码风格自动缩进呢? – DeA

回答

2

它不输出任何东西,因为您的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列表中的最后两次名,虽然。

0

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

谢谢大家的回复,事实证明,我的第二个if-else语句在我的for循环中是问题,我现在正在显示此练习的输出。 :) – PhantomDiclonius