python基础教程笔记1

python基础教程

1.基础

1/2==0
1.0/2==0.5
1.0//2==0.0
2**3==8
cmath.sqrt(-1)==1j
repr("hello")=="'hello'"
str("hello")=="hello"

长字符串

'''this is a 
long string.'''
#一行中最后一个字符是反斜线则换行符本身被转义
"hello,\
world!"
>>>1+2+ \
	3
6
>>>print \
	'hello world'
hello world

原始字符串以r开头

>>>print 'C:\\nowhere'
C:\nowhere
>>>print r'C:\nowhere'
C:\nowhere
>>>print r'Let\'s'
>>>print r"illegal\"
SyntaxError
>>>print r'C:\Program'+'\\' 
C:\Program\
>>>u'hello world'   #unicode

2.列表和元组

list列表

>>>"hello"[-1]
'0'
>>>fourth=raw_input('year:')[3]
year:2005
>>>fourth
'5'

#分片
>>>numbers=[1,2,3,4,5,6,7,8,9,10]
>>>numbers[0:3]
[1,2,3]
>>>numbers[-3:-1]
[8,9]
>>>numbers[-3:0]
[]
>>>numbers[-3:]
[8,9,10]
>>>numbers[:3]
[1,2,3]
>>>numbers[:]
[1,2,3,4,5,6,7,8,9,10]   #可用于复制整个序列
>>>numbers[8:3:-1]
[9,8,7,6,5]
>>>numbers[::-2]
[10,8,6,4,2]
>>>numbers[5::-2]
[6,4,2]
>>>numbers[:5:-2]
[10,8]

#序列运算
>>>[1]+[2]
[1,2]
>>>'python'*2
'pythonpython'
>>> s=[None]*2 # N 大写
>>> s
[None, None]
>>>None in s
True
>>>#函数 len, max, min
>>>s=list('hello')
['h','e','l','l','o']
>>>del s[1]
>>>s
['h','l','l','o']
>>>s[1:1]=list('e')
>>>s
['h','e','l','l','o']

#列表方法
>>>s=[1,2,3]
>>>s.append(4)
>>>b=[4,5,6]
>>>s.extend(b)
>>># s.count(4)  s.index()  s.insert(位置,对象)  s.remove() 
>>># s.pop()  唯一一个既修改列表又返回元素值的列表方法  
>>>#s.reverse() 
>>>x=[3,2,1]
>>>y=x[:]
>>>y.sort()  #参数有cmp,key,reverse

元组

>>>1,2,3
(1,2,3)
>>> 1,
(1,)
>>> 2*(1+2)
6
>>> 2*(1+2,)
(3, 3)
>>> x=1,2,3
>>> x[1]
2
>>> x[0:2]
(1, 2)

3.字符串

>>>'%s plus %s equals %s' % (1,1,2)
'1 plus 1 equals 2'
>>>#  -:左对齐
>>>#  +:加上正负号
>>>#  0:0填充
>>>#  %e:科学计数法  
>>>#  %g:指数大于-4或小于精度值则同e,其它情况同f
>>>#  %c:单字符
>>>#  %r:repr
>>>#  %u:无符号十进制
>>> '%10f' % math.pi
'  3.141593'
>>> '%10.2f' % math.pi
'      3.14'
>>> '%.2f' % math.pi
'3.14'
>>> '%5s' % 'Guido van Rossum'
'Guido van Rossum'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
>>> print ('% 5d' % 10)+'\n'+('%+5d' % -10)
   10
  -10

字符串方法

