2016-08-30 68 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