310 学用Python笔记——控制流

if
while
for
break
continue
(没有switch)


if语句

if语句用来检验一个条件, 如果 条件为真,我们运行一块语句(称为 if-块 ), 否则 我们处理另外一块语句(称为 else-块 )。 else 从句是可选的。
示例:

1
2
if True:
    print 'Yes, it is true'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python
# Filename: if.py
 
number = 23
guess = int(raw_input('Enter an integer : '))
 
if guess == number:
    print 'Congratulations, you guessed it.' # New block starts here
    print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
    print 'No, it is a little higher than that' # Another block
    # You can do whatever you want in a block ...
else:
    print 'No, it is a little lower than that'
    # you must have guess > number to reach here
 
print 'Done'
# This last statement is always executed, after the if statement is executed

在Python中没有switch语句。可以使用if..elif..else语句来完成同样的工作.在某些场合,使用字典会更加快捷,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/python
# Filename: using_dict.py
 
# 'ab' is short for 'a'ddress'b'ook
 
ab = {       'Swaroop'   : 'swaroopch@byteofpython.info',
             'Larry'     : 'larry@wall.org',
             'Matsumoto' : 'matz@ruby-lang.org',
             'Spammer'   : 'spammer@hotmail.com'
     }
 
print "Swaroop's address is %s" % ab['Swaroop']
 
# Adding a key/value pair
ab['Guido'] = 'guido@python.org'
 
# Deleting a key/value pair
del ab['Spammer']
 
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)
 
if 'Guido' in ab: # OR ab.has_key('Guido')
    print "\nGuido's address is %s" % ab['Guido']


while语句

只要在一个条件为真的情况下,while语句允许你重复执行一块语句。while语句是所谓 循环 语句的一个例子。while语句有一个可选的else从句。
示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/python
# Filename: while.py
 
number = 23
running = True
 
while running:
    guess = int(raw_input('Enter an integer : '))
 
    if guess == number:
        print 'Congratulations, you guessed it.'
        running = False # this causes the while loop to stop
    elif guess < number:
        print 'No, it is a little higher than that'
    else:
        print 'No, it is a little lower than that'
else:
    print 'The while loop is over.'
    # Do anything else you want to do here
 
print 'Done'