例题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.')
结果:
发现的问题:
- 有时候避免错误,elif比else更好。
- 5-10是否有更好的方法?
- if 列表名可以判断列表是否为空。