您的位置:首页 > 编程语言 > Python开发

python基础知识总结

2017-09-18 20:54 531 查看

一、变量本质

1. python中的变量不需要先定义,再使用,可以直接使用,还有重新使用用以存储不同类型的值。 
2. 变量命名遵循C命名风格。

3. 大小写敏感。

4. 变量引用计数。

5. del语句可以直接释放资源,变量名删除,引用计数减1。

6. 变量内存自动管理回收,垃圾收集。

7. 指定编码在文件开头加入 # ­­ coding: UTF­8 ­­ 或者 #coding=utf­8。

>>> a=12;

>>> id(a)

28213328

>>> b=12

>>> c=12

>>> id(b)

28213328

>>> id(c)

28213328

>>> c=99

>>> id(c)

28215224 //前面a、b、c三个变量指向内存同一个地方,当c改变值时指向内存另一个地方,通过del可以删除变量

>>> del a

>>> del(c)

>>> print c

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'c' is not defined

>>> print a

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'a' is not defined

>>> type(b)

<type 'int'>

二、函数

1、简单函数

1. def定义函数的关键字

2. x和y为形参,不需要类型修饰

3. 函数定义行需跟':'

4. 函数体整体缩进

5. 函数可以拥有返回值,若无返回值,返回None,相当于C中的NULL

>>> def add(x,y):

...     z=x+y;

...     return z;

... 

>>> c=add(2,4)

>>> c

6

 

2、输入输出函数

(1)原生输入函数raw_input,红色部分是需要输入的部分。raw_input是从控制台获取,类型全部是字符串;而input是读取的需要是一个合法的Python表达式,对于字符串需要用引号括起来,否则会出错,整型不需要。

>>> file=open('test.txt','w')

>>> print >> file, 'hello'

>>> file.close()

>>> raw_input_1=raw_input("raw_input:")

raw_input:need we input something

>>> raw_input_1

'need we input something'

>>> input_1=input("Input:")

Input:hello

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "<string>", line 1, in <module>

NameError: name 'hello' is not defined

>>> input_1=input("Input:")

Input:"hello"

>>> input_1

'hello'

>>> type(input_1)

<type 'str'>

>>> raw_input_1=raw_input("raw_input:")

raw_input:123

>>> type(raw_input_1)

<type 'str'>

>>> input_1=input("input:")

input:123

>>> type(input_1)

<type 'int'>

(2)输出函数

>>> print '%s %d' %('hello', 2)

hello 2

>>> print b*8 //输出8个b

hellohellohellohellohellohellohellohello

>>> print r'hello\n' //输出原生字符串,字符串直接按照字面的意思来使用

hello\n

(3)重定向



三、局部变量和全局变量

跟C语言一样
需要注意的是函数内部修改全局变量时需要用global声明一下

>>> a=2

>>> def fun():

...     print a

...     global a

...     a=4

...     print a

... 

<stdin>:3: SyntaxWarning: name 'a' is used prior to global declaration

>>> def fun():

...     global a

...     print a

...     a=5

...     print a

... 

>>> fun()

2

5

>>> def fun1():

...     print a //全局变量可以直接引用

... 

>>> fun1()

5

四、特殊变量

_xxx from module import *无法导入 

__xxx__ 系统定义的变量

__xxx 类的本地变量 

五、表达式

1、算术表达式
a ** b:a的b次幂
a / b:浮点数保留小数,整型不保留小数
a // b:向下取整

>>> 5 ** 2

25

>>> 5 / 2

2

>>> 5 // 2

2

>>> 5.0 / 2

2.5

>>> 5.0 // 2.0

2.0

2、逻辑表达式

not a 逻辑非

a and b

a or b

a is b a和b是同一个对象

a is not b a和b不是同一个对象

>>> a=1

>>> b=1

>>> a and b

1

>>> a or b

1

>>> a is b

True

>>> a is not b

False

>>> id(a)

28213592

>>> id(b)

28213592

>>> not b

False

>>> b

1

>>> b=0

>>> not b

True

>>> a and b

0

>>> a is b

False

关系表达式、位运算与C语言一致

六、循环语句

1、在 python 中,for ... else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过

break 跳出而中断的)的情况下执行,while ... else 也是一样。
冒号千万不要丢。

>>> for letter in 'hello':

...     print letter

... else:

...     print 'end'

... 

h

e

l

l

o

end

>>> 

2、break、continue与C语言一致

七、list列表\元组

1、列表和元组二者均能保存任意类型的python对象,索引访问元素从开始 列表元素用[]包括,元素个数,值都可以改变 元组元素用()包括.
Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

