当前位置:
首页 > Python基础教程 >
-
Python中的if、else、elif语句用法简明讲解
这篇文章主要介绍了Python中的if、else、elif语句的用法讲解,条件判断语句是程序中流程控制的基础办法之一,需要的朋友可以参考下
下面我们学习if语句,输入下面的代码,确保能够正确运行。
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
运行结果
root@he-desktop:~/mystuff# python ex29.py
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.
加分练习
通过上面的练习,我们自己猜测一下if语句的作用,用自己的话回答下面的问题。
-
你认为if对它下面的代码做了什么?
判断为True就执行它下面的代码,否则不执行。 -
为什么if下面的代码要缩进4个空格?
为了表示这些代码属于if判断下包括的代码。 -
如果不缩进会发生什么?
会提示一个缩进错误。 -
你可以从第27节中拿一些布尔表达式来做if判断吗?
-
改变people,dogs,cats变量的值,看看会发生什么?
答案:
-
if语句下面的代码是if的一个分支。就像书里的一个章节,你选择了这章就会跳到这里阅读。这个if语句就像是说:“如果布尔判断为True,就执行下面的代码,否则跳过这些代码”。
-
用冒号结束一个语句就是要告诉python,我要开始一个新的代码段了。缩进4个空格就是说,这些代码是包含在这个代码段中的,和函数的使用一样。
-
不缩进会报错,python规定冒号后面语句必须有缩进。
-
可以,而且可以是复杂的语句。
-
修改变量的值后,判断语句就会相应的变True或者False,然后输出不同的语句。
比较我的答案和你自己的答案,确保你能理解代码块这个概念,因为这个对于下面的练习非常重要。
输入下面的代码,运行它:
people = 30
cars = 40
buses = 15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't dicide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
运行结果
root@he-desktop:~/mystuff# python ex30.py
We should take the cars.
Maybe we could take the buses.
Alright, let's just take the buses.
来源:https://www.jb51.net/article/80828.htm
栏目列表
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
开启SQLSERVER数据库缓存依赖优化网站性能
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比