python之if语句

来源:互联网 发布:2015淘宝双十一销售额 编辑:程序博客网 时间:2024/05/29 13:14

1.条件测试:

每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式被称为条件测试。

Python根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码。

2.检查多个条件:

1.使用and检查多个条件。

要检查是否两个条件都为 True ,可使用关键字 and 将两个条件测试合而为一;如果每个测试都通过了,整个表达式就为 True ;反正为False.

  例:

age_0 = 22


age_1 = 18


age_0 >= 21 and age_1 >= 21


False


age_1 = 22


age_0 >= 21 and age_1 >= 21


True

2.使用or检查多个条件:

只要至少有一个条件满足,就能通过整个测试。仅当两个测试都没有通过时,使用 or 的表达式才为 False 。

age_0 = 22


age_1 = 18


age_0 >= 21 or age_1 >= 21


True


age_0 = 18


age_0 >= 21 or age_1 >= 21


False

3.检查特定值是否包含在列表中:

要判断特定的值是否已包含在列表中,可使用关键字 in 。

例:

requested = ['mushrooms', 'onions', 'pineapple']


'mushrooms' in requested


True


  'pepperoni' in requested


False


4.检查特定值是否不包含在列表中:

确定特定的值未包含在列表中很重要;在这种情况下,可使用关键字 not in 。

例:

banned_users = ['andrew', 'carolina', 'david']


user = 'marie'


  if user not in banned_users:


print(user.title() + ", you can post a response if you wish.")


5.if语句包含(简单的if语句,if-else 语句,if-elif-else结构)