5.1 条件测试
if之后的判断语句称作条件测试。用‘==’表示相等,‘!=’表示不相等。
两个对比量的大小写在检查时会被区分开来。
检查多个条件可用'and'或者'or'来连接;
检查特定值是否在列表中可用'in'来完成;同时用'not in'检查特定值是否不包含在列表中。
布尔表达式的结果为'True'或'False'。
动手练习:
# coding=GBK
#5-1 条件测试
phone='Iphone'
print("Is phone=='Iphone'? I predict True.")
print(phone=='Iphone')
print("\nIs phone=='Huawei'? I predict False.")
print(phone=='Huawei')
#5-2
a='Xming'
b='xming'
print('\n'+str(a==b))
print(a.lower()==b)
number_1=1995
number_2=1990
if number_1>=number_2:
print('相等')
else:
print('不相等')
5.2 if语句
if、if-else、if-elif-else从逻辑看来都比较简单,在嵌套for循环时注意缩进即可。
注意'=='与'='号混用的带来的bug。
在比较运算符的两端各添加一个空格让代码便于阅读:if age < 4优于if age<4
练习:
#5-8
name=['admin','Eric','Tom','Jerry','Jack']
for i in name:
if i=='admin':
print('Hello admin,would you like to see a status report?')
else:
print('Hello '+i+',thank you for logging in again.')
#5-9
name=[]
if name:
for a in name:
if a=='admin':
print('Hello admin,would you like to see a status report?')
else:
print('Hello '+i+',thank you for logging in again.')
else:
print('We need to find some users!')
#5-10
current_users=['Adman','Blank','Cath','john','Ericy','Lina']
new_users=['Am','Bh','Ck','JOHN','LINA']
m=0
for i in new_users:
current_users2=[b.upper() for b in current_users]
if i.upper() in current_users2 :
a=1
else:
a=0
if a==1:
print('You need to rewrite you name')
else:
print('This name is unused')
#5-11
number=list(range(1,10))
print(number)
for i in number:
if i==1:
print(str(i)+'st')
elif i==2:
print(str(i)+'nd')
elif i==3:
print(str(i)+'rd')
else:
print(str(i)+'th')