python编程:从入门到实践习题第五章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_list=['admin','a','b','c','d']

for user in users_list:

    if user=='admin':

        print("Hello admin,would you like to see a status report?")

    else:

        print("Hello "+user+",thank you for logging in again.")

5-9 处理没有用户的情形:
在为完成练习 5-8编写的程序中,添加一条 if 语句,检 查用户名列表是否为空。

 如果为空,就打印消息“We need to find some users!”。

 删除列表中的所有用户名,确定将打印正确的消息。

users_list=[]

if users_list:

    for user in users_list:

        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 检查用户名:
按下面的说明编写一个程序,模拟网站确保每位用户的用户名 都独一无二的方式。

 创建一个至少包含 5个用户名的列表,并将其命名为 current_users。

 再创建一个包含 5个用户名的列表,将其命名为 new_users,并确保其中有一两 个用户名也包含在列表 current_users 中。

 遍历列表 new_users,对于其中的每个用户名,都检查它是否已被使用。如果是 这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指 出这个用户名未被使用。

 确保比较时不区分大消息;换句话说,如果用户名’John’已被使用,应拒绝用户 名’JOHN’。

current_users=['John','Sona','Angela','Luna','Civier']

new_users=['John','sona','Lisa','Tracy','Mike']

for user in new_users:

    use=False

    for used in current_users:

        if user.lower() ==used.lower():

            use=True

    if use:

        print("Used,try another name!")   

    else:

        print("Congratulations,you can use "+user+" as your username!")

或者

current_users=['John','Sona','Angela','Luna','Civier']

new_users=['John','sona','Lisa','Tracy','Mike']

lower_current_users=[]

for used in current_users:

    lower_current_users.append(used.lower())

for users in new_users:

    if users.lower() in lower_current_users:

        print("Used,try another name!")

    else:

        print("Congratulations ,you can use "+users+" as your username!")

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

list=[1,2,3,4,5,6,7,8,9]

for num in list:

    if num<2:

        print(str(num)+"st")

    elif num<3:

        print(str(num)+"nd")

    else:

        print(str(num)+"th")

版权声明:本文为Wood_Cube原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。