Python入门(二,基础)
来源:互联网 发布:鸟哥笔记 知乎 编辑:程序博客网 时间:2024/05/17 09:29
一,基本语法
Python标识符
在python里,标识符有字母、数字、下划线组成。
在python中,所有标识符可以包括英文、数字以及下划线(_),但不能以数字开头。
python中的标识符是区分大小写的。
以下划线开头的标识符是有特殊意义的。以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;
以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。
Python保留字符
下面的列表显示了在Python中的保留字。这些保留字不能用作常数或变数,或任何其他标识符名称。
所有Python的关键字只包含小写字母。
andexecnotassertfinallyorbreakforpassclassfromprintcontinueglobalraisedefifreturndelimporttryelifinwhileelseiswithexceptlambdayield行和缩进
学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。python最具特色的就是用缩进来写模块。
缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。
多行语句
Python语句中一般以新行作为为语句的结束符。
但是我们可以使用斜杠( \)将一行的语句分为多行显示,如下所示:
total = item_one + \ item_two + \ item_three
语句中包含[], {} 或 () 括号就不需要使用多行连接符。如下实例:
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Python 引号
Python 接收单引号(' ),双引号(" ),三引号(''' """) 来表示字符串,引号的开始与结束必须的相同类型的。
其中三引号可以由多行组成,编写多行文本的快捷语法,常用语文档字符串,在文件的特定地点,被当做注释。
word = 'word'sentence = "This is a sentence."paragraph = """This is a paragraph. It ismade up of multiple lines and sentences."""
Python注释
python中单行注释采用 # 开头。
python没有块注释,所以现在推荐的多行注释也是采用的 #比如:
#!/usr/bin/python# First commentprint "Hello, Python!"; # second comment
输出结果:
Hello, Python!
注释可以在语句或表达式行末:
name = "Madisetti" # This is again comment
多条评论:
# This is a comment.# This is a comment, too.# This is a comment, too.# I said that already.
Python空行
函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。
空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。
记住:空行也是程序代码的一部分。
等待用户输入
下面的程序在按回车键后就会等待用户输入:
#!/usr/bin/pythonraw_input("\n\nPress the enter key to exit.")
以上代码中 ,"\n\n"在结果输出前会输出两个新的空行。一旦用户按下键时,程序将退出。
同一行显示多条语句
Python可以在同一行中使用多条语句,语句之间使用分号(;)分割,以下是一个简单的实例:import sys; x = 'foo'; sys.stdout.write(x + '\n')
多个语句构成代码组
缩进相同的一组语句构成一个代码块,我们称之代码组。
像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。
我们将首行及后面的代码组称为一个子句(clause)。
如下实例:
if expression : suite elif expression : suite else : suite
命令行参数
很多程序可以执行一些操作来查看一些基本信,Python可以使用-h参数查看各参数帮助信息:
$ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc. ]
二,数据类型
变量赋值
Python中的变量不需要声明,变量的赋值操作既是变量声明和定义的过程。
每个变量在内存中创建,都包括变量的标识,名称和数据这些信息。
每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。
等号(=)用来给变量赋值。
等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值。例如:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
以上实例中,100,1000.0和"John"分别赋值给counter,miles,name变量。
执行以上程序会输出如下结果:
1000.0
John
多个变量赋值
Python允许你同时为多个变量赋值。例如:
以上实例,创建一个整型对象,值为1,三个变量被分配到相同的内存空间上。
您也可以为多个对象指定多个变量。例如:
以上实例,两个整型对象1和2的分配给变量a和b,字符串对象"john"分配给变量c。
print a,b,c,d,e,f
1 1 1 2 3 "john"
标准数据类型
在内存中存储的数据可以有多种类型。
例如,person.s年龄作为一个数值存储和他或她的地址是字母数字字符存储。
Python有一些标准类型用于定义操作上,他们和为他们每个人的存储方法可能。
Python有五个标准的数据类型:
- Numbers(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Dictionary(字典)
Python数字
数字数据类型用于存储数值。
他们是不可改变的数据类型,这意味着改变数字数据类型会分配一个新的对象。
当你指定一个值时,Number对象就会被创建:
var2 = 10
您也可以使用del语句删除一些对象引用。
del语句的语法是:
您可以通过使用del语句删除单个或多个对象。例如:
del var_a, var_b
Python支持四种不同的数值类型:
- int(有符号整型)
- long(长整型[也可以代表八进制和十六进制])
- float(浮点型)
- complex(复数)
一些数值类型的实例:
- 长整型也可以使用小写"L",但是还是建议您使用大写"L",避免与数字"1"混淆。Python使用"L"来显示长整型。
- Python还支持复数,复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型
Python字符串
字符串或串(String)是由数字、字母、下划线组成的一串字符。
一般记为 :
它是编程语言中表示文本的数据类型。
python的字串列表有2种取值顺序:
- 从左到右索引默认0开始的,最大范围是字符串长度少1
- 从右到左索引默认-1开始的,最大范围是字符串开头
如果你的实要取得一段子串的话,可以用到变量[头下标:尾下标],就可以截取相应的字符串,其中下标是从0开始算起,可以是正数或负数,下标可以为空表示取到头或尾。
比如:
s[1:5]的结果是love。
当使用以冒号分隔的字符串,python返回一个新的对象,结果包含了以这对偏移标识的连续的内容,左边的开始是包含了下边界。
上面的结果包含了s[1]的值l,而取到的最大范围不包括上边界,就是s[5]的值p。
加号(+)是字符串连接运算符,星号(*)是重复操作。如下实例:
str = 'Hello World!'
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[2:5] # 输出字符串中第三个至第五个之间的字符串
print str[2:] # 输出从第三个字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出连接的字符串
以上实例输出结果:
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python列表
List(列表) 是 Python 中使用最频繁的数据类型。列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(所谓嵌套)。
列表用[ ]标识。是python最通用的复合数据类型。看这段代码就明白。
列表中的值得分割也可以用到变量[头下标:尾下标],就可以截取相应的列表,从左到右索引默认0开始的,从右到左索引默认-1开始,下标可以为空表示取到头或尾。
加号(+)是列表连接运算符,星号(*)是重复操作。如下实例:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个的元素
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表
以上实例输出结果:
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
Python元组
元组是另一个数据类型,类似于List(列表)。
元组用"()"标识。内部元素用逗号隔开。但是元素不能二次赋值,相当于只读列表。
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个的元素
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表
以上实例输出结果:
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # 元组中是非法应用
list[2] = 1000 # 列表中是合法应用
Python元字典
字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。
两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典用"{ }"标识。字典由索引(key)和它对应的值value组成。
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # 输出键为'one' 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值
输出结果为:
Python数据类型转换
有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。
以下几个内置的函数可以执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。
int(x [,base])
将x转换为一个整数
long(x [,base] )
将x转换为一个长整数
float(x)
将x转换到一个浮点数
complex(real [,imag])
创建一个复数
str(x)
将对象 x 转换为字符串
repr(x)
将对象 x 转换为表达式字符串
eval(str)
用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s)
将序列 s 转换为一个元组
list(s)
将序列 s 转换为一个列表
set(s)
转换为可变集合
dict(d)
创建一个字典。d 必须是一个序列 (key,value)元组。
frozenset(s)
转换为不可变集合
chr(x)
将一个整数转换为一个字符
unichr(x)
将一个整数转换为Unicode字符
ord(x)
将一个字符转换为它的整数值
hex(x)
将一个整数转换为一个十六进制字符串
oct(x)
将一个整数转换为一个八进制字符串
三,运算符
Python算术运算符
以下假设变量a为10,变量b为20:
以下实例演示了Python所有算术运算符的操作:
#!/usr/bin/pythona = 21b = 10c = 0c = a + bprint "Line 1 - Value of c is ", cc = a - bprint "Line 2 - Value of c is ", c c = a * bprint "Line 3 - Value of c is ", c c = a / bprint "Line 4 - Value of c is ", c c = a % bprint "Line 5 - Value of c is ", ca = 2b = 3c = a**b print "Line 6 - Value of c is ", ca = 10b = 5c = a//b print "Line 7 - Value of c is ", c
以上实例输出结果:
Line 1 - Value of c is 31Line 2 - Value of c is 11Line 3 - Value of c is 210Line 4 - Value of c is 2Line 5 - Value of c is 1Line 6 - Value of c is 8Line 7 - Value of c is 2
Python比较运算符
以下假设变量a为10,变量b为20:
以下实例演示了Python所有比较运算符的操作:
#!/usr/bin/pythona = 21b = 10c = 0if ( a == b ): print "Line 1 - a is equal to b"else: print "Line 1 - a is not equal to b"if ( a != b ): print "Line 2 - a is not equal to b"else: print "Line 2 - a is equal to b"if ( a <> b ): print "Line 3 - a is not equal to b"else: print "Line 3 - a is equal to b"if ( a < b ): print "Line 4 - a is less than b" else: print "Line 4 - a is not less than b"if ( a > b ): print "Line 5 - a is greater than b"else: print "Line 5 - a is not greater than b"a = 5;b = 20;if ( a <= b ): print "Line 6 - a is either less than or equal to b"else: print "Line 6 - a is neither less than nor equal to b"if ( b >= a ): print "Line 7 - b is either greater than or equal to b"else: print "Line 7 - b is neither greater than nor equal to b"
以上实例输出结果:
Line 1 - a is not equal to bLine 2 - a is not equal to bLine 3 - a is not equal to bLine 4 - a is not less than bLine 5 - a is greater than bLine 6 - a is either less than or equal to bLine 7 - b is either greater than or equal to b
Python赋值运算符
以下假设变量a为10,变量b为20:
以下实例演示了Python所有赋值运算符的操作:
#!/usr/bin/pythona = 21b = 10c = 0c = a + bprint "Line 1 - Value of c is ", cc += aprint "Line 2 - Value of c is ", c c *= aprint "Line 3 - Value of c is ", c c /= a print "Line 4 - Value of c is ", c c = 2c %= aprint "Line 5 - Value of c is ", cc **= aprint "Line 6 - Value of c is ", cc //= aprint "Line 7 - Value of c is ", c
以上实例输出结果:
Line 1 - Value of c is 31Line 2 - Value of c is 52Line 3 - Value of c is 1092Line 4 - Value of c is 52Line 5 - Value of c is 2Line 6 - Value of c is 2097152Line 7 - Value of c is 99864
Python位运算符
按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如下:
以下实例演示了Python所有位运算符的操作:
#!/usr/bin/pythona = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0c = a & b; # 12 = 0000 1100print "Line 1 - Value of c is ", cc = a | b; # 61 = 0011 1101 print "Line 2 - Value of c is ", cc = a ^ b; # 49 = 0011 0001print "Line 3 - Value of c is ", cc = ~a; # -61 = 1100 0011print "Line 4 - Value of c is ", cc = a << 2; # 240 = 1111 0000print "Line 5 - Value of c is ", cc = a >> 2; # 15 = 0000 1111print "Line 6 - Value of c is ", c
以上实例输出结果:
Line 1 - Value of c is 12Line 2 - Value of c is 61Line 3 - Value of c is 49Line 4 - Value of c is -61Line 5 - Value of c is 240Line 6 - Value of c is 15
Python逻辑运算符
Python语言支持逻辑运算符,以下假设变量a为10,变量b为20:
以下实例演示了Python所有逻辑运算符的操作:
#!/usr/bin/pythona = 10b = 20c = 0if ( a and b ): print "Line 1 - a and b are true"else: print "Line 1 - Either a is not true or b is not true"if ( a or b ): print "Line 2 - Either a is true or b is true or both are true"else: print "Line 2 - Neither a is true nor b is true"a = 0if ( a and b ): print "Line 3 - a and b are true"else: print "Line 3 - Either a is not true or b is not true"if ( a or b ): print "Line 4 - Either a is true or b is true or both are true"else: print "Line 4 - Neither a is true nor b is true"if not( a and b ): print "Line 5 - a and b are true"else: print "Line 5 - Either a is not true or b is not true"
以上实例输出结果:
Line 1 - a and b are trueLine 2 - Either a is true or b is true or both are trueLine 3 - Either a is not true or b is not trueLine 4 - Either a is true or b is true or both are trueLine 5 - a and b are true
Python成员运算符
除了以上的一些运算符之外,Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。
以下实例演示了Python所有成员运算符的操作:
#!/usr/bin/pythona = 10b = 20list = [1, 2, 3, 4, 5 ];if ( a in list ): print "Line 1 - a is available in the given list"else: print "Line 1 - a is not available in the given list"if ( b not in list ): print "Line 2 - b is not available in the given list"else: print "Line 2 - b is available in the given list"a = 2if ( a in list ): print "Line 3 - a is available in the given list"else: print "Line 3 - a is not available in the given list"
以上实例输出结果:
Line 1 - a is not available in the given listLine 2 - b is not available in the given listLine 3 - a is available in the given list
Python身份运算符
身份运算符用于比较两个对象的存储单元
以下实例演示了Python所有身份运算符的操作:
#!/usr/bin/pythona = 20b = 20if ( a is b ): print "Line 1 - a and b have same identity"else: print "Line 1 - a and b do not have same identity"if ( id(a) == id(b) ): print "Line 2 - a and b have same identity"else: print "Line 2 - a and b do not have same identity"b = 30if ( a is b ): print "Line 3 - a and b have same identity"else: print "Line 3 - a and b do not have same identity"if ( a is not b ): print "Line 4 - a and b do not have same identity"else: print "Line 4 - a and b have same identity"
以上实例输出结果:
Line 1 - a and b have same identityLine 2 - a and b have same identityLine 3 - a and b do not have same identityLine 4 - a and b do not have same identity
Python运算符优先级
以下表格列出了从最高到最低优先级的所有运算符:
以下实例演示了Python所有运算符优先级的操作:
#!/usr/bin/pythona = 20b = 10c = 15d = 5e = 0e = (a + b) * c / d #( 30 * 15 ) / 5print "Value of (a + b) * c / d is ", ee = ((a + b) * c) / d # (30 * 15 ) / 5print "Value of ((a + b) * c) / d is ", ee = (a + b) * (c / d); # (30) * (15/5)print "Value of (a + b) * (c / d) is ", ee = a + (b * c) / d; # 20 + (150/5)print "Value of a + (b * c) / d is ", e
以上实例输出结果:
Value of (a + b) * c / d is 90Value of ((a + b) * c) / d is 90Value of (a + b) * (c / d) is 90Value of a + (b * c) / d is 50
四:条件语句
Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
可以通过下图来简单了解条件语句的执行过程:
Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
Python 编程中 if 语句用于控制程序的执行,基本形式为:
if 判断条件: 执行语句……else: 执行语句……
其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。
else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句,具体例子如下:
# coding=utf8# 例1:if 基本用法flag = Falsename = 'luren'if name == 'python': # 判断变量否为'python' flag = True # 条件成立时设置标志为真 print 'welcome boss' # 并输出欢迎信息else: print name # 条件不成立时输出变量名称
输出结果为:
>>> luren# 输出结果
if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。
当判断条件为多个值是,可以使用以下形式:
if 判断条件1: 执行语句1……elif 判断条件2: 执行语句2……elif 判断条件3: 执行语句3……else: 执行语句4……
实例如下:
# coding=utf8# 例2:elif用法num = 5 if num == 3: # 判断num的值 print 'boss' elif num == 2: print 'user'elif num == 1: print 'worker'elif num < 0: # 值小于零时输出 print 'error'else: print 'roadman' # 条件均不成立时输出
输出结果为:
>>> roadman# 输出结果
由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。
# coding=utf8# 例3:if语句多个条件num = 9if num >= 0 and num <= 10: # 判断值是否在0~10之间 print 'hello'>>> hello# 输出结果num = 10if num < 0 or num > 10: # 判断值是否在小于0或大于10 print 'hello'else:print 'undefine'>>> undefine# 输出结果num = 8# 判断值是否在0~5或者10~15之间if (num >= 0 and num <= 5) or (num >= 10 and num <= 15): print 'hello'else: print 'undefine'>>> undefine# 输出结果
当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。
简单的语句组
你也可以在同一行的位置上使用if条件判断语句,如下实例:
#!/usr/bin/python var = 100 if ( var == 100 ) : print "Value of expression is 100" print "Good bye!"
以上代码执行输出结果如下:
Value of expression is 100Good bye!
五:循环语句
Python 循环语句
本章节将向大家介绍Python的循环语句,程序在一般情况下是按顺序执行的。
编程语言提供了各种控制结构,允许更复杂的执行路径。
循环语句允许我们执行一个语句或语句组多次,下面是在大多数编程语言中的循环语句的一般形式:
Python提供了for循环和while循环(在Python中没有do..while循环):
循环控制语句
循环控制语句可以更改语句执行的顺序。Python支持以下循环控制语句:
六:While循环语句
- Python入门(二,基础)
- Python入门基础(二)
- Python入门基础(二)
- 【python入门笔记】(二)python基础
- python基础入门(二)
- python基础入门二
- python学习笔记(二)基础入门
- Python入门基础之二
- Python入门(二)中文编码与基础语法
- 《零基础入门学习python》学习过程(二)
- Python入门基础之条件循环语句(二)
- python入门(二)
- python入门(二)
- python入门(二)
- Python 入门(二)
- Python入门(二)
- Python入门(二)
- PYTHON入门(二)
- 杭电2033 结构体的应用,注意大于60时需要进一位的
- android源码编译前期准备
- vlc 插件加载模拟程序
- Spring + mybatis整合实例应用
- 【知识小课堂】4 之 索引
- Python入门(二,基础)
- 鸟哥的Linux私房菜基础学习篇(第二版)第六章课后习题与答案
- Android中获取联系人时的注意事项
- Android 深入理解View
- 套接字编程(VC_Win32)
- 结束,也是起点。
- 使用Director::getInstance()->pause()需谨慎
- Java命令行运行参数说明大全
- clojure从零开始(三)