美文网首页
Python:if语句

Python:if语句

作者: Dragon_boy | 来源:发表于2020-07-24 18:06 被阅读0次

示例

cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
    if car == 'bmw':
        prinit(car.upper())
    else:
        print(car.title())

条件测试

检查是否相等

使用==会返回一个布尔值。

检查相等时不考虑大小写

Python中检查是否相等时区分大小写:

car = 'Audi'
car == 'audi'  # False

如果要不区分大小写,可以将值都转化为小写,使用lower(),且这种方式不会修改原值。

检查是否不相等

使用!=即可,和大多数语言一样。

比较数字

可以使用许多数学比较,<,<=,>,>=

检查多个条件

使用关键字and,和or

  1. 使用and
    and左右两个条件都为Tue,那么结果为True:
age_0 >= 21 and age_1 >=21

2.使用or
只要有一个条件为True,结果就为True,反之为False:

age_0 >=21 or age_1 >= 21

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

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

requested_toppings = ['mushrooms', 'onions','pineapple']
'mushrooms' in requested_toppings  # True

检查特定值不包含在列表中

使用not in:

banned_user = ['andrew', 'carolina', 'david']
user = 'marie'

if user not in banned_users:
    print(user.title() + ', you can post a response if you wish.')

if语句

简单的if语句:

if conditional_test:
    do something

if-else语句

age = 17
if age >= 18:
    prinit('you are old enough.')
else:
    print('sorry, you are too young to vote.')

if-elif-else语句

age = 12

if age < 4:
    print('Your admission cost is $0.')
elif age < 18:
    print('Your admission cost is $5.')
else:
    print('Your aimission cost is $10.')

可以使用多个elif,也可以省略else。

使用if语句处理列表

确定列表不是空的

requested_toppings = []
if requested_toppings:
    do something

如果列表为空,if语句处会返回False。

相关文章

网友评论

      本文标题:Python:if语句

      本文链接:https://www.haomeiwen.com/subject/wgkslktx.html