Python基础知识汇总

  • 一、Python简介
  • 二、 重要的库
  • 三、 安装
  • 四、 基础语法
  • 4.1 编程模式
  • 4.2 标识符
  • 4.3 保留字符
  • 4.3 行和缩进
  • 4.3 多行语句
  • 4.4 Python引号
  • 4.5 Python注释
  • 4.6 转义字符
  • 4.7 日期与时间
  • 4.8 异常处理
  • 五、 变量类型
  • 5.1 标准数据类型
  • 5.2 变量赋值
  • 5.2 数据类型转换
  • 六、 运算符
  • 6.1 算术运算符
  • 6.2 比较运算符
  • 6.3 赋值运算符
  • 6.4 位运算符
  • 6.5 逻辑运算符
  • 6.6 成员运算符
  • 6.7 身份运算符
  • 6.8 运算符优先级
  • 6.9 字符串运算符
  • 6.9.1 字符串格式化
  • 七、 逻辑语句
  • 7.1 条件语句
  • 7.2 循环语句
  • 7.2.1 循环类型
  • 7.2.2 控制语句
  • 八、 函数
  • 8.1 数学函数
  • 8.1.1 数学常量
  • 8.2 随机函数
  • 8.3 自定义函数
  • 8.3.1 参数
  • 8.3.2 变量
  • 8.3.3 匿名函数
  • 8.4 文件读取与输出


一、Python简介

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言;也是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。

二、 重要的库

(1)NumPy(Numerical Python),科学计算的基础包;
(2)Pandas,快速便捷地处理结构化数据的大量数据结构和函数;
(3)Matplotlib,绘制数据图表的库;
(4)SciPy,解决科学数据计算各种标准依据;

三、 安装

四、 基础语法

4.1 编程模式

(1)交互式编程:不需要创建脚本文件,通过Python解释器的交互模式编写代码;
(2)脚本式编程:通过脚本参数调用解释器执行脚本,直到脚本执行完毕,当脚本执行完,解释器不再有效;

4.2 标识符

(1)由字母、数字、下划线组成;
(2)不能以数字开头;
(3)区分大小写;
(4)以下划线开头的标识符是有特殊意义。

4.3 保留字符

字符

说明

字符

说明

字符

说明

And

用于表达式运算,逻辑与操作

exec

用于执行python语句

not

用于表达式运算,逻辑非操作

assert

断言,用于判断变量或条件表达式的值是否为真

finally

用于异常语句,出现异常后,始终要执行finally包含的代码块。与try,except结合使用

or

用于表达式运算,逻辑或操作

break

中断循环语句的执行

for

用于表达式运算,逻辑与操作

pass

空的类,函数,方法的占位符

class

用于定义类

from

用于导入模块,与import结合使用

print

打印语句

continue

继续执行下一次循环

global

定义全局变量

raise

异常抛出操作符

def

用于定义函数或方法

if

条件语句,与else,elif结合使用

return

用于从函数返回计算结果

del

删除变量或者序列的值

import

用于导入模块,与from 结合使用

try

包含可能会出现异常的语句,与except,finally结合使用

elif

条件语句 与if else 结合使用

in

判断变量是否存在序列中

while

循环语句

else

条件语句,与if,elif结合使用,也可以用于异常和循环使用

is

判断变量是否为某个类的实例

with

简化Python的语句

except

捕获异常后的操作代码,与try,finally结合使用

lambda

定义匿名函数

yield

用于从函数依次返回值以下划线开始或者结束的标识符通常有特殊的意义

4.3 行和缩进

(1)Python的代码块不适用大括号{}来控制类,函数以及其他逻辑判断;
(2)用缩进来写模块;
(3)缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,必须严格遵行。

4.3 多行语句

(1)一般以新行作为语句的结束符;
(2)可以使用\将一行的语句分为多行显示

#多行语句
item_one=1
item_two=2
item_three=3
total = item_one + \
        item_two + \
        item_three
print total

4.4 Python引号