>>># -------------------------find
>>> "abcde".find('a')
0
>>> "abcde".find('b')
1
>>> "abcde".find('f')
-1
>>> "abcde".find('abc')
0
>>> "abcde".find('bcd')
1
>>> #---------------------------join
>>> '+'.join([1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> '+'.join(['1','2','3'])
'1+2+3'
>>> #----------------------------split
>>> '1+2+3'.split('+')
['1', '2', '3']
>>>#------------------------------lower
>>> 'ABC'.lower()
'abc'
>>>#-------------------------------replace
>>> 'this is a test'.replace('is','eez')
'theez eez a test'
>>>#-------------------------------strip
>>> '      internal whitespace is kept      '.strip()
'internal whitespace is kept'
>>>#--------------------------------translate  只处理单个字符,可同时进行多个替换
>>>from string import translate
>>> table=maketrans('cs','kz')
>>> len(table)
256
>>> maketrans('','')[97:123]
'abcdefghijklmnopqrstuvwxyz'
>>> 'this is a test'.translate(table,'')  #第二个参数指定需要删除的字符
'thiz iz a tezt'

4.字典

电话号码应保存为字符串,否则0开头会存为八进制。

>>> items=[('name','Gumby'),('age',42)]
>>> d=dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>># or
>>> d=dict(name="Gumby",age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> '%(name)s \' s age is %(age)s' % d
"Gumby ' s age is 42"
>>> len(d)
2
>>> d['name']
'Gumby'
>>> del d['name']
>>> 'name' in d
False

字典方法

>>>#----------------clear
>>>d.clear() #清除所有项,无返回值
>>>>>> d
{'age': 42, 'name': 'Gumby'}
>>> x=d
>>> d={}
>>> d
{}
>>> x
{'age': 42, 'name': 'Gumby'}
>>># then
>>> d
{'age': 42, 'name': 'Gumby'}
>>> x=d
>>> x
{'age': 42, 'name': 'Gumby'}
>>> d.clear()
>>> d
{}
>>> x
{}
>>>#-------------------copy浅复制
>>> x={'username':'admin','machines':['foo','bar']}
>>> y=x.copy()
>>> y['username']='mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo']}
>>> x
{'username': 'admin', 'machines': ['foo']}
>>>#--------------------deep copy 深复制
>>> from copy import deepcopy
>>> d={}
>>> d['names']=['Alfed','Bertrand']
>>> c=d.copy()
>>> dc=deepcopy(d)
>>> d['names'].append("Clive")
>>> c
{'names': ['Alfed', 'Bertrand', 'Clive']}
>>> dc
{'names': ['Alfed', 'Bertrand']}
>>>#--------------------fromkeys
>>> {}.fromkeys(['name','age'])
{'age': None, 'name': None}
>>> {}.fromkeys(['name','age'],'(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}
>>>#---------------------get
>>> d={}
>>> print d['name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'
>>> print d.get('name')
None
>>> print d.get('name','N/A')
N/A
>>>#---------------------has_key
>>> d.has_key('name')
False
>>>#---------------------pop
>>> x={'username':'admin','machines':['foo','bar']}
>>> x.pop('username')
'admin'
>>> x
{'machines': ['foo', 'bar']}
>>>#---------------------popitem弹出随机项(字典无顺序概念)
>>> x={'username':'admin','machines':['foo','bar']}
>>> x.popitem()
('username', 'admin')
>>> x
{'machines': ['foo', 'bar']}
>>>#--------------------setdefault  类似get
>>>#--------------------update
>>> x
{'username': 'admin', 'name': None, 'machines': ['foo', 'bar']}
>>> y={'username':'hello'}
>>> x.update(y)
>>> x
{'username': 'hello', 'name': None, 'machines': ['foo', 'bar']}
>>>#--------------------items 返回列表;iteritems返回迭代器对象
>>> x={'username':'admin','machines':['foo','bar']}
>>> x.items()
[('username', 'admin'), ('machines', ['foo', 'bar'])]
>>> x.iteritems()
<dictionary-itemiterator object at 0x00000000039F8F98>
>>>#--------------------keys  iterkeys
>>> x.keys()
['username', 'machines']
>>> x.iterkeys()
<dictionary-keyiterator object at 0x00000000039F8F98>
>>>#---------------------values  itervalues
>>> x={'username':'admin','machines':['foo','bar']}
>>> x.values()
['admin', ['foo', 'bar']]
>>> x.itervalues()
<dictionary-valueiterator object at 0x00000000039F8F98>

5.条件、循环和其它语句

逗号输出

>>> print 'age:',10
age: 10     #自动加空格

导入

from somemodule import some function as foobar
import module as foobar

序列解包

>>> x,y,z=1,2,3
>>> x,y=y,z
>>> values=1,2,3
>>> values
(1, 2, 3)
>>> x,y,z=values

>>> x={'username':'admin','machines':['foo','bar']}
>>> a,b=x.popitem()
>>> a
'username'
>>> b
'admin'

#python3.0
>>>a,b,*rest=[1,2,3,4]

条件预计:if,else,elif

x<>y即x!=y

同一性运算符is用于判断是否为同一个对象。

>>> x=y=[1,2,3]
>>> z=[1,2,3]	
>>> x==y
True
>>> x==z
True
>>> x is y
True
>>> x is z
False
>>> x is not z
True
>>> "alpha"<"beta"
True
>>> 's' in "is"
True
>>>#bool运算符and or not

断言:确保某一条件一定为真才能让程序正常工作。

>>> age=-1
>>> assert 0<age<10,'the age must be realistic'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: the age must be realistic

循环

# for i in []
# for i in range()/xrange()
# range一次创建整个序列,xrange一次创建一个数。
>>> x={'username':'admin','machines':['foo','bar']}
>>> for key in x:
...     print key,'corresponds to',x[key]
...
username corresponds to admin
machines corresponds to ['foo', 'bar']
>>> x.values()
['admin', ['foo', 'bar']]
>>> x.keys()
['username', 'machines']
>>> x.items()
[('username', 'admin'), ('machines', ['foo', 'bar'])]

>>> names=['anne','beth','george','damon']
>>> ages=[12,45,32,102]
>>> zip(names,ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
#zip可以处理不等长的序列,短的序列用完时就会停止。
>>> zip(range(5),xrange(100000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

# enumerate函数可以在提供索引的地方迭代索引-值对

>>> sorted([4,3,6,8,3])
[3, 3, 4, 6, 8]
>>> sorted('Hello,world!')
['!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello,world!'))
['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed("Hello,world!"))
'!dlrow,olleH'

#跳出循环:break,continue

列表推导式 list comprehension

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#python中空代码块是非法的,解决方法是pass语句,即什么也都不做。
>>>pass
>>>

#del
>>> x=["Hello","world"]
>>> y=x
>>> y[1]="python"
>>> del x       #删除的只是名称
>>> y
['Hello', 'python']

# exec 和 eval
>>> exec "print 1"
1
>>> from math import sqrt
>>> exec "sqrt=1"
>>> sqrt(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

命名空间,也叫作用域(scope),可认为是保存变量的地方,类似于不可见的字典。

>>> from math import sqrt
>>> scope={}
>>> exec "sqrt=1" in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
# eval用于计算表达式
>>> eval(raw_input("enter an arithmetic expression:"))
enter an arithmetic expression:6+8*2
22
#eval(raw_input(...))等同于input()
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值