1.其实Python和C语言中的if语句是极相似的,因为if语句的职能便是判断,区别如下:
(1).Python(无括号,有冒号且缩进):
if car =='byd':
print(car.upper())
(2).C(有括号,无冒号且缩进无意义):
if(car=="byd")
printf("%s",car);
2.检查是否不相等:将 “==” 换为"!="即可。
3.比较数字时可用 " ==、>、>=、<、<=、!="等符号。
4.同时并列比较数据:
age_1=10
age_2=20
if age_1>=10 or age_2>=20: #这里的or可以替换为and,只不过语义改变。
print('cql666')
5.检查特定值是否包含于列表之中(if语句的冒号和缩进不可省):
names=['ldl','xhx','cql']
if 'ldl' in names: #如果检查特定值是否不包含在列表中,则为:if 'ldl' not in the names:
print('ldl is one of the names!' )
6.if-else语句:
names=['ldl','xhx','cql']
if 'ldl' in names:
print('ldl is one of the names!' )
else:
print("ldl isn't one of the names!")
7.if-elif-else语句:
names=['ldl','xhx','cql']
if 'ldl' in names:
print('ldl is one of the names!' )
elif 'xhx' in names:
print("xhx is one of the names!")
else:
print("cql is one of the names!")
8.if-elif语句:
众所周知,if语句后并不是必然要加上else语句,因此我们可以一直使用elif语句在if之后进行判断并选择性运行代码。
For example:
names=['ldl','xhx','cql','syx']
if 'ldl' in the names:
print('ldl is one of the names!' )
elif 'xhx' in names:
print("xhx is one of the names!")
elif 'cql' in names:
print("cql is one of the names!")
9.测试多个条件:
if-elif语句固然很强大,但其仅能对一组数据进行比较,若其中一条为True,则跳过余下测试,因此可采用多个if来进行:
names=['ldl','xhx','cql','syx']
if 'ldl' in names:
print('ldl is one of the names!' )
if 'xhx' in names:
print("xhx is one of the names!")
if 'cql' in names:
print("cql is one of the names!")
这个代码输出了三条语句,而之前的if-elif却都只能输出一条,其余不满足者皆会被跳过。
10.for语句与if语句的嵌套:
names=['ldl','xhx','zsd','syx','cql']
for name in names:
if name=='cql‘:
print(name + ' is so handsome!')
else:
print(name+' is also handsome,but cql is more than him.')
print(name+' is my roommate')
11.确保列表不为空:
names=[]
if names:
for name in names:
print('he is a fool')
else:
print('there is nothing')
12.使用多个列表:
names=['ldl','cql','xhx','syx','zsd']
room331=['ldl','cql','xhx','syx']
for mate in names:
if mate in room331:
print(mate+' is very good.')
else:
print(mate+'is not in 331.')
总结完毕~准备睡觉,全力为明天下午的数建校赛做准备!!!