Python 基本语句
来源:互联网 发布:端口聚合的作用 编辑:程序博客网 时间:2024/06/09 18:30
Python 基本语句
首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。
1、Python语句特点
(1) if语句中括号()是可选的。(2) 冒号(:)出现在结尾,表示一个语句的结束。
(3) 分号(;)不用出现在结尾。
(4) 大括号不在需要,而是以缩进来表示代码块的开始和结尾。
2、if语句
(1) 一般格式if <state1>: # if语句,以分号(:)结尾<statement1> # 缩进替代大括号elif <state2>: # elif语句,可以有多个<statement2>else: # else语句<statement3>(2) 只包含if语句。
>>> if x > 1:print "True"(3) if和else配合使用。
>>> if x > 1:print "True"else:print "False"(4) 多路选择elif。
>>> if x < -1:print "x < -1"elif x < 0:print "x < 0"elif x < 1:print "x < 1"else:print "x >= 1"
3、while语句
(1) 一般格式。while <state1>: # where语句,以分号(:)结尾<statement1>else: # else语句,循环正常结束调用<statement2>(2) while单独使用。
>>> x = "HelloWorld!">>> while x: # x是否是空列表print x[0],x = x[1:]H e l l o W o r l d !(3) else是循环结束时调用。
>>> L = [1, 2, 3, 4]>>> while L:print L[0],L = L[1:]else: # 循环结束,调用else语句print 61 2 3 4 6
4、for语句
(1) 一般格式。for <target> in <object>: # for语句,以分号(:)结尾<statement1>else: # else语句,循环正常结束调用<statement2>(2) for单独使用。
>>> for x in [1, 2, 3, 4]:print x,1 2 3 4>>> for x in ("hello", "world"):print xhelloworldfor使用元组赋值。
>>> T = [(1, 2), (3, 4), (5, 6)]>>> for (a, b) in T:print a, b>>> for item in T:a, b = itemprint a, b1 23 45 6for对字典操作时,实际是对字典的关键字列表操作。
>>> D = {"a":1, "b":2, "c":3}>>> for item in D:print item, D[item]a 1c 3b 2(3) else是循环结束时调用。
>>> L = [1, 2, 3, 4]>>> for x in L:print x,else:print 61 2 3 4 6
5、break和continue语句用于循环语句中。
break用来跳出循环。>>> x = "HelloWorld!">>> while True:if x: # x是否是空列表print x[0],x = x[1:]else: # x是空列表,跳出循环breakH e l l o W o r l d !continue用来跳到循环的顶端。
>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> for x in L:if x % 2 == 0: # 如果x是偶数,跳过下面语句continueprint x, # 该方法只会打印奇数1 3 5 7 9
6、pass语句
pass是空的占位语句。
0 0
- python 基本语句
- python 基本语句
- Python中的基本语句
- Python基本语句
- Python基本语句
- Python 基本语句
- python基本语句
- python 基本语句
- Learning Python 007 基本语句
- 初识Python、数据类型、基本语句
- Python基础二--基本控制语句
- Python学习【2】基本输入输出语句
- 第3课 Python基本输入输出语句
- python 条件语句的基本用法
- python操作excel的基本语句
- 1.Python入门之基本语句
- Python宝典第三章:Python数据类型与基本语句
- 零基础学python-3.1 python基本规则和语句
- webpack hotreplace取消webstorm的自动保存,修改为手动保存
- linux系统/var/log目录下的信息详解
- 卡特兰数问题
- python笔记 对txt文件的读写
- Service(上)
- Python 基本语句
- 笔记1:ubuntu14.04 caffe环境搭建
- LeetCode-Brainteaser-292. Nim Game
- Android中shape和selector的使用
- DB_NAME、DB_UNIQUE_NAME、SERVICE_NAME和INSTANCE_NAME等的区别
- 交换机trunk模式工作原理
- 从0开始学习 GitHub 系列之「08.如何发现优秀的开源项目」
- 环信java注册实例
- centos7制作本地源