python入门-if
if
if-elif-else
age=12
if age<4:
price=4
elif age<18:
price=5
else :
price=6
print("cost is "+str(price)+".")
- 简单例子,注意写法elif,用price的值更便于修改
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Hold the anchovies")
if 'extra cheese' in requested_toppings:
print("add the anchovies")
- 当要测试多个条件时,应该使用不包括elif和else的if语句,可能多个条件为true
- 如果使用了elif和else,当满足一个条件时就会退出,不会继续判断剩余条件
使用if语句处理列表
requested_toppings=['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings :
if requested_topping =='green peppers':
print("we dont have peppers")
else:
print("Adding "+requested_topping+' .')
print("\n finish this pizza")
- 对for中某个元素进行单独操作时可以用到if
requested_toppings1=[]
if requested_toppings1:
for requested_topping in requested_toppings :
print("Adding "+requested_topping+' .')
else:
print("Are you sure?")
- 确定列表元素不为空,即列表名在条件表达式中,至少含有一个元素为true,列表为空返回False,在进行for循环之前,对列表是否为空进行检查十分必要
requested_toppings=['mushrooms','french fries','extra cheese']
available_toppings=['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings :
if requested_topping in available_toppings:
print("Adding "+requested_topping+' .')
else:
print("we dont have "+requested_topping)
print("\n finish this pizza")
- if语句使用多个列表
if语句的格式
if age > 4:
- 在><或者≥,≤运算符左右两边都嫁一个空格