python学习if语句_Python学习(七)if语句

Python if语句

Python if语句

Python中,if语句可以检查程序的状态,并依据状态采取相应的措施

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

for car in cars:

if car == 'bmw':

#car等于“bmw"全部大写

print(car.upper())

else:

#首字母大写

print(car.title())

Audi

BMW

Subru

Toyota

条件测试

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

检查是否相等

>>> car = 'bmw'

>>> car == 'bmw'

True

>>> car == 'Bmw'

False

检查是否相等时不考虑大小写

不考虑大小写时可将单词转换为全部小写

>>> car = 'Bmw'

>>> car == 'bmw'

False

>>> car.lower() == 'bmw'

True

name = "Hello world!"

单词首字母大写

print(name.title())

Hello World!

单词全部字母大写

print(name.upper())

HELLO WORLD!

单词全部字母小写

print(name.lower())

hello world!

检查是否不相等

判断两个值是否不等,可以结合使用感叹号和等号(!=),很多程序语言都是这样表示

requested_topping = 'mushrooms'

if requested_topping != 'anchovies':

print("Hold the anchovies")

else:

print("Hold not the anchovies")

Hold the anchovies

比较数字

数字对比可以使用==(=,>,>=,

>>> age = 18

>>> age == 18

True

>>> age = 19

>>> age < 20

True

>>> age <= 20

False

>>> age >= 20

False

检查多个条件

1、使用and检查多个条件

检查多个条件都符合,使用and

age_0 = 22

age_1 = 18

print(age_0 >= 21 and age_1 >=21)

False

age_1 = 21

print(age_0 >= 21 and age_1 >=21)

True

2、使用or检查多个条件

检查多个条件只要一条符合,使用or

age_0 = 22

age_1 = 18

print(age_0 >= 21 or age_1 >=21)

True

age_0 = 18

print(age_0 >= 21 or age_1 >=21)

False

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

检查特定值是否包含在列表中,实例如某用户在BBS中已经被禁言,不允许在发表评论。这是就可以使用“not in”筛选这个用户

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

user = 'marie'

if user not in banned_users:

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

Marie, you can post a response if you wish.

布尔值表达

布尔值表达:相同“True”;不同“False”

确定列表不是空的

requested_toppings = []

if requested_toppings:

for i in requested_toppings:

print('adding %s .'%(i))

print("==>>: Finished making your pizza!")

else:

print("==>>: Are you sure you want a plain pizza?")

==>>: Are you sure you want a plain pizza?

列表为空不执行for循环直接执行else

使用多个列表对比

available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese']

requested_toppings = ['mushrooms', 'french fries', 'extra cheese']

for requested_topping in requested_toppings:

if requested_topping in available_toppings:

print("Adding " + requested_topping + ".")

else:

print("Sorry, we don't have " + requested_topping + ".")

print("\nFinished making your pizza!")

Adding mushrooms.

Sorry, we don't have french fries.

Adding extra cheese.

Finished making your pizza!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值