五、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: 好。

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

  1. LINQ语句用法(笔记)

    LINQ语句用法(笔记) Linq语句是一组方法,允许以最少的代码对集合执行筛选.排序和分组操作.Linq代表语言集成查询.它是一组基于将查询功能集成到C#语言中的技术的名称.虽然Linq方法不是语言 ...

  2. python用法查询笔记(二)—— 面向对象

    python用法查询笔记(二)-- 面向对象 类 1. 创建类 2. 把类中的变量传递给类中的函数 3. 给类方法传参 4. 类的实例化 5. 类的实例化 6. 重写类方法 7. 初始化函数 8. 继 ...

  3. Python - while语句和if语句 的 用法 及 代码

    while语句和if语句 的 用法 及 代码 本文地址 : http://blog.csdn.net/caroline_wendy/article/details/17199771 Python中wh ...

  4. python语言if语句-Python入门教程之if语句的用法

    这篇文章主要介绍了Python入门教程之if语句的用法,是Python入门的基础知识,需要的朋友可以参考下 OK分享完毕!需要Python资料的可以加QQ群:832339352 进群免费领取下面资料! ...

  5. SQL基本语句及用法

    目录 一.基本SQL语句用法及概述 1.常用MySQL命令 2.语法规范 3.SQL语句分类 二.数据查询语言 1.基础查询 1)查询的字段列表可以是字段.常量.表达式.函数等 2)使用别名,字段名和 ...

  6. Oracle with语句的用法

    http://database.51cto.com/art/201010/231528.htm Oracle with语句是经常可以见到的语句,下面就为您详细介绍Oracle with语句的用法,如果 ...

  7. SQL Server中drop、truncate和delete语句的用法

    SQL Server中drop.truncate和delete语句的用法 drop  删除表和表中的所有数据(不保留表的结构) drop table tablename truncate   删除表中 ...

  8. c语言 case语句用法,switch ... case语句的用法[组图]

    switch ... case语句的用法[组图] 08-13栏目:技术 TAG:switch case语句 switch case语句 当情况大于或等于4种的时候就用switch ...  case语 ...

  9. php 类中调用另类,PHP return语句另类用法不止是在函数中,return语句_PHP教程

    PHP return语句另类用法不止是在函数中,return语句 分享下PHP return语句的另一个作用,在bbPress的代码中看到的一个奇葩使用方法. 一直以为,return只能出现在函数中, ...

最新文章

  1. python基础之python中if __name__ == '__main__': 的解析
  2. SharePoint 2013 术语和术语集介绍
  3. 【poj1742】 Coins
  4. app inventer与java不同,App Inventor内置块
  5. spring学习(26):更优雅的依赖注入 在@bean注入参数
  6. ZetCode Java 教程
  7. anaconda安装python包_Anaconda:安装或更新 Python 第三方包
  8. mysql 简单游标
  9. 限时删!我亲自整理一套目标检测、卷积神经网络和OpenCV学习资料(教程/PPT/代码)...
  10. 一个计算周次和本周时间范围的代码(c#)
  11. Python|进程调度算法
  12. 陈越微博c语言自学攻略,数据结构自学攻略
  13. 独家对话行癫:最详解密阿里云顶层设计和底层逻辑
  14. Java面试题:单核CPU支持多线程吗?
  15. 8w 字,给程序员的职场第一课(上篇)
  16. 解决ubuntu下wps卡顿和缺少字体
  17. 视觉设计本地化的重要性
  18. shell脚本——一键完成虚拟机初始化
  19. android x86引导修复,Android-x86 9.0-r2 发布,更新内核与UEFI引导修复
  20. itoa或者_itoa_s,fopen 和 fopen_s等几种函数的用法

热门文章

  1. SAP Spartacus 4.0 源代码模式下开启 SSR,为什么会从本地去加载 all.css?
  2. SAP Spartacus SSR模式启用失败的一个原因:SSR rendering exceeded timeout
  3. 巧用Angular项目的get设置Angular class属性访问的别名
  4. SAP Spartacus的User明细如何通过ngrx-store-devtools被解析出来
  5. 在SAP ABAP和Hybris Commerce里启动后台作业
  6. how is native onClick event passed to application handler
  7. 阮一峰react demo代码研究的学习笔记 - how is h1 got parsed - not answer
  8. why always SAP WebContent is added as prefix of url when repository request ser
  9. ERP Configurable product不会被CRM中间件下载
  10. yaas client requestAccessToken