>>> alist=[1,2,3,4,5]

>>> alist

[1, 2, 3, 4, 5]

>>> alist[1]

2

>>> alist[1:]

[2, 3, 4, 5]

>>> alist[:2]

[1, 2]

>>> alist[1]=9

>>> alist

[1, 9, 3, 4, 5]

>>> del alist[1]

>>> alist

[1, 3, 4, 5]

>>> alist[1]

3

>>> tup1=(1,2,3,4)

>>> tup1

(1, 2, 3, 4)

>>> tup2=('math','china')

>>> tup3=tup1+tup2 //连接

>>> tup3

(1, 2, 3, 4, 'math', 'china')

>>> tup2

('math', 'china')

>>> tup3[1:4]

(2, 3, 4)

>>> tup3[1]=4 //不支持修改

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

>>> del tup1

>>> tup3

(1, 2, 3, 4, 'math', 'china')

>>> for a in tup2:

...     print a

... 

math

china

>>> 'math' in tup2

True

>>> len(tup2) //求长度

2

>>> s='helloworld'

>>> tuple(s) //字符串转元组

('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')

>>> tup=('math','china')

>>> a=''.join(tup) //元组元素连接成字符串

>>> a

'mathchina'

>>> str(tup)

"('math', 'china')"

>>> 

Python包含以下函数:

cmp(list1, list2) 比较两个列表的元素

len(list) 列表元素个数

max(list)
返回列表元素最大值 

min(list)
返回列表元素最小值

list(seq)
将元组转换为列表

方法:

list.append(obj) 在列表末尾添加新的对象

list.count(obj) 统计某个元素在列表中出现的次数

list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值

list.index(obj) 从列表中找出某个值第一个匹配项的索引位置

list.insert(index,obj) 将对象插入列表

list.pop(obj=list[-1]) 移动列表中的一个元素(默认是最后一个),并且返回该元素的值

list.remove(obj) 移除列表中某个值得第一个匹配项

list.reverse() 反向列表中元素

list.sort([func]) 对原列表进行排序

>>> list=[1,2,3]

>>> list2=[2,3,5]

>>> list+list2

[1, 2, 3, 2, 3, 5]

>>> list.extend(list2)

>>> list

[1, 2, 3, 2, 3, 5]

>>> list.count(2)

2

>>> list.index(5)

5

>>> list.insert(1,33)

>>> list

[1, 33, 2, 3, 2, 3, 5]

>>> list.pop()

5

>>> list

[1, 33, 2, 3, 2, 3]

>>> list.pop(2) //移除索引为2的元素,默认是移除最后一个

2

>>> list

[1, 33, 3, 2, 3]

>>> list.remove(3)

>>> list

[1, 33, 2, 3]

>>> list.reverse()

>>> list

[3, 2, 33, 1]

>>> list.sort()

>>> list

[1, 2, 3, 33]

>>> 

八、字典

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

>>> dict={'jack':24,'john':33}

>>> dict['jack']

24

>>> dict2={1:24,2:33}

>>> dict2={1:24,1:33} //键必须唯一,后面会把前面覆盖掉

>>> dict2

{1: 33}

>>> dict

{'john': 33, 'jack': 24}

>>> len(dict2)

1

>>> dict

{'john': 33, 'jack': 24}

>>> dict.keys()

['john', 'jack']

>>> dict.values()

[33, 24]

>>> del dict['john'] //删除某个键值对

>>> dict

{'jack': 24}

>>> dict.clear() //清楚字典所有元素

>>> dict

{}

>>> del dict //删除字典

>>> dict

<type 'dict'>

>>> 

九、字符串函数

>>> mystr='hello boy, I am iron man'

>>> s='hello'

>>> start=0

>>> end=len(mystr)

>>> mystr.find(s,start,end) //找字符串s的起始索引位置,找不到返回-1

0

>>> mystr.find('hhh',start,end)

-1

>>> mystr.index(s,start,end)
//找字符串s的起始索引位置,找不到返回错误

0

>>> mystr.index('hhh',start,end)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: substring not found

>>> mystr.count(s,start,end)
//找字符串s出现的次数

1

>>> count=1

>>> mystr.replace(s,'hey',count)
//替换字符串s,替换个数为count

'hey boy, I am iron man'

>>> mystr

'hello boy, I am iron man' //原来字符串没变,需要赋值mystr=mystr.replace(s,'hey',count)

>>> mystr.split(' ',2) //根据空格切割2次,即切成3份

['hello', 'boy,', 'I am iron man']

>>> mystr.capitalize() //首字符大写

'Hello boy, i am iron man'

>>> mystr.center(33) //字符串居中,空余两边补空格

