首页 > 技术文章 > 《python编程从入门到实践》if语句

xzzheng 2019-01-10 23:51 原文

  • 条件测试

  每条if语句的核心是一个值为true 或 flase的表达式,称为条件测试。

  if语句的一个简单例子:

 1 cars=['audi','bmw','subra','toyota']
 2 
 3 for car in cars:
 4     if car=='bmw':#注意if后空格一下 直接写表达式,表达式后跟冒号
 5         print(car.upper())
 6     else: #else后有冒号
 7         print(car.title())
 8 输出为:
 9 Audi
10 BMW
11 Subra
12 Toyota

  ps:在C中 if(表达式)

    在python中 if 表达式 :

 

  • 检查相等(==)

  在检查是否相等时要考虑大小写,但如果只是想检查变量的值,就不用考虑大小写

  • 检查不相等(!=)

1 requested_topping = 'mushroom'
2 if requested_topping != 'anchovies':
3     print("hold the anchovies")
4 输出为:
5 hold the anchovies

 

  • 检查多个条件(and、or)

  当要满足多个条件时需要用and把多个条件连接起来;

  当要满足其中一个条件时,用or将条件连接起来。

 

  • 检查特定值包含在/不在列表中(in、not in)

  这与数据库里的sql语句类似:

 1 requested_toppings = ['mushrooms','onions','pineapple']
 2 if 'mushrooms' in requested_toppings:
 3     print("ture")
 4 if 'pepperoni' in requested_toppings:
 5     print("flase")
 6 输出为:
 7 ture
 8 
 9 banned_users = ['andrew','carlina','david']
10 user = 'marie'
11 if user not in banned_users:
12     print(user.title() + ",you can  post a respond!")
13 输出为:
14 Marie,you can  post a respond!
  • 布尔表达式

  布尔表达式是条件测试的别名,其结果要么为True,要么为False。

 

  • if-elif-else结构

  1.python只执行if-elif-else结构中的一个代码块,依次检查每个条件测试,只 执行通过测试的代码,跳过余下的;

  2.不要求if-elif后一定有else;

  3.如果知道最终测试条件,应考虑使用一个elif代码块来代替else代码块

  4.测试多个条件时,使用一系列简单if语句

 

 1 age = 66
 2 if age <4:
 3     price = 0
 4 elif age < 18:
 5     price = 5
 6 elif age < 65:
 7     price = 10
 8 else:
 9     price = 5
10 print("your admission cost is $"+str(price))
11 输出为:
12 your admission cost is $5

 

  • if语句处理列表

  简单例子:

 1 requested_toppings = ['mushrooms','green peppers','extra chess']
 2 for requested_topping in requested_toppings:
 3     if requested_topping=='green peppers':#检查特殊元素
 4         print("sorry,out of green peppers")
 5     else:
 6         print("adding "+requested_topping)
 7 print("\nfinished making your pizza")
 8 输出为:
 9 adding mushrooms
10 sorry,out of green peppers
11 adding extra chess
12 
13 finished making your pizza
  • 确定列表空否

 1 requested_toppings=[]
 2 if requested_toppings:#列表中有元素返回true
 3     for requested_topping in requested_toppings:
 4         print("adding "+requested_topping)
 5     print("\nfinished making your pizza")
 6 else:#列表中无元素
 7     print("are you sure you want a plain pizza?")
 8     
 9 输出为:
10 are you sure you want a plain pizza?

 

   总结:

    python的if、if-else、if-elif-else语句相当于c中的if、if else、if else语句的嵌套

    如果要运行多个代码块,就使用简单的if语句;

    若只想运行其中一个代码块,就用if-elif-else结构

 

推荐阅读