Python编程:从入门到实践-if 语句

  • 简单示例

1 #!/usr/bin/env python
2 #-*- encoding:utf-8 -*-
3 cars = ['audi', 'bmw', 'subaru', 'toyota']
4 for car in cars:
5   if car == 'bmw':
6     print(car.upper())
7   else:
8     print(car.title())
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/demo.py
Audi
BMW
Subaru
Toyota
运行结果
  • 条件测试

  • 检查是否相等

>>> car = 'bmw'
>>> car == 'bmw'
True
>>> car = 'audi'
>>> car == 'bmw'
False
>>>
  •  检查是否相等时不考虑大小写

>>> car = 'Audi'
>>> car == 'audi'
False
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
  • 检查是否不相等

1 requested_toppings = 'mushrooms'
2 if requested_toppings != 'anchovies':
3   print("Hold the anchovies!")
  • 比较数字

>>> age = 18
>>> age == 18
True

 

#!/usr/bin/env python
#-*- encoding:utf-8 -*-
answer = 17
if answer != 42:
  print("That is not the correct answer.Please try again!")

 

C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/demo.py
That is not the correct answer.Please try again!
  •  检查多个条件

使用and检查多个条件

>>> 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

 使用or检查多个条件

>>> 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
  • 检查特定值是否包含在列表

>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False
>>>

  

 

posted on 2018-11-23 23:14  helontian  阅读(125)  评论(0)    收藏  举报