if else if语句的用法python_Python笔记3---if语句、if-elif-else 结构、使用if语句处理列表...

五、if语句

5.1 一个简单示例

使用if 语句来正确地处理特殊情形。

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

for car in cars:

if car == 'bmw':

print(car.upper())

else:

print(car.title())

代码输出:

Audi

BMW

Subaru

Toyota

5.2 条件测试

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

Python根据条件测试的值为True 还是False 来决定是否执行if 语句中的代码。

如果条件测试的值为True ,Python就执行紧跟在if 语句后面的代码;如果为False ,Python就忽略这些代码。

5.2.1 检查是否相等

大多数条件测试都将一个变量的当前值同特定值进行比较。

>>> car = 'bmw' >>> car = 'audi'

>>> car == 'bmw' >>> car == 'bmw'

True False

5.2.2 检查是否相等时区分大小写

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

>>> car = 'Audi'

>>> car == 'audi'

False

5.2.3 检查是否不相等

要判断两个值是否不等,可结合使用惊叹号和等号(!=),其中的惊叹号表示不。

requested_topping = 'mushrooms'

if requested_topping != 'anchovies':

print("Hold the anchovies!")

代码输出:

Hold the anchovies!

5.2.4 比较数字检查数值非常简单。

answer = 17

if answer != 42:

print("That is not the correct answer. Please try again!")5.2.5 检查多个条件

1)使用and检查多个条件

要检查是否两个条件都为True ,可使用关键字and 将两个条件测试合而为一;

如果每个测试都通过了,整个表达式就为True ;

如果至少有一个测试没有通过,整个表达式就为False 。

>>> age_0 = 22

>>> age_1 = 18

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

False

2)使用or检查多个条件关键字 or 也能够让你检查多个条件,但只要至少一个条件满足,就能够通过测试。

仅当两个测试都没有通过时,使用or的表达式才返回False。

>>> age_0 = 18

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

False

5.2.6 检查特定值是否要判断特定的值是否已包含在列表中,可使用关键字in 。

>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']

>>> 'mushrooms' in requested_toppings

True

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

确定特定的值未包含在列表中使用关键字not in 。

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

user = 'marie'

if user not in banned_users:

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

代码输出:

Marie, you can post a response if you wish.

5.2.8 布尔表达式随着你对编程的了解越来越深入,将遇到术语布尔表达式,布尔值通常用于记录条件。

game_active = True

can_edit = False

5.3 if语句

5.3.1 简单的if语句

最简单的if 语句只有一个测试和一个操作:

age = 19

if age >= 18:

print("You are old enough to vote!")

print("Have you registered to vote yet?")

代码输出:

You are old enough to vote!

Have you registered to vote yet?

注:在if 语句中,缩进的作用与for 循环中相同。如果测试通过了,将执行if 语句后面所有缩进的代码行,否则将忽略它们。

5.3.2 if-else语句

在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作;在这种情况下,可使用Python提供的if-else 语句。

age = 17

if age >= 18:

print("You are old enough to vote!")

print("Have you registered to vote yet?")

else:

print("Sorry, you are too young to vote.")

print("Please register to vote as soon as you turn 18!")

代码输出:

Sorry, you are too young to vote.

Please register to vote as soon as you turn 18!

注:if-else 结构非常适合用于要让Python执行两种操作之一的情形。

5.3.3 if-elif-else结构

经常需要检查超过两个的情形,为此可使用Python提供的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 admission cost is $10.")

代码输出:

Your admission cost is $5.

5.3.4 使用多个elif代码块

可根据需要使用任意数量的elif 代码块。

age = 12

if age < 4:

price = 0

elif age < 18:

price = 5

elif age < 65:

price = 10

else:

price = 5

print("Your admission cost is $" + str(price) + ".")

5.3.5 省略else代码块Python并不是要求if-elif结构后面必须有else代码块。

age = 12

if age < 4:

price = 0

elif age < 18:

price = 5

elif age < 65:

price = 10

elif age >= 65:

price = 5

print("Your admission cost is $" + str(price) + ".")

注:else 是一条包罗万象的语句,只要不满足任何if 或elif 中的条件测试,其中的代码就会执行。5.3.6 测试多个条件有时候必须检查你关心的所有条件,在这种情况下,应使用一系列简单if 语句。

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

if 'mushrooms' in requested_toppings:

print("Adding mushrooms.")

if 'pepperoni' in requested_toppings:

print("Adding pepperoni.")

if 'extra cheese' in requested_toppings:

print("Adding extra cheese.")

print("\nFinished making your pizza!")

代码输出:

Adding mushrooms.

Adding extra cheese.

Finished making your pizza!

5.4 使用if语句处理列表

5.4.1 检查特殊元素

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']

for requested_topping in requested_toppings:

if requested_topping == 'green peppers':

print("Sorry, we are out of green peppers right now.")

else:

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

print("\nFinished making your pizza!")

代码输出:

Sorry, we are out of green peppers right now.

Adding extra cheese.

Finished making your pizza!

5.4.2 确定列表不是空的

检查列表元素是否为空

requested_toppings = []

if requested_toppings:

for requested_toppingin requested_toppings:

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

print("\nFinished making your pizza!")

else:

print("Are you sure you want a plain pizza?")注:如果requested_toppings 不为空就运行for 循环;否则就打印一条消息。

5.4.3 使用多个列表

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!

5.5 设置if语句的格式PEP 8提供的唯一建议是,在诸如== 、>= 和<= 等比较运算符两边各添加一个空格。if age < 4: 要比if age<4: 好。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值