Python 从入门到实践 5-8 课后习题

来源:互联网 发布:mac壁纸软件推荐 编辑:程序博客网 时间:2024/06/14 18:54

5.8

以特殊方式跟管理员打招呼:创建一个至少包含5 个用户名的列表,且其中一

个用户名为'admin'。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。
遍历用户名列表,并向每位用户打印一条问候消息。
 如果用户名为'admin',就打印一条特殊的问候消息,如“Hello admin, would you
like to see a status report?”。
 否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。

names = ['admin', 'David', 'Jone', 'Mickle', 'Jane']for name in names:    if 'admin' in name:        print("Hello admin, would you like to see a status report?")    else:        print("Hello Eric,thank you for logging in again")问题1:else后的print会打印4遍。
问题2:如果与else缩进一样的话。for循环只会执行一次。
5.9
处理没有用户的情形:在为完成练习5-8 编写的程序中,添加一条if 语句,检查用户名列表是否为空。 如果为空,就打印消息“We need to find some users!”。 删除列表中的所有用户名,确定将打印正确的消息。
#添加if语句判断用户名列表是否为空列表names = ['David', 'admin', 'Jone', 'Mickle', 'Jane']if names:    for name in names:        if 'admin' in name:            print("Hello admin, would you like to see a status report?")        else:            print("Hello Eric,thank you for logging in again")else:    print("We need find some users!")
5.10检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。 创建一个至少包含5 个用户名的列表,并将其命名为current_users。 再创建一个包含5 个用户名的列表,将其命名为new_users,并确保其中有一两个用户名也包含在列表current_users 中。 遍历列表new_users,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。

current_users = ['Jone', 'David', 'John', 'Franck', 'admin']new_users = ['Lemon', 'Jone', 'Len', 'John', 'Hayley']for new_users in current_users:    if new_users.lower() in current_users.lower():        print("The name has created,please change the name.^_^")    else:        print("OK,the name which you named could use,please enter")
问题:错误不知道在哪,运行不出来,希望可以得到帮助,或者我自己可以理解了,再回头更改!
5.11
序数:序数表示位置,如1st 和2nd。大多数序数都以th 结尾,只有1、2 和3例外。 在一个列表中存储数字1~9。 遍历这个列表。 在循环中使用一个if-elif-else 结构,以打印每个数字对应的序数。输出内容应为1st、2nd、3rd、4th、5th、6th、7th、8th 和9th,但每个序数都独占一行。
numbers = [1, 2, 3, 4, 5 ,6, 7, 8, 9]for number in numbers:    if number == 1:        print(str(number) +'st')    elif number == 2:        print(str(number) + 'nd')    elif number == 3:        print(str(number) + 'rd')    else:        print(str(number) + 'th')

阅读全文
0 0
原创粉丝点击