浅谈Python的控制流
来源:互联网 发布:dekker算法 编辑:程序博客网 时间:2024/06/05 07:55
最早接触Python是听说它被称为最强脚本语言,好奇什么养的东西称得上是“最强”。 其实在国外的教学中Python是排在C之前的,现在正值假期,与一C9院校的哥们谈到这件事,他们在大一就开这门课程,有的教材是《像计算机科学家一样思考Python》。 Python的实际应用很多,像国外的YouTube国内的豆瓣,搜狐邮箱,还有著名的OpenStack(开源云计算平台),此外Python在google,yahoo,甚至是NASA中都广泛应用。想着Python丢的差不多了,算是一起把它系统的过一遍了。
python中有三种控制流语句 if for 和while
if语句
用于验证某个条件,条件为真 运行i f-块 否则运行 else-块
#filename: if.pynumber = 23guess = int(raw_input('Enter an integer: '))if guess == number :print'congratulations,you guess it.'print"(but you do not win any prizes!)"elif guess < number :print 'no ,it is little higher that 'else :print 'no ,it is little lower that'print 'Done'与C的语法规则可以说一模一样 只不过If语句后多了一个: 尽管是一个非常简单的程序,也反映出了python程序中许多值得注意的地方,庆幸的是我学过C,C++ 对于有过同样学习经历的人来说 是尤为简单,自然的。
while语句
#filename: while.pynumber = 23running = Truewhile running:guess = int(raw_input('Enter an integer: '))if guess == number :print'congratulations,you guess it.'elif guess < number :print 'no ,it is little higher that 'else :print 'no ,it is little lower that'print 'Done'使用while 就不用像前面的例子一样每次猜测重复执行。其中的True 和 False是熟悉的布尔类型,可以等效理解为1和0 。在校验重要条件的时候是非常重要的,但并不是真实值1和0
for语句
#filename: for.pyfor i in range(1,5):print ielse:print 'the for loop is over'输出结果:
1
2
3
4
range函数用于生成数列,默认的 range的步长为1 for循环在这个范围内递归 for i in range(1,5)等价于 for i in(1,2,3,4)
我发现很有趣的一点,python中的for循环从根本不同于C C++。如果你想写for (int i = 0;i < 5;++i) 那么在python中写作 for i in range(0,5) python的for循环更加简单,明白,不易出错
break语句
#filename: break.pywhile True:s = raw_input('enter something: ')if s == 'quit':breakprint 'length of the string is',len(s) print 'Done'反复的获取输入 然后打印每次输入的长度 提供了一个特别的终止条件‘quit’
continue语句
#filename: continue.pywhile True:s = raw_input('enter something: ')if s == 'quit':breakif len(s) < 3:print 'input is of sufficient length'
3 0
- 浅谈Python的控制流
- 浅谈Python的选择
- 浅谈python的with
- 浅谈python 的import
- Python的访问控制
- Python的流程控制
- Python的控制结构
- python的控制语句
- 浅谈组态软件的控制功能
- 浅谈TCP(传输控制协议)的可靠性
- 浅谈 Python 的 with 语句
- 浅谈 Python 的 with 语句
- 浅谈 Python 的 with 语句
- 浅谈 Python 的 with 语句
- 浅谈 Python 的 with 语句
- 浅谈 Python 的 with 语句
- 浅谈 Python 的 with 语句
- 浅谈 Python 的 with 语句
- 人文社科中理论、模型的意义--一些质疑
- 【解决】iptables -P INPUT DROP后无法联网
- UVA 11183 Teen Girl Squad 最小树形图
- SQL语句中inner join、left join、right join、full join的区别
- 字符串的操作~
- 浅谈Python的控制流
- js GB2312和unicode互转
- 《MonkeyRunner原理剖析》第九章-MonkeyImage实现原理 - 第三节 - 裸图RawImage
- Android 下拉刷新加载更多
- Managed Metadata Service Application(七)权限管理
- CSV Parser
- SDWebImage和EGOImageview(个人建议SDWebImage更牛)
- 抽屉效果的导航菜单
- wikioi 1313 质因数分解