python3.7入门系列五 if 语句

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bowei026/article/details/89857171

if 是条件判断语句,是高级语言都有的特性。

fruits = ['apple', 'banana', 'pear', 'strawberry']
for fruit in fruits:
    if fruit == 'banana':
        print(fruit.upper())
    else:
        print(fruit.title())

判断是否相等
>>> fruit = 'peach'
>>> fruit == 'apple'
False

判断是否相等时不考虑大小写
>>> fruit = 'Apple'
>>> fruit.lower() == 'apple'
True

判断是否不相等
>>> fruit = 'peach'
>>> fruit != 'apple'
True

数字比较
>>> age = 18
>>> age == 18
True
数字比较有等于、小于、小于等于、大于、大于等于
>>> age = 18
>>> age == 18
True
>>> age < 17
False
>>> age <= 17
False
>>>
>>> age > 18
False
>>> age >= 18
True

判断多个条件
>>> age = 18
>>> height = 170
>>> age >= 18 and height >= 170
True
>>> age > 18 or height > 165
True
>>> (age > 18) or (height > 165)
True

判断特定值是否包含/不包含在列表或字符串中
>>> fruits = ['apple', 'banana', 'pear', 'strawberry']
>>> 'pear' in fruits
True
>>> 'he' in 'hello'
True
>>> 'pear' not in fruits
False
>>> 'he' not in 'hello'
False

布尔表达式
>>> a = 'he' not in 'hello'
>>> a
False
>>> changed = True
>>> changed
True

if 语句
>>> age = 19
>>> if age >= 18:
...     print('你成年了')
...
你成年了

if - else
>>> age = 17
>>> if age >= 18:
...     print('你成年了')
... else:
...     print('你未成年')
...
你未成年

if - elif - else
>>> age = 19
>>> if age < 18:
...     print('你未成年')
... elif age < 22:
...     print('你成年了,但是你还不能结婚')
... else:
...     print('你可以结婚了')
...
你成年了,但是你还不能结婚

可以有多个elif
>>> age = 33
>>> if age < 18:
...     print('你未成年')
... elif age < 22:
...     print('你还不能结婚')
... elif age < 30:
...     print('你该结婚了')
... elif age < 60:
...     print('你还不能退休')
... else:
...     print('你可以退休了')
...
你还不能退休

判断列表/字符串是否为空
>>> fruits = ['apple', 'banana', 'pear', 'strawberry']
>>> if fruits:
...     print('还有水果可以吃')
... else:
...     print('水果吃完了')
...
还有水果可以吃

>>> message = 'hello python'
>>> if message:
...     print('你有新的消息')
... else:
...     print('没有消息')
...
你有新的消息

使用多个列表
>>> fruits = ['apple', 'banana', 'pear', 'strawberry']
>>> today_foods = ['peach', 'banana', 'watermelon', 'strawberry']
>>> for food in today_foods:
...     if food in fruits:
...         print(food + '有库存,晚上可以吃')
...     else:
...         print(food + '没有了,晚上吃不到了')
...
peach没有了,晚上吃不到了
banana有库存,晚上可以吃
watermelon没有了,晚上吃不到了
strawberry有库存,晚上可以吃
 

本文内容到此结束,更多内容可关注公众号和个人微信号:

猜你喜欢

转载自blog.csdn.net/bowei026/article/details/89857171