python第四次練習

例題5-6 人生的不同階段

  描述:設置變量age 的值,再編寫一個if-elif-else 結構,
             根據age 的值判斷處於人生的哪個階段。
  代碼:

age = 19
if age < 2:
    print('He is a baby.')
elif age < 4:
    print('He is learning to walk.')
elif age < 13:
    print('He is a child.')
elif age < 20:
    print('He is a teenager.')
elif age < 65:
    print('He is an adult.')
else:
    print('He is a senior citizen.')

  結果:
這裏寫圖片描述

例題5-8+5-9 用戶

  描述:列表爲非空,對用戶名爲admin的區別打招呼。另列表爲空並檢查。
  代碼:

users = ['Eric', 'Ponyo', 'Reading', 'Mary', 'admin']
for user in users:
    if user == 'admin':
        print('Hello admin, would you like to see a status report?')
    else:
        print('Hello ' + user + ', thank you for logging in again.' )

  結果:
這裏寫圖片描述

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

  結果:
這裏寫圖片描述

例題5-10 檢查用戶名

  描述:創建兩個用戶名列表若,
             第二個中的某個在第一個存在(不區分大小寫),
             則打印消息不能使用。
  代碼:

current_users = ['eric', 'ponyo', 'reading', 'mary', 'elsa']
new_users = ['ERIC', 'PONYo', 'Alice', 'Ben', 'Piano']
for new_user in new_users:
    if new_user.lower() in current_users:
        print('A new user name is needed.')
    else:
        print('The user name is available.')

  結果:
這裏寫圖片描述

發現的問題:

  1. 有時候避免錯誤,elif比else更好。
  2. 5-10是否有更好的方法?
  3. if 列表名可以判斷列表是否爲空。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章