Python的关键要素:
Python的关键要素包括:Python中基础数据类型、 对象引用(变量)、常用组合数据类型、 逻辑操作符、控制流语句、算数操作符、Python输入/输出、函数的创建与调用
1、Python中基础数据类型:
数字:int、 long、float、complex、 bool
整型(int):不可变类型
布尔型(bool):Trul,False
浮点型(float):不可变类型:3.1415926
复数(complex):3+6j
字符:str,unicode
字符串:"myname is field",'hello' '''world'''
例1:整型
In [1]: no=2
In [2]: id(no)
Out[2]: 33699744
In [3]: no=3
In [4]: id(no)
Out[4]: 33699720
In [5]: type(no)
Out[5]: int
In [6]: num=3
In [7]: id(num)
Out[7]: 33699720
#Python中一切皆对象,整型时不可变类型,变量引用相同的整型对象,其id相同
In [8]: 1+2
Out[8]: 3
In [9]: print _
3
# print _ 打印最后一个引用的对象,即最后表达式的结果
例2:浮点型
In [10]: no1=3.14
In [11]: type(no1)
Out[11]: float
In [12]: type(no) is type(no1)
Out[12]: False
例3:字符型
In [13]: name="field"
In [14]: print name[0]
f
In [15]: id (name)
Out[15]: 36570192
In [16]: name='jones'
In [17]: id (name)
Out[17]: 43946128
In [18]: type(name)
Out[18]: str
In [20]: name1='jones'
In [21]: id (name)
Out[21]: 43946128
#Python中字符是不可变类型,变量引用相同的不可变对象,其id相同
2、对象引用(变量)
Python将所有数据存为内存对象,Python中变量实际上是指向内存对象的引用。在任何时刻,某个对象引用可以根据需要重新引用一个不同的对象(可以是不同数据类型)。
type()用于返回给定对象的数据类型;
“=”:用于变量名与内存中某对象绑定;
变量命名规则:只能包含字母、数字、下划线,且不能以数字开头;严格区分字母大小写,禁止使用保留字;
命名惯例:
单一下划线开头变量名(_x)不会被from module import *语句导入;
前后有下划线的变量名(__x__)为系统定义变量名,对Python解释器有特殊意义;
以两个下划线开头且结尾无下划线的变量名(__x)为本地变量;
交互模式下,变量名“_”表示最后表达式的结果;
注意:变量名没有类型,对象才有
In [22]: name='fieldyang'
In [23]: print _
True
3、python常用组合数据类型
序列类型:
列表:(list),可变类型,使用[]创建,如:['My','name','is','Field']
元组:(tuple),不可变类型,使用()创建,如:("one","two")
字符串也属于序列类型
注意:列表和元组均不真正存储数据,而是存放对象应用
集合类型:
集合:集合(set),frozenset
映射类型:
字典:(dict),可变对象,如:{'a':11, 'c': 33, 'b': 22}
组合类型:组合类型也是对象,因此可以嵌套,如:['hello','world',[1,2,3]]
注意:数据类型均有其长度,可使用len()函数测量:len(name)
文件类型:file
其它类型:类类型, None
其它文件类工具:pipes,fifos, sockets
例1:
In [23]:l1=["My","name","is","Field"]
In [24]: print l1
['My', 'name', 'is', 'Field']
例2:使用索引运算符“list[i][j]”做列表索引引用
In [25]: l1[0]
Out[25]: 'My'
In [26]: l1[0][0]
Out[26]: 'M'
In [27]: l1[3]
Out[27]: 'Field'
In [28]: id(l1)
Out[28]: 40583824
In [29]:l1[3]="Ling"
In [30]: id(l1)
Out[30]: 40583824
#列表是可变类型,改变列表内容,其id不会改变
例3:使用列表切片运算符“list[i:j]”及列表扩展切片符“list[i:j:stride]”做切片引用
In [31]: print l1
['My', 'name', 'is', 'Ling']
In [32]: name='FieldYang'
In [33]: name[0]
Out[33]: 'F'
In [34]: name[0:1]
Out[34]: 'F'
In [35]: name[0:3]
Out[35]: 'Fie'
In [36]: name[6:]
Out[36]: 'ang'
In [37]: name[0:8:2]
Out[37]: 'Feda'
In [38]: len(name)
Out[38]: 9
例4:字典
In [39]: d1={'a':11,'b':22,'c':33}
In [40]: print d1
{'a': 11, 'c': 33, 'b': 22}
4、逻辑操作符:
身份操作符:is,后面可以接None:x is y, x not is y
例1:
In [61]: name
Out[61]: 'FieldYang'
In [62]: name1 = 'FieldYang'
In [63]: name1
Out[63]: 'FieldYang'
In [64]: name is name1
Out[64]: True
In [66]: name1 = 'Field'
In [67]: name1 is name1
Out[67]: False
In [68]: type(name) is type(name1)
Out[68]: True
成员操作符:x in y, x not in y
例2:
In [75]: print l1
['My', 'name', 'is', 'Ling']
In [76]: print name
FieldYang
In [77]: name not in l1
Out[77]: True
In [78]: 'name' in l1
Out[78]: True
比较操作符:x < y, x > y,, x <= y, x >= y, x == y, x != y
例3:
In [81]: num=1
In [82]: num1=1
In [83]: num==num1
Out[83]: True
In [84]: num1=2
In [85]: num==num1
Out[85]: False
In [86]: num>num1
Out[86]: False
In [87]: num<num1
Out[87]: True
In [88]: num!=num1
Out[88]: True
In [89]: num<=num1
Out[89]: True
逻辑运算符:and,or,not
5、控制流语句
if/elif/else:条件判断
for/else:序列迭代
while/else:普通循环
pass:占位符
break:跳出最内层的循环
continue:跳到所处的最近层循环的开始出
return:返回,默认none
raise:触发异常
try/except/finally:捕捉异常
条件测试:
if 条件测试表达式
Python中的真假:
1)、任何非0数字和非空对象都为真;
2)、数字0、空对象和特殊对象None均为假;
3)、比较和相等测试会递归地应用于数据结构中;
4)、返回值为True或False;
组合条件测试:
Xand Y: 与运算
Xor Y: 或运算
notX: 非运算
A= X if Y else Z
ifY:
A= X
Else:
A= Z
expression1if boolean_expression else expression2
while语句:
whilebool_expression:
while_suite
else:
else_suite
可用参数:
break: 跳出最内层的循环;
continue:跳到所处的最近层循环的开始处;
pass:点位语句
else代码块:循环正常终止才会执行;如果循环终止是由break跳出导致的,则else不会执行;
6、算数操作符:
一元运算:-x, +x,~x:
幂运算:x ** y
增强赋值: +=, -=,*=, /=, //=, %=,
7、Python输入/输出
输出:
Python3:print()函数;
Python2:print语句
输入:
input()
raw_input()
格式化输出:
print "String %format1 %format2 ... " %(value1,value2,...)
d,i:十进制整数或长整数;
u:无符号整数或长整数;
o:八进制整数或长整数;
x:十六进制整数或长整数;
X:十六进制整数(大写字母);
F:浮点数,如[-]m.dddddd;
E:浮点数,如[-]m.dddddde+-xx;
E:浮点数,如[-]m.ddddddE+-xx;
g,G:指数小于-4或更高精度时使用%e或%E,否则使用%f;
s:字符串或任意对象,格式化代码使用str()生成字符串;
r:同repr()生成的字符串;c:单个字符;%字面量%;
%号后面可以使用的修饰符:
%[(name)][flags][width][.precision]typecode
[(name)]:位于括号中的一个属于后面的字典的键名,用于选出一个具体项目
[flags]:标志(可使用一个或多个)
-:左对齐,默认为右对齐
+:添加数字符号,正数会带上+号
0:使用0填充
[width]:指定最小宽度的数字
[.precision]:小数点,用于按照精度分割字段的宽度
typecode:数字,指定要答应的字符串中的最大字符个数,浮点数中小数点之后的位数,或整数的最小位数;
例1:print输出
In [94]: a=22
In [95]: b=44
In [96]: print a,b
22 44
In [97]: print a,b,
22 44
例2:读标准输入
In [91]: raw_input("please input anumber: ")
please input a number: 88
Out[91]: '88'
In [92]: num=raw_input("please input anumber: ")
please input a number: 88
In [93]: print num
88
例3:格式化输出浮点型、整型、字符型
In [98]: num=8.8
In [99]: print "The num is %f" %num
The num is 8.800000
In [100]: print "The num is %d" %num
The num is 8
In [101]: num1=6.66
In [102]: print "The nums are %d and%f" % (num,num1)
The nums are 8 and 6.660000
In [103]: print "The nums are %d and%f" % (num,5.2)
The nums are 8 and 5.200000
In [104]: print "The nums are %e and%f" % (num,5.2)
The nums are 8.800000e+00 and 5.200000
In [105]: name="FieldYang"
In [106]: print "My name is %s."% name
My name is FieldYang.
In [107]: print "The num is %s."% num
The num is 8.8.
In [120]: print "The nums are %+e and%f" % (num,5.2)
The nums are +8.800000e+00 and 5.200000
In [121]: print "The nums are %+e and%f" % (num,-5.2)
The nums are +8.800000e+00 and -5.200000
In [122]: print "The nums are %+e and%+f" % (num,-5.2)
The nums are +8.800000e+00 and -5.200000
In [123]: print "The nums are %f and%f" % (num,-5.2)
The nums are 8.800000 and -5.200000
例4:格式化输出使用修饰符
In [124]: print "The nums are %+20fand %f" % (num,-5.2)
The nums are +8.800000 and -5.200000
In [125]: print "The nums are %+20.10fand %f" % (num,-5.2)
The nums are +8.8000000000 and -5.200000
In [126]: print "The nums are %-20.10fand %f" % (num,-5.2)
The nums are 8.8000000000 and -5.200000
In [127]: print "The nums are %-20.15fand %f" % (num,-5.2)
The nums are 8.800000000000001 and -5.200000
例5:使用字典演示格式化输出
In [137]: d1={'a':11,'b':22,'c':33}
In [138]: print d1
{'a': 11, 'c': 33, 'b': 22}
In [139]: print "The a is %(a)10.3f, bis %(b)-10d,c is %(c)5.3f" % d1
The a is 11.000, b is 22 ,c is33.000
In [140]: print "The a is %(a)s, b is%(b)d,c is %(c)5.3f" % d1
The a is 11, b is 22,c is 33.000
8、函数的创建与调用
deffunctionName(arguments):
suite
函数可以参数化,通过传递不同的参数来调用,每个函数都有返回值,默认为None,也可以使用“return value”明确定义返回值。
def语句会创建一个函数对象,并同时创建一个指向函数的对象引用,函数也是对象,可以存储在组合数据类型中,也可以作为参数传递给其它函数;
说明:calleble()可用于测试函数是否可调用
Python标准库中有很多内置模块,这些模块拥有大量内置函数;Python模块使用import语句进行导入,后跟模块名称(不能带上.py后缀),导入一个模块后,可以访问其内部包含的任意函数、类、变量
例1:构建printName打印出赋值的名字
In [1]: def printName(name):
....: print name
....:
In [2]: printName('JONES')
JONES
In [3]: test='kin'
In [4]: printName(test)
kin
In [5]: name=printName('field')
Field
例2:使用callable()测试函数是否可调用
In [6]: callable(name)
Out[6]: False
In [7]: callable(printName)
Out[7]: True
例3:使用import导入模块并测试模块内函数方法的使用
In [8]: import random
In [9]: random.
random.BPF random.WichmannHill random.getstate random.sample
random.LOG4 random.betavariate random.jumpahead random.seed
random.NV_MAGICCONST random.choice random.lognormvariate random.setstate
random.RECIP_BPF random.division random.normalvariate random.shuffle
random.Random random.expovariate random.paretovariate random.triangular
random.SG_MAGICCONST random.gammavariate random.randint random.uniform
random.SystemRandom random.gauss random.random random.vonmisesvariate
random.TWOPI random.getrandbits random.randrange random.weibullvariate
In [9]: random.random()
Out[9]: 0.4189901841264161
In [10]: random.random()
Out[10]: 0.9359719349997645
In [11]: students = ['x','y','z']
In [12]: random.choice(students)
Out[12]: 'x'
In [13]: random.choice(students)
Out[13]: 'x'
In [14]: random.choice(students)
Out[14]: 'z'
In [15]: random.choice(students)
Out[15]: 'x'
In [16]: random.choice(students)
Out[16]: 'x'
In [17]: random.choice(students)
Out[17]: 'x'
In [18]: random.choice(students)
Out[18]: 'y'