python--------条件,循环语句.
2016-05-05 20:12
639 查看
语句块是在条件为真时执行或者执行多次的一组语句。在代码前放置空格来缩进语句,即可创建语句块。语句块中的每一行都应该缩进同样的量。
在python中,冒号(:)用来标识语句块的开始,块中的每一个语句都是缩进的且缩进量相同。当回退到和已经闭合的块一样的缩进量时,就表示当前块已经结束。
条件语句:
程序都是一条一条语句的执行的。
打印出1-100之间所有的数字:----while循环
在python中,冒号(:)用来标识语句块的开始,块中的每一个语句都是缩进的且缩进量相同。当回退到和已经闭合的块一样的缩进量时,就表示当前块已经结束。
条件语句:
程序都是一条一条语句的执行的。
#!/usr/bin/env python name=raw_input('what is your name: ') if name.endswith('Gumby'): print 'Hello, Gumby' /然后执行一下这个脚本文件: [root@ceshi sbin]# ./1.py what is your name: Gumby Hello, Gumby在这个脚本文件中如果用户输入了“Gumby”作为结尾的名字,那么name.endswith方法就会返回真,使得if进入语句块,打印出问候语。我们可以用else语句增加一种选择:如下
[root@ceshi sbin]# vim 1.py #!/usr/bin/env python name=raw_input('what is your name: ') if name.endswith('Gumby'): print 'Hello, Gumby' else: print 'Hello, stranger' #执行语句即可。 [root@ceshi sbin]# ./1.py what is your name: Gumby Hello, Gumby [root@ceshi sbin]# ./1.py what is your name: john Hello, stranger [root@ceshi sbin]#如果需要检查多个条件,可以使用elif,就是else if的缩写。
[root@ceshi sbin]# vim 1.py #!/usr/bin/env python num = input('Enter a number: ') if num > 0: print 'The number is passive' elif num < 0: print 'The number is negative' else: print 'The number is zero' 执行脚本: [root@ceshi sbin]# ./1.py Enter a number: 5 The number is passive [root@ceshi sbin]# ./1.py Enter a number: -9 The number is negative [root@ceshi sbin]# ./1.py Enter a number: 0 The number is zero循环:
打印出1-100之间所有的数字:----while循环
[root@ceshi sbin]# vim 1.py #!/usr/bin/env python x=1 while x <= 100: print x x+=1 执行语句: [root@ceshi sbin]# ./1.py 1 2 3 4 5 6 ·· 100for循环:
#!/usr/bin/env python words=['this', 'is', 'an', 'ex', 'parrot'] for word in words: print word 执行这个脚本文件: [root@ceshi sbin]# ./1.py this is an ex parrotpython中还有另外一个内嵌的函数如下:
>>> range(10) /类似于分片,只包含下端,不包含上端 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(0,10) /还可以省略下端 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法