ex29-30 if,elif and else.

1、if 的作用在于为代码创建了一个所谓的“分支”。if 语句告诉脚本:如果这个布尔表达式为真,就运行接下来的代码。

2、行尾的冒号作用在于告诉python 接下来要创建一个新的代码块,这和创建函数是一个道理。

3、在pyhton 的运行规则里,只要一行一(:)结尾,接下来的内容就应该有缩进。

4、如果python遇到多个elif块都是True,那么只有第一个为True的块会运行。

下边是ex29的代码。

 1 #-*- coding: UTF-8 -*- 
 2 people = 20
 3 cats = 30
 4 dogs = 15
 5 
 6 
 7 
 8 
 9 if people < cats :
10   print "Too many cats ,the world is doomed!"
11   
12 if people > cats:
13     print "Not many cats , the world is saved."
14     
15 if people < dogs:
16     print "The world is drooled on!"
17 
18 if people > dogs:
19     print " The world is dry."
20     
21     
22 dogs +=5
23 
24 if people >= dogs :
25     print"people are greater than or equal to dogs."
26     
27 if people <= dogs :
28     print "people are less than or equal to dogs."
29     
30 if people == dogs:
31     print "people are dogs."
32     
33 #在if 语句中加入布尔值
34 if False or True:
35     print "people are dogs."
36     
37 if False and True:
38     print "people are dogs."

下面是ex30的代码:

 1 #-*- coding: UTF-8 -*-
 2 people = 30
 3 cars = 40
 4 buses = 15
 5 
 6 if cars > people:
 7     print "we should take cars."
 8 elif cars < people:
 9     print "We should not take cars."
10 else:
11     print "We can't decide."
12     
13 if buses > cars:
14     print "That's too many buses."
15 elif buses < cars:
16     print "maybe we should take buses."
17 else:
18     print "We still can't decide."
19     
20     
21 if people > buses:
22     print"Alright,let's just take the buses."
23 else:
24     print "Fine,let's stay home then."
25 
26 #稍微复杂一点的布尔表达式
27 if people > cars and cars <buses:
28     print "YOhooooo"
29 else:
30     print "Fine,let's stop here."

 

posted @ 2017-11-02 21:49  丁头零零  阅读(231)  评论(0编辑  收藏  举报