python基础(四)
4.if语句
#一个简单示例
letters = ['aa','bb','cc','dd','ee'] for letter in letters: if letter == 'cc': print(letter.upper()) else: print(letter.title())
Aa
Bb
CC
Dd
Ee
#条件测试
haha = 'jingjing' if haha != 'jingjian': print("wrong!")
wrong!
#检查多个条件 age_0 = 22 age_1 = 18 age_0 >= 21 and age_1 >= 21
False
age_0 >= 21 or age_1 >= 21
True
(age_0 >= 21) and (age_1 <= 21)
True
#检查特定值是否包含在列表中 dd = ['yu','li','lu','ting'] 'jing' in dd
False
'ting' in dd
True
if 'lu' not in dd: print("buzai") else: print("zai")
zai
#布尔表达式,条件测试的别名,结果是Ture或者False game_active = Ture can_edit = False
#if语句
#if elif else age = 10 if age < 4: print('free') elif age < 18: print('5') else: print('10')
5
age = 36 if age < 4: print('free') elif age < 18: print('5') else: print('10')
10
age = 36 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 0 print("cost is:" + str(price)+ "!")
cost is:10!
#省略else部分 age = 69 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 elif age > 65: price = 0 print("cost is:" + str(price)+ "!")
cost is:0!
#使用if语句处理列表
letters = ['a','b','c','d','e'] for letter in letters: print("adding " + letter + ".") print("\nOk!")
adding a.
adding b.
adding c.
adding d.
adding e.
Ok!
letters = ['a','b','c','d','e'] for letter in letters: if letter =='c': print('yeyey') else: print('nonon')
nonon
nonon
yeyey
nonon
nonon
#确定列表不是空的,列表是空的前一个if返回False,打印else中信息 titdds = [] if titdds: for titdd in titdds: print("adding" + titdd + ".") print("\nhahaha") else: print("didididi")
didididi
#使用多个列表 yuans = ['aa','bb','cc','ss'] adds = ['tt','aa','ll','pp'] for yuan in yuans: if yuan in adds: print("yeyeyey") else: print("nononon")
yeyeyey
nononon
nononon
nononon
#设置if语句的格式
== >= <=等比较运算符左右各一个空格
if age < 4: