1 格式
cars = ['audi','bmw','subaru','toyata'] for car in cars: if car =='bmw': print(car.upper()) else: print(car.title())
python检查相等的时候区分大小写
2 检查是否相等
car='bmw' car=='bmw'
检查不相等
requested_topping='mushrooms' if requested_topping !='anchovies': print('hold the anchovies!')
3 多个条件 and or
age_0=22 age_1=18 if age_0>=21 and age_1>=21: print('ok') else: print('not ok')
4 检查特定的值 是否在列表中 in not in
requested_toppings=['mushrooms','onions','pineapple'] 'mushrooms' in requested_toppings
'mushrooms' not in requested_toppings
5 IF语句
if condition:
do somthing
age=19 if age>=18: print('is ok') print('this is second ok')
6 if-else语句
age=17 if age>=18: print('first is ok') print('second is ok') else: print('third is ok') print('fourth is ok')
7 if-elif-else 结构
age=12 if age<4: print('your admission cost is $0') elif age<18: print('your admission cost is #5') else: print('your adminssion cost is #10')
8 多个elif语句
age=12 if age<4: price=0 elif age<18: price=5 elif age<65: price=10 else: price=5 print(price)
9 确认列表是不是空的
requested_toppings=[] if requested_toppings: for requested_topping in requested_toppings: print('adding'+requested_topping+".") print(" finished making your pizza!") else: print('are you sure you want a plain pizza')
10 IF语句格式
在 == >= <= 两边各加一个空格