练习29--if语句

一 代码及运行结果

ex29.py

 1 people =30
 2 cats = 13
 3 dogs = 19
 4 
 5 if people < cats:
 6     print("Too many cats! The world is dommed!")
 7 
 8 if people > cats:
 9     print("Not many cats! The world is saved!")
10 
11 if people < dogs:
12     print("The world is drooled on!")
13 
14 if people > dogs:
15     print("The world is dry!")
16 
17 dogs += 5
18 
19 if people >= dogs:
20     print("People are greater than or equal to dogs.")
21 
22 if people <= dogs:
23     print("People are less than or equal to dogs.")
24 
25 if people == dogs:
26     print("People are dogs.")

运行结果:

PS E:3_work4_python2_code_python2_LearnPythonTheHardWay> python ex29.py
Not many cats! The world is saved!
The world is dry!
People are greater than or equal to dogs.

二 一些问题

1. 你认为 if 对它下面的代码起什么作用?
  • 决定下面的语句是否执行
  • if 语句在代码中创建了一个“分支”(branch),有点类似于在一本冒险书中,你选择了哪个答案,就翻到对应的一页,如果你选择了不同的答案,就会去到不同的地方。if 语句就是告诉脚本,如果这个布尔表达式是 True,那就运行它下面的代码,否则的话就跳过。
2. 为什么 if 下面的代码要缩进 4 个空格?
  • if语句和缩进部分是完整的代码块,如果不缩进的话程序不会正常运行
  • 通过一行代码结尾的冒号告诉 Python 你在创建一个新的代码块,然后缩进四个空格告诉Python 这个代码块中都有些什么。这就跟本书前半部分中你学的函数是一样的。
3. 如果没有缩进会发生什么?
  • 报错:
    IndentationError: expected an indented block
原文地址:https://www.cnblogs.com/luoxun/p/13290385.html