(python learn) 8 流程控制

if

 1 #!/usr/bin/python
 2 
 3 my_number=28
 4 guess=int( raw_input("please input a number:"))
 5 
 6 if guess==my_number:
 7     print "you got it"
 8 elif guess<my_number:
 9     print "your guess is too small"
10 else:
11     print "your guess is too big"

首先通过 my_number变量来保存28这个数字,

然后用guess 来保存一个从标准输入读取的数字。

在第一个if中通过判断 guess == my_number来看是否相等,要注意后面有冒号,并且if的子句要有缩进

第8行的是elif 可以理解成 else if , 同样注意冒号和缩进

第10行的else 也要有冒号,子句有缩进。

while

#!/usr/bin/python

my_number=28
not_hit=True

while not_hit:
    guess=int( raw_input("please input a number:"))

    if guess==my_number:
        print "you got it"
        not_hit=False
    elif guess<my_number:
        print "your guess is too small"
    else:
        print "your guess is too big"
else:
    print "the loop is over"

要注意的地方有两点

1. while的条件后面有冒号

2. while 可以接一个else

for

1 #!/usr/bin/python
2 
3 for n in range(1,9):
4     print n
5 else:
6     print "loop  finished "

要注意的地方是 for后面有冒号, for可以带一个子句。

原文地址:https://www.cnblogs.com/kramer/p/2965903.html