第四章 if语句

4.1 条件测试

4.1.1 检查是否相等

car = 'bmw'
print(car == 'bmw')
print(car == 'byd')
print(car != 'byd')

输出结果:

True
False
True

  • == 等于
  • != 不等于
  • >, >=, <, <= 大小于等于

4.1.2 检查多个条件

car = 'bmw'
phone = 'iphone'
print(car == 'bmw' and phone == 'iphone')
print(car == 'byd' or phone == 'samsung')

True
False

  • and 逻辑且
  • or 逻辑或

4.1.3 检查特定值是否在列表中

nums = [10, 20, 30]
print(30 in nums)
print(40 not in nums)

True

True

  • in 在列表中
  • not in不在列表中

4.1.4 布尔表达式

flag = True
flag = False

不多赘述

4.2 if语句

age = 15
if age >= 18:
    print("You are old enough")
    print("You can vote now")
Python的if语句不需要加括号。注意冒号

4.2.1 if-else语句

age = 15
if age >= 18:
    print("You are old enough")
    print("You can vote now")
else:
    print("You are too young")
    print("Please wait for " + str(18-age) + " year(s)")

输出结果:

You are too young

Please wait for 3 year(s)

4.2.2 if-elif-else语句

age = 15
if age >= 18:
    print("You are an adult")
elif age >= 12:
    print("You are a teenager")
else: 
    print("You are a child")

输出结果:

You are a teenager

4.2.3 检查列表是否为空

nums = []
if nums:
    print("list is not empty")
else:
    print("list is empty")

输出为:

list is empty

4.2.4 if语句与布尔表达式

flag = True
if flag:
    print("YES")
else:
    print("NO")

输出:

YES

不多赘述