高级编程技术(Python)作业5

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

Solution:

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!")

Output:

We need to find some users!

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

Solution:

current_users = ["Bengi", "Ashero", "Tim", "Pat", "Faker"]
new_users = ["Bang", "Blank", "Wolf", "Pat", "faker"]
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("This name has been used." + 
              "You need to use another one.")
    else:
        print("This name hasn't been used yet.")

Output:

This name hasn't been used yet.
This name hasn't been used yet.
This name hasn't been used yet.
This name has been used.You need to use another one.
This name has been used.You need to use another one.

注:在保存用户名的时候其实最好是将其全部保存为小写字母,这样在进行比较的时候就不会需要额外再写一个列表把小写的保存了。

5-11 序数:序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。

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

Solution:

nums = range(1,10)
for num in nums:
    if num == 1:
        print("1st")
    elif num == 2:
        print("2nd")
    elif num == 3:
        print("3rd")
    else:
        print(str(num) + "th")

Output:

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

猜你喜欢

转载自blog.csdn.net/weixin_38311046/article/details/79680802