本章知识点:
1.编写结果为True或False的条件测试。
2.if-else语句、if-elif-else结构。
3.for循环中以高效方式对特定的列表元素进行处理。
4.代码格式。
习题:
知识点:初步熟悉条件各种测试。
5-1条件测试
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
5-2更多的条件测试
name = 'Huang'
print(name == 'huang')
print(name.lower() == 'huang')
print(name != 'huang')
num1 = 22
num2 = 18
print(num1 > 20 and num1 >= 20)
print(num1 == 20 or num1 != 20)
print(num2 < 20 and num2 <= 20)
new_chart = ('Blue','Green','Yellow','Purple','Grey')
print('Blue' in new_chart)
print('Black' not in new_chart)
知识点:1、if语句、if-else语句、if-elif-else结构。
2、测试多个条件。
5-3外星人颜色1
alien_color1 = 'green'
if alien_color1 == 'green':
print('You get 5 points.')
else:
print('You do not get any points.')
5-4外星人颜色2
alien_color2 = 'yellow'
if alien_color2 == 'green':
print('You get 5 points.')
else:
print('You get 10 points.')
5-5外星人颜色3
alien_color3 = 'red'
if alien_color3 == 'green':
print('You get 5 points.')
elif alien_color3 == 'yellow':
print('You get 10 points.')
else:
print('You get 15 points')
5-6人生的不同阶段
num = 65
if num < 2:
print('你是婴儿')
elif num < 4:
print('你在蹒跚学步')
elif num < 13:
print('你是儿童')
elif num < 20:
print('你是青少年')
elif num < 65:
print('你是成年人')
elif num >= 65:
print('你是老年人')
5-7喜欢的水果
favourite_fruits = ['banana','apple','orange']
fruits = ['mango','apple','orange','watermelon','banana']
for tmp in fruits:
if tmp in favourite_fruits:
print('You really like ' + tmp)
知识点:使用if语句处理列表。
5-8 以特殊方式跟管理员打招呼 5-9处理没有用户的情形
users = ['admin','huang','zhang','gui','lin']
for tmp in users:
if tmp == 'admin':
print('Hello admin,would you like to see a status report?')
else:
print('Hello Eric,thank you for logging in again.')
users = []
if users:
print('There are some users.')
else:
print('We need to find some users.')
5-10检查用户名
current_users = ['admin','huang','zhang','gui','lin']
new_users = ['huang','Ke','Lin','lao','lai']
for tmp in new_users:
tmp = tmp.lower()
if tmp in current_users:
print('You should input another user name.')
else:
print('This name have not been used.')
5-11序数
number = [1,2,3,4,5,6,7,8,9]
for tmp in number:
if tmp == 1:
print('1st')
elif tmp == 2:
print('2nd')
elif tmp == 3:
print('3rd')
else:
print(str(tmp) + 'th')