Python中的if、else、elif语句用法简明讲解

作者:lixiang0522 时间:2023-05-18 22:18:59 

下面我们学习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语句的作用,用自己的话回答下面的问题。
1. 你认为if对它下面的代码做了什么?
判断为True就执行它下面的代码,否则不执行。

2. 为什么if下面的代码要缩进4个空格?
为了表示这些代码属于if判断下包括的代码。

3. 如果不缩进会发生什么?
会提示一个缩进错误。

4. 你可以从第27节中拿一些布尔表达式来做if判断吗?

5. 改变people,dogs,cats变量的值,看看会发生什么?

答案:
1. if语句下面的代码是if的一个分支。就像书里的一个章节,你选择了这章就会跳到这里阅读。这个if语句就像是说:“如果布尔判断为True,就执行下面的代码,否则跳过这些代码”。

2. 用冒号结束一个语句就是要告诉python,我要开始一个新的代码段了。缩进4个空格就是说,这些代码是包含在这个代码段中的,和函数的使用一样。

3. 不缩进会报错,python规定冒号后面语句必须有缩进。

4. 可以,而且可以是复杂的语句。

5. 修改变量的值后,判断语句就会相应的变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.
标签:Python,条件
0
投稿

猜你喜欢

  • python assert断言的实例用法

    2023-06-24 22:15:42
  • 使用php数据缓存技术提高执行效率

    2023-05-24 23:14:24
  • Python使用googletrans报错的解决方法

    2021-09-21 01:38:00
  • python实现requests发送/上传多个文件的示例

    2023-07-23 01:42:39
  • Oracle数据库安全策略分析(二)

    2010-07-31 13:04:00
  • Python常问的100个面试问题汇总(下篇)

    2023-09-23 06:30:29
  • 前端如何用post的方式进行eventSource请求

    2024-04-10 16:13:32
  • 利用python打开摄像头及颜色检测方法

    2022-08-06 13:11:29
  • Python 异步等待任务集合

    2022-08-14 17:23:22
  • MySQL命令行中给表添加一个字段(字段名、是否为空、默认值)

    2024-01-16 12:47:36
  • Python发送邮件封装实现过程详解

    2021-06-13 09:19:41
  • vue 动态创建组件的两种方法

    2024-05-09 10:51:27
  • python爬取指定微信公众号文章

    2021-03-29 02:34:39
  • Pandas数据处理加速技巧汇总

    2023-08-12 19:02:36
  • DJango的创建和使用详解(默认数据库sqlite3)

    2024-01-24 20:24:39
  • mac安装pytorch及系统的numpy更新方法

    2023-08-14 19:06:15
  • Python可视化库之HoloViews的使用教程

    2023-11-05 17:09:03
  • python如何寻找主串中所有指定子串下标

    2023-11-27 08:38:41
  • 无阻塞加载脚本分析[全]

    2024-04-17 10:25:35
  • Keras多线程机制与flask多线程冲突的解决方案

    2023-09-12 02:10:51
  • asp之家 网络编程 m.aspxhome.com