Learn Python The Hard Way学习(30) - Else和If


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

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

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

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

5. 修改变量的值后,判断语句就会相应的变True或者False,然后输出不同的语句。

比较我的答案和你自己的答案,确保你能理解代码块这个概念,因为这个对于下面的练习非常重要。

输入下面的代码,运行它:
[python] 
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." 


运行结果
www.2cto.com# python ex30.py
We should take the cars.
Maybe we could take the buses.
Alright, let's just take the buses.

加分练习
1. 猜测一下elif和else是做什么的?

2. 改变变量的值,看程序输出有什么不同。

3. 尝试一下复杂的布尔表达式。

4. 给每行都添加注释。
作者:lixiang0522

相关内容

    暂无相关文章

评论关闭