Python编程:从入门到实践 第 5 章 if语句 课后练习 5-8~5-11

5-8 以特殊方式跟管理员打招呼 :创建一个至少包含 5 个用户名的列表,且其中一个用户名为 'admin' 。想象你要编写代码,在每位用户登录网站后都打印一条问
候消息。遍历用户名列表,并向每位用户打印一条问候消息。
如果用户名为 'admin' ,就打印一条特殊的问候消息,如 “Hello admin, would you like to see a status report?” 。
否则,打印一条普通的问候消息,如 “Hello Eric, thank you for logging in again” 。

users = ['Henry', 'lisa', 'tim','admin','jolie']
for user in users:
    if user == 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + user.title() + ", thank you for logging in again.")

结果:

Hello Henry, thank you for logging in again.
Hello Lisa, thank you for logging in again.
Hello Tim, thank you for logging in again.
Hello admin, would you like to see a status report?
Hello Jolie, thank you for logging in again.

5-9 处理没有用户的情形 :在为完成练习 5-8 编写的程序中,添加一条 if 语句,检查用户名列表是否为空。
如果为空,就打印消息 “We need to find some users!” 。
删除列表中的所有用户名,确定将打印正确的消息。

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

结果:

Hello Henry, thank you for logging in again.
Hello Lisa, thank you for logging in again.
Hello Tim, thank you for logging in again.
Hello admin, would you like to see a status report?
Hello Jolie, thank you for logging in again.
We need to find some users!

5-10 检查用户名 :按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
创建一个至少包含 5 个用户名的列表,并将其命名为 current_users 。
再创建一个包含 5 个用户名的列表,将其命名为 new_users ,并确保其中有一两个用户名也包含在列表 current_users 中。
遍历列表 new_users ,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。确保比较时不区分大消息;换句话说,如果用户名 'John' 已被使用,应拒绝用户名 'JOHN' 。

current_users = ['henry', 'alice', 'allen', 'jolie', 'tim']
new_users = ['jolie', "Charlie", "harry", 'Henry', 'lisa']
lower_current_users = []
for current_user in current_users:
    lower_current_users.append(current_user.lower())
for new_user in new_users:
    if new_user.lower() in lower_current_users:
        print(str(new_user) + " have been used, please use another name.")
    else:
        print("You can use the name.")

结果:

jolie have been used, please use another name.
You can use the name.
You can use the name.
Henry have been used, please use another name.
You can use the name.

5-11 序数 :序数表示位置,如 1st 和 2nd 。大多数序数都以 th 结尾,只有 1 、 2 和 3 例外。
在一个列表中存储数字 1~9 。
遍历这个列表。
在循环中使用一个 if-elif-else 结构,以打印每个数字对应的序数。输出内容应为 1st 、 2nd 、 3rd 、 4th 、 5th 、 6th 、 7th 、 8th 和 9th ,但每个序
数都独占一行。

numbers = list(range(1, 10))
for number in numbers:
    if number == 1:
        print("1st")
    elif number == 2:
        print("2nd")
    else:
        print(str(number) + 'th')

结果:

1st
2nd
3th
4th
5th
6th
7th
8th
9th

猜你喜欢

转载自blog.csdn.net/hjk120key3/article/details/82253082
今日推荐