'     hello boy, I am iron man    '

>>> mystr.endswith('man') //是否已‘man’结尾

True

>>> mystr.startswith('hell')

True

>>> mystr.expandtabs() //替换tab键

'hello boy, I am iron man'

>>> s2='hello boy'

>>> s2.isalnum()

False

>>> s2='hello boy3'

>>> s2.isalnum()

False

>>> s2='helloboy3'

>>> s2.isalnum() //至少有一个数字,其他全部是数字或者字符,空格不行

True

>>> s2.isalpha()

False

>>> s2='helloboy' //全部是字符,空格不行

>>> s2.isalpha()

True

>>> s2='hello boy'

>>> s2.isalpha()

False

>>> s3='34555' //全部是数字

>>> s3.isdigit()

True

>>> s4=' '

>>> s4.isspace() //全部是空格

True

>>> s4=' 44'

>>> s4.isspace()

False

>>> s5='Hello World'

>>> s5.istitle() //是否是标题化,即每个单词首字母是大写

True

>>> s5='Hello World boy'

>>> s5.istitle()

False

>>> s6='HELLO BOY'

>>> s6.isupper() //可以区分大小写的字符是否全部是大写字符

True

>>> s6='HELLO Boy'

>>> s6.isupper()

False

>>> s6.lower() //转换为小写字符

'hello boy'

>>> s6.join(' hey')

' HELLO BoyhHELLO BoyeHELLO Boyy'

>>> s6

'HELLO Boy'

>>> s6.join('hey') //hey每个字符穿插在s6中间

'hHELLO BoyeHELLO Boyy'

>>> s7=' hello boy'

>>> s7.ljust(22) //左对齐,右补空格

' hello boy            '

>>> s7.rjust(22)
//右对齐,左补空格

'             hello boy'

>>> s7.lstrip() //去除左边空格

'hello boy'

>>> s7=' hello boy '

>>> s7.rstrip()
//去除右边空格

' hello boy'

>>> mystr

'hello boy, I am iron man'

>>> mystr.rfind('hell', 0, len(mystr))
//从右边开始查找

0

>>> mystr.rindex('man', 0, len(mystr))

21

>>> mystr.partition('I') //以字符串S分割字符串

('hello boy, ', 'I', ' am iron man')

>>> mystr.rpartition('I') //从右边开始分割

('hello boy, ', 'I', ' am iron man')

>>> mystr.splitlines() //按行分割

['hello boy, I am iron man']

>>> s7

' hello boy '

>>> s7.zfill(20) //右对齐,左边补0

'000000000 hello boy '

十、时间和日期

>>> import time

>>> ticks=time.time() //从1970纪元后经过的浮点秒数

>>> ticks

1505814398.984294

>>> print time.localtime(ticks)

time.struct_time(tm_year=2017, tm_mon=9, tm_mday=19, tm_hour=17, tm_min=46, tm_sec=38, tm_wday=1, tm_yday=262, tm_isdst=0)

>>> print time.asctime(time.localtime(ticks))
//将时间转为ASCII字符串

Tue Sep 19 17:46:38 2017

>>> import calendar

>>> print calendar.month(2017,10)

    October 2017

Mo Tu We Th Fr Sa Su

                   1

 2  3  4  5  6  7  8

 9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

>>> print time.clock() //Python time clock() 函数以浮点数计算的秒数返回当前的CPU时间。在不同系统上用法不同

0.069357

>>> print time.clock()

0.06992

>>> calendar.setfirstweekday(6)

>>> print calendar.month(2017,10)

    October 2017

Su Mo Tu We Th Fr Sa

 1  2  3  4  5  6  7

 8  9 10 11 12 13 14

15 16 17 18 19 20 21

22 23 24 25 26 27 28

29 30 31

>>> def caltime():

...     time0=time.time()

...     time.sleep(2.4)

...     print time.time()-time0

... 

>>> caltime()

2.40359592438

>>> 

十一、高级函数

>>> #coding=utf-8

... def printinfo(name, sex='male'):
//缺省参数

...     print name,sex

...     return

... 

>>> printinfo('jack')

jack male

>>> printinfo('jack', 'female')

jack female

>>> def printinfo(name, *arg):
//变长参数

...     print name

...     for var in arg:

...             print var

...     return

... 

>>> printinfo('jack')

jack

>>> printinfo('jack', 'male', 24, 180)

jack

male

24

180

>>> sum=lambda arg1,arg2:arg1+arg2
//匿名函数

>>> print sum(19,3)

22

>>> 


其他教程见连接:http://www.runoob.com/python/python-tutorial.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python