python 从入门到实践 第五章习题 (高级编程技巧 week3-1)
5.1
这里主要就讲了一些条件语句的判断条件。
其中我们以前可能没有接触过的就是这样的语句:检测某特定值是否在列表中。
这里有个新的关键词:in
5-2
print('abc' == 'abc')
if "aBc".lower() == "abc":
print("True")
if 4 != 4:
print("Not equal")
else:
print("Equal")
l = range(1,11)
print(1 in l)
print(11 in l)
print(1 in l and 2 in l) # return True
print(1 in l or 11 in l) # return True
5.3 if语句
基本的格式:
if conditional_test:
dodododo
else:
dodododo
当然还有另外一种结构:
if comditional_test:
dodododo
elif comditional_test2:
dodododo
elif conditional_test3:
dodododo
else:
dodododo
5-4
alien_color = "green"
if alien_color == "green":
print("You shoot a green alien! You got five points")
else:
print("You got ten points!")
5-6 人生的不同阶段
age = 20
if age < 2:
print("He is a baby.")
elif 2 <= age and age < 4:
print("He is learning walking.")
elif 4 <= age and age < 13:
print("He is a child.")
elif 13 <= age and age < 20:
print("He is a teenager.")
elif 20 <= age and age < 65:
print("He is an adult.")
else:
print("He is an old man.")
5-7 喜欢的水果
favorite_fruits = ["apple", "orange", "banana"]
if "apple" in favorite_fruits:
print("You really like apples." )
elif "orange" in favorite_fruits:
print("You really like oranges." )
elif "banana" in favorite_fruits:
print("You really like bananas." )
elif "pear" in favorite_fruits:
print("You really like pears.")
elif "blueberry" in favorite_fruits:
print("You really like bluebarries.")
5.4 使用if语句处理列表
5-8 / 5-9
users = ["admin", "John", "Mike", "Amy", "Lily"]
if users:
for name in users:
if name == "admin":
print("Hello admin, would you like to see a status report?")
else :
print("Hello ", name, ", thank you for logging in again")
else:
print("We need to find some users!")
5-10
current_users = ["John", "Mike", "Amy", "Lily","Yaron"]
new_users = ["John", "Walker", "Mike", "Kuly", "Amy"]
for user in new_users:
if user.title() in current_users:
print("please use another username")
else:
print("This user name haven't been used!")