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动态类型的学习---引用的理解
- 垃圾邮件过滤器 python简单实现
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- Python,Flex 2和Aptana[js开放工具]
- 国外开发者谈为何放弃PHP而改用Python
- 利用webqq协议使用python登录qq发消息源码参考
- python 判断自定义对象类型
- 让python的Cookie.py模块支持冒号做key的方法
- Python 面向对象 成员的访问约束
- 新手该如何学python怎么学好python?
- Python linecache.getline()读取文件中特定一行的脚本