您的位置:首页 > 编程语言 > Python开发

[python作业] [第三周] [周一]

2018-03-19 23:15 429 查看
5-2 更多的条件测试:你并非只能创建 10 个测试。如果你想尝试做更多的比较,可

再编写一些测试,并将它们加入到 conditional_tests.py 中。对于下面列出的各种测试,

至少编写一个结果为 True 和 False 的测试。

 检查两个字符串相等和不等。

 使用函数 lower()的测试。

 检查两个数字相等、不等、大于、小于、大于等于和小于等于。

 使用关键字 and 和 or 的测试。

 测试特定的值是否包含在列表中。

 测试特定的值是否未包含在列表中。

>>> 'nihao' == 'Nihao'
False
>>> 'nihao' != 'Nihao'
True
>>> 'nihao' == 'Nihao'.lower()
True
>>> 5 == 5 and 1 != 0 and 1 > 0 and 0 < 1 and 1 >= 1 and 1 <= 2
True
>>> 1 > 2 or 1 > 0
True
>>> my_list = list(range(0, 11))
>>> 1 in my_list
True
>>> 11 in my_list
False
>>> 11 not in my_list
True


5-5 外星人颜色#3:将练习 5-4 中的 if-else 结构改为 if-elif-else 结构。

 如果外星人是绿色的,就打印一条消息,指出玩家获得了 5 个点。

 如果外星人是黄色的,就打印一条消息,指出玩家获得了 10 个点。

 如果外星人是红色的,就打印一条消息,指出玩家获得了 15 个点。

 编写这个程序的三个版本,它们分别在外星人为绿色、黄色和红色时打印一条

消息。

alien_color = 'red'
if alien_color == 'green':
print('You get 5 points!')
elif alien_color == 'yellow':
print('You get 10 points!')
else:
print('You get 15 points!')

alien_color = 'green'
if alien_color == 'green':
print('You get 5 points!')

alien_color = 'yellow'
if alien_color == 'yellow':
print('You get 10 points!')


Output:
You get 15 points!
You get 5 points!
You get 10 points!


5-6 人生的不同阶段: 设置变量 age 的值, 再编写一个 if-elif-else 结构, 根据 age

的值判断处于人生的哪个阶段。

 如果一个人的年龄小于 2 岁,就打印一条消息,指出他是婴儿。

 如果一个人的年龄为 2(含)~ 4 岁,就打印一条消息,指出他正蹒跚学步。

 如果一个人的年龄为 4(含)~ 13 岁,就打印一条消息,指出他是儿童。

 如果一个人的年龄为 13(含)~ 20 岁,就打印一条消息,指出他是青少年。

 如果一个人的年龄为 20(含)~ 65 岁,就打印一条消息,指出他是成年人。

 如果一个人的年龄超过 65(含) 岁,就打印一条消息,指出他是老年人。

for i in range(0, 6):
age = int(input('Please input you age:'))
if age < 2:
print("You're a baby\n")
elif age < 4:
print("You're learning to walk\n")
elif age < 13:
print("You're a child\n")
elif age < 20:
print("You're a teenager\n")
elif age < 65:
print("You're an adult\n")
else:
print("You're an old man")


Output:
Please input you age:1
You're a baby

Please input you age:3
You're learning to walk

Please input you age:5
You're a child

Please input you age:15
You're a teenager

Please input you age:20
You're an adult

Please input you age:66
You're an old man


5-10 检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名

都独一无二的方式。

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

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

个用户名也包含在列表 current_users 中。

 遍历列表 new_users,对于其中的每个用户名,都检查它是否已被使用。如果是

这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指

出这个用户名未被使用。

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

名’JOHN’。

current_users = ['A', 'B', 'C', 'D', 'E']
new_users = ['d', 'E', 'F', 'G', 'H']
for name in new_users:
if name.lower() in [temp.lower() for temp in current_users]:
print("The name " + name + " was taken, please select another one.")
else:
print("You can use the name " + name)


Output:
The name d was taken, please select another one.
The name E was taken, please select another one.
You can use the name F
You can use the name G
You can use the name H


90df
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: