您的位置:首页 > 编程语言 > Python开发

Python自学4:Python的程序流程

2013-11-18 16:05 323 查看
# -*- coding:utf-8 -*-
#Python自学4:Python的程序流程

#和大多数编程语言一样,Python也有顺序、分支、循环这三种流程。
#一、分支结构:if
#   语法:if <expr1>:
#            <statement-block>
#         elif <expr2>:
#            <statement-block>
#         elif <expr3>:
#            <statement-block>
#         ...
#         else:
#            <statement-block>

#注意:1、if后面的表达式可以是任何的表达式,除None、""、[]、()、{}以外,其它都是真。
#      2、表达式以冒号(:)分割
#      3、else后面跟表达式之后,也有冒号(:)
#      4、注意缩进
def hanshu(x):
if x>0:
print "%s is positive" % x
elif x==0:
print "%s is zero" % x
elif x < 0:
print "%s is negative" % x
else:
print "%s is not a number" % x

print "hanshu(4)=",hanshu(4)
print "hanshu(0)=",hanshu(0)
print "hanshu(-3)=",hanshu(-3)
print "hanshu(abc)=",hanshu('abc')
#结果:      hanshu(4)= 4 is positive
#None                            没有return时,默认返回None
#hanshu(0)= 0 is zero
#None
#hanshu(-3)= -3 is negative
#None
#hanshu(abc)= abc is positive
#None

#二、循环语句:for、while、break、continue、range()
#for、while、break、continue其它编程语言都有,大家很熟悉,不在多说
#    for x in <sequence>:
#        <statement-block>
#    else:
#        <else-block>

#    注:sequence表示任何string 、tuple 、 dictionary

#    while <expr1>:
#        <block>
#    else:
#        <else-block>

for x in "abcd":
print "%s is one of abcd" % x

for x in [1,2,3,4]:
print "%s is one of [1,2,3,4]" % x

dic = {'one':1,'two':2,'three':3}

for x in dic:
print "dic[",x,"]=",dic[x]

#range([start,]stop[,step]):表示从start开始,stop结束,每步增加step,默认start为0,step为1
print range(10)         #结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print range(0,10,2)     #结果:[0, 2, 4, 6, 8]
print range(10,2)       #结果:[]        若可能产生无限个数,那么是空list,不会产生死循环
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python