接收单引号(’),双引号(’’),三引号(’’’ “”")来表示字符串,保证引号的开始与结束为相同类型。

#引号
word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""
print word
print sentence
print paragraph

4.5 Python注释

(1)单行注释采用#开头
(2)多行注释使用三个单引号(’’’)或三个双引号(""")

#注释
# 第一个注释
print "Hello, Python!";  # 第二个注释
name = "Madisetti" # 这是一个注释

'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

4.6 转义字符

字符

描述

\ (在行尾时)

续行符

\ \

反斜杠符号

\‘

单引号

\’‘

双引号

\a

响铃

\b

退格(Backspace)

\e

转义

\000


\n

换行

\v

纵向制表符

\t

横向制表符

\r

回车

\oyy

八进制数,yy代表的字符,例如:\o12代表换行

\xyy

十六进制数,yy代表字符,例如:\x0a代表换行

\other

其他的字符以普通格式输出

4.7 日期与时间

字符

描述


tm_year

四位数年

例:2019

tm_mon


1-12

tm_mday


1-31

tm_hour

小时

0-23

tm_min

分钟

0-59

tm_sec


0-61(60或61是闰秒)

tm_wday

一周的第几日

0-6(0是周一)

tm_yday

一年的第几日

1-366(儒略历)

tm_isdst

夏令时

-1、0、1,-1是决定是否为夏令时的旗帜

4.8 异常处理

1.try…except…else
2.try…finally…raise

#异常处理
try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"
   fh.close()


try:
   fh = open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"


try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
finally:
   print "Error: can\'t find file or read data"


try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can\'t find file or read data"


def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument

# Call above function here.
temp_convert("xyz");


#异常触发
def functionName( level ):
   if level < 1:
      raise "Invalid level!", level
      # The code below to this would not be executed
      # if we raise the exception

try:
   Business Logic here...
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

#自定义异常
class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args

五、 变量类型

5.1 标准数据类型

(1)Number,数字
1>数字数据类型用于存储数值
2>不可改变的数据类型
3>四种数值类型:int,有符号整型;long,长整型,也可代表八进制和十六进制;float,浮点型;complex,复数。
(2)String,字符串

#字符串
#s="a1a2•••an"(n>=0)
s = 'ilovepython'
print s[1:5]
print s[5:-1]

str = 'Hello World!'
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[2:5] # 输出字符串中第三个至第五个之间的字符串
print str[2:] # 输出从第三个字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出连接的字符串

(3)List,列表

#列表
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 # 打印组合的列表

(4)Tuple,元组

#元组
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print tuple # 输出完整元组
print tuple[0] # 输出元组的第一个元素
print tuple[1:3] # 输出第二个至第三个的元素 
print tuple[2:] # 输出从第三个开始至列表末尾的所有元素
print tinytuple * 2 # 输出元组两次
print tuple + tinytuple # 打印组合的元组

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # 元组中是非法应用
list[2] = 1000 # 列表中是合法应用

(5)Dictionary,字典

#元字典
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() # 输出所有值

5.2 变量赋值

(1)变量不需要声明,变量的赋值操作既是变量声明和定义的过程;
(2)等号(=)用于给变量赋值;
(3)Python允许同时为多个变量赋值。

#变量赋值
counter = 100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "John" # 字符串

print counter
print miles
print name

a = b = c = 1
print a,b,c
a, b, c = 1, 2, "john"
print a,b,c

5.2 数据类型转换

函数

描述

函数

描述

int(x[,base])

将x转换为一个整数

long(x[,base])

将x转换为一个长整数

float(x)

将x转换到一个浮点数

complex(real[,imag])

创建一个复数

str(x)

将x转换为字符串

repr(x)

将x转换为表达式字符串

eval(str)

用来计算在字符串中的有效表达式,并返回一个对象

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)

将一个整数转换为一个八进制字符串

六、 运算符

6.1 算术运算符

运算符

描述

举例

+

两个对象相加

a=10,b=20,a+b输出结果30

-

两个对象相减

a=10,b=20,a-b输出结果-10

*

两个对象相加乘

a=10,b=20,a*b输出结果200

/

两个对象相除

a=10,b=20,a/b输出结果0.5

%

取模,返回除非余数

a=10,b=20,a%b输出结果0

**

幂乘积,返回前面的后面次幂的值

a=10,b=2,a**b输出结果100

//

取整,返回商的整数部分

a=9,b=2,a+b输出结果4.0

#算术运算符
a = 21
b = 10
c = 0

c = a + b
print "Line 1 - Value of c is ", c

c = a - b
print "Line 2 - Value of c is ", c 

c = a * b
print "Line 3 - Value of c is ", c 

c = a / b
print "Line 4 - Value of c is ", c 

c = a % b
print "Line 5 - Value of c is ", c

a = 2
b = 3
c = a**b 
print "Line 6 - Value of c is ", c

a = 10
b = 5
c = a//b 
print "Line 7 - Value of c is ", c

6.2 比较运算符

运算符

描述

举例

==

等于

a=10,b=20,a==b输出结果false

!=

不等于

a=10,b=20,a!=b输出结果true

<>

不等于,同上

a=10,b=20,a<>b输出结果true

<

小于

a=10,b=20,a<b输出结果true

>

大于

a=10,b=20,a>b输出结果true

>=

大于等于

a=10,b=2,a>=b输出结果false

<=

小于等于

a=9,b=2,a<=b输出结果false

#比较运算符
a = 21
b = 10
c = 0

if ( 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"

6.3 赋值运算符

运算符

描述

举例

=

简单赋值

c=a+b,将a+b的运算结果赋值给c

+=

加法赋值

c+=a等效于c=c+a

-=

减法赋值

c-=a等效于c=c-a

*=

乘法赋值

c*=a等效于c=c*a

/=

除法赋值

c/=a等效于c=c/a

%=

取模赋值

c%=a等效于c=c%a

**=

幂乘积赋值

c**=a等效于c=c**a

//=

取整赋值

c//=a等效于c=c//a

#赋值运算符
a = 21
b = 10
c = 0

c = a + b
print "Line 1 - Value of c is ", c

c += a
print "Line 2 - Value of c is ", c 

c *= a
print "Line 3 - Value of c is ", c 

c /= a 
print "Line 4 - Value of c is ", c 

c  = 2
c %= a
print "Line 5 - Value of c is ", c

c **= a
print "Line 6 - Value of c is ", c

c //= a
print "Line 7 - Value of c is ", c

6.4 位运算符

运算符

描述

举例

&

位与,两个相应位都为1,则该位为1,否则为0

a&b输出结果12 ,二进制:00001100

|

位或,只要对应位有一个为1,则结果位为1,否则为0

a|b输出结果61 ,二进制:00111101

^

位异或,两对应位不同时,结果位为1

a^b输出结果49 ,二进制:00110001

~

位取反,每个位取反,1变0,0变1

~a输出结果-61 ,二进制:11000011

<<

左移动,各位左移若干位,高位丢失,低位补0

a<<2输出结果240,二进制:11110000

>>

右移动,各位右移若干位,低位丢失,高位补0

a>>2输出结果15,二进制:00001111

#位运算符
a = 60            # 60 = 0011 1100 
b = 13            # 13 = 0000 1101 
c = 0

c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", c

c = a | b;        # 61 = 0011 1101 
print "Line 2 - Value of c is ", c

c = a ^ b;        # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", c

c = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", c

c = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", c

6.5 逻辑运算符

运算符

描述

举例

and


(a and b)返回true

or


(a or b)返回true

not


(a not b)返回false

#逻辑运算符
a = 10
b = 20

if ( 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 = 0
if ( 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 - Either a is not true or b is  not true or both are not true"
else:
   print "Line 5 - a and b are true"

6.6 成员运算符

运算符

描述

举例

in

指定的序列中找到值返回true,否则false

a in list,返回false

not in

指定序列中没有找到值返回true,否则false

b not in list,返回true

#成员运算符
a = 10
b = 20
list = [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 = 2
if ( 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"

6.7 身份运算符

运算符

描述

举例

is

判断两个标识符是否引用自一个对象

a is b,等效于id(a) is id(b),返回true

is not

指定序列中没有找到值返回true,否则false

a is not b,等效于id(a) is not id(b),返回false

#身份运算符
a = 20
b = 20

if ( 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 = 30
if ( 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"

6.8 运算符优先级

运算符

描述

**


~,+@,-@

取反,一元加号(如+=、++等),一元减号

*,/,%,//

乘,除,取模,取整

+,-

加法,减法

>>,<<

右移,左移

&

位与

^,|

位异或,位或

<=,>=,<,>

比较运算符

< >,!=,==

等于运算符

=,%=,/=,//=,-=,+=,*=,**=

赋值运算符

is,is not

身份运算符

in,not in

成员运算符

not,or,and

逻辑运算符

#运算符优先级
a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d       #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ",  e

e = ((a + b) * c) / d     # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ",  e

e = (a + b) * (c / d);    # (30) * (15/5)
print "Value of (a + b) * (c / d) is ",  e

e = a + (b * c) / d;      #  20 + (150/5)
print "Value of a + (b * c) / d is ",  e

6.9 字符串运算符

运算符

描述

实例

+

字符串连接

a+b输出结果:HelloPython

*

重复输出字符串

a*2输出结果:HelloHello

[]

通过索引获取字符串中字符

a[1]输出结果e

[:]

截取字符串中的一部分

a[1:4]输出结果ell

in

成员运算符,如果字符串中包含给定的字符返回true

H in a输出结果1

not in

成员运算符,如果字符串中不包含给定的字符返回true

M not in a输出结果1

r/R

原始字符串(所有字符串都直接按字面的意思使用,没有转义特殊或不能打印的字符),其除了在字符串的第一个引号前加上字母“r”(大小写皆可)外,与普通字符串有着几乎完全相同的语法

print r’\n’与print \n对比

%

格式字符串

6.9.1 字符串格式化

符号

描述

%c

格式化字符及其ASCII码

%s

格式化字符串

%u

格式化无符号整型

%d

格式化整数

%o

格式化无符号八进制数

%x

格式化无符号十六进制数

%X

格式化无符号十六进制数(大写)

%f

格式化浮点数字,可指定小数点后的精度

%e

用科学计数法格式化浮点数

%E

作用同%e

%g

%f和%e的简写

%G

%F和%E的简写

%p

用十六进制数格式化变量的地址

七、 逻辑语句

7.1 条件语句

通过一条或多条语句的执行结果来决定执行的代码块
if…else…、if…elif…elif…else…

#条件语句
'''
if 判断条件:
    执行语句……
else:
    执行语句……
'''

flag = False
name = 'python'
if name == 'python':         # 判断变量否为'python'
    flag = True              # 条件成立时设置标志为真
    print 'welcome boss'    # 并输出欢迎信息
else:
    print name              # 条件不成立时输出变量名称

'''
if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……
'''

num = 2     
if num == 3:            # 判断num的值
    print 'boss'        
elif num == 2:
    print 'user'
elif num == 1:
    print 'worker'
elif num < 0:           # 值小于零时输出
    print 'error'
else:
    print 'roadman'     # 条件均不成立时输出

num = 9
if num >= 0 and num <= 10:    # 判断值是否在0~10之间
    print 'hello'

num = 10
if num < 0 or num > 10:    # 判断值是否在小于0或大于10
    print 'hello'
else:
	print 'undefine'

num = 8
# 判断值是否在0~5或者10~15之间
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
    print 'hello'
else:
    print 'undefine'

var = 100  
if ( var  == 100 ) : print "变量 var 的值为100" 
print "Good bye!"

7.2 循环语句

该语句允许我们执行一个语句或语句组多次

7.2.1 循环类型

循环类型

描述

while循环

在给定的判断条件为true时执行循环体,否则退出循环体

for循环

重复执行语句

嵌套循环

可以在循环中将while循环和for循环相互嵌套

while…、while…else…

#while语句
'''
while 判断条件:
    执行语句……
'''
count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Good bye!"

#死循环
var = 1
while var == 1 :  # 该条件永远为true,循环将无限执行下去
   num = raw_input("Enter a number  :")
   print "You entered: ", num

print "Good bye!"

#while … else 
count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

#简单语句组
flag = 1
while (flag): print 'Given flag is really true!';flag=0;
print "Good bye!"

for…、for…else…

#for语句
'''
for iterating_var in sequence:
   statements(s)
'''
for letter in 'Python':     # 第一个实例
   print '当前字母 :', letter

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print '当前水果 :', fruit

print "Good bye!"

#序列索引迭代
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print '当前水果 :', fruits[index]

print "Good bye!"

#for...else
for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print '%d 等于 %d * %d' % (num,i,j)
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print num, '是一个质数'

嵌套循环

#嵌套循环
i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " 是素数"
   i = i + 1

print "Good bye!"

7.2.2 控制语句

控制语句

描述

break

在语句块执行过程中终止循环,并且跳出整个循环

continue

在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环

pass

空语句,为了保持程序结构的完整性

# continue 和 break 用法
i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print i         # 输出双数2、4、6、8、10

i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break
        
#break语句
for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print 'Current Letter :', letter
  
var = 10                    # Second Example
while var > 0:              
   print 'Current variable value :', var
   var = var -1
   if var == 5:
      break

print "Good bye!"

#continue语句
for letter in 'Python':     # 第一个实例
   if letter == 'h':
      continue
   print '当前字母 :', letter

var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:
      continue
   print '当前变量值 :', var
print "Good bye!"

#pass语句
# 输出 Python 的每个字母
for letter in 'Python':
   if letter == 'h':
      pass
      print '这是 pass 块'
   print '当前字母 :', letter

print "Good bye!"

八、 函数

8.1 数学函数

函数

描述

abs(x)

返回数字的绝对值,如abs(-10),返回10

ceil(x)

返回数字的上入整数,如math.ceil(4.1)返回5

cmp(x,y)

如x<y则返回-1,x==y则返回0,x>y则返回1

exp(x)

返回e的x次幂

fabs(x)

返回数字的绝对值,如abs(-10),返回10.0

floor(x)

返回数字的下舍整数,如math.floor(4.6)返回4

log(x)、log(x,y)

lnx,如math.log(math.e) 返回1;如math.log(100,10)返回2.0

log10(x)

返回以10为基数的x的对数,如math.log10(100)返回2.0

max(x1,x2,…)

返回给定参数的最大值,参数可以为序列

min(x1,x2,…)

返回给定参数的最小值,参数可以为序列

modf(x)

返回x的整数部分与小数部分,两部分的数字符号与x相同,整数部分以浮点型表示

pow(x,y)

返回x**y运算结果

round(x,[n])

返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数

sqrt(x)

返回数字x的平方根,数字可以为负数,返回类型为实数,如math.sqrt(4)返回2+0j

8.1.1 数学常量

常量

描述

pi

数学常量pi(圆周率,一般以π来表示)

e

数学常量e,即自然常数

8.2 随机函数

函数

描述

choice(x)

从序列元素中随机挑选一个元素,如random.choice(range(10)),从0-9中随机挑选一个整数

randrange(x)

从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1

random(x)

随机生成一个实数,它在[0,1)范围内

seed([x])

改变随机数生成器的种子seed。如不设定seed,Python会自动选择seed

shuffle(lst)

将序列的所有元素随机排序

uniform(x)

随机生成下一个实数,它在[x,y]范围内

8.3 自定义函数

1.函数代码块以def开头,后接函数标识符名称和圆括号()
2.任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数
3.函数的第一行语句可以选择性地使用文档字符串,用于存放函数说明
4.函数内容以冒号开始,并且缩进
5.Return[expression]结束函数,选择性地返回一个值给调用方,不带表达式的return相当于返回None

#自定义函数
'''
def functionname( parameters ):
   "函数_文档字符串"
   function_suite
   return [expression]		
'''

def printme( str ):
   "打印传入的字符串到标准显示设备上"
   print str
   return

#函数调用
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");


# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4]);
   print "函数内取值: ", mylist
   return
 
# 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print "函数外取值: ", mylist

8.3.1 参数

1.必备参数,方法运行传入必备参数

#参数
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme();

2.命名参数,def后的函数命名

def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme( str = "My string");

3.缺省参数,必备参数赋值限定值

def printinfo( name, age ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;
 
#调用printinfo函数
printinfo( age=50, name="miki" );


def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;
 
#调用printinfo函数
printinfo( age=50, name="miki" );
printinfo( name="miki" );

4.不定长参数,必备参数中一个参数符号代表任意个参数

#不定长参数
'''
def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]
'''
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print "输出: "
   print arg1
   for var in vartuple:
      print var
   return;
 
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );

8.3.2 变量

1.全局变量
2.局部变量

#变量的作用范围
total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
   #返回2个参数的和."
   total = arg1 + arg2; # total在这里是局部变量.
   print "函数内是局部变量 : ", total
   return total;
 
#调用sum函数
sum( 10, 20 );
print "函数外是全局变量 : ", total

8.3.3 匿名函数

区别于自定义函数,不使用命名参数实现函数效果

#匿名函数
'''
lambda [arg1 [,arg2,.....argn]]:expression
'''

sum = lambda arg1, arg2: arg1 + arg2;
# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 )
print "相加后的值为 : ", sum( 20, 20 )


#return语句
def sum( arg1, arg2 ):
   # 返回2个参数的和."
   total = arg1 + arg2
   print "函数内 : ", total
   return total;
 
# 调用sum函数
total = sum( 10, 20 );
print "函数外 : ", total

8.4 文件读取与输出

1.打印到屏幕,print
2.读取键盘输入,input、raw_input
3.打开文件,open
4.关闭文件,close
5.写入文件,write
6.读取字符串,read

#键盘输入
str = raw_input("Please enter:");
print "你输入的内容是: ", str

str = input("Please enter:");
print "你输入的内容是: ", str

#打开与关闭文件
# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace


# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
fo.close()

# 打开一个文件
fo = open("foo.txt", "wb")
# 文件写入
fo.write( "www.runoob.com!\nVery good site!\n");
 
# 关闭打开的文件
fo.close()


# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close()


# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
 
# 查找当前位置
position = fo.tell();
print "当前文件位置 : ", position
 
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
# 读取字符串
str = fo.read(10);
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()

import os
 
# 重命名文件test1.txt到test2.txt。
os.rename( "test1.txt", "test2.txt" )

import os
 
# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")