2008年12月4日 星期四

Begining Python: From Novice to Professional

Install
http://www.python.org/download/
http://www.python.org/download/windows/
http://www.python.org/ftp/python/3.0/python-3.0.msi

Types
int,long,float

+,-,*,%,
/
before python3.0,
int use floor round, or use
from __future__ import division
to get float result from int division


// int division
** exponentiation


Hexadecimals: 0xXXXX

Octals:0XXXX(python3.0不會動...)

Container: sequence, mapping

Sequences: list, tuple, string, unicode string, buffer object, xrange object

List
index from 0

Sequence addition
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]

Sequence multiplication
>>> [42]*5
[42, 42, 42, 42, 42]

Slicing
>>> xxx=[1,2,3,4,5,6,7,8,9,0]
>>> xxx[4:6]
[5, 6]

>>> xxx[-3:]
[8, 9, 0]
>>> xxx[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> xxx[5:-3]
[6, 7]
>>> xxx[:2]
[1, 2]

Step
>>> xxx[::2]
[1, 3, 5, 7, 9]
>>> xxx[1::2]
[2, 4, 6, 8, 0]

keywork None
>>> xxx=[None]
>>> xxx
[None]

>>> len(x)
0
>>> len(xxx)
10
>>> max(xxx)
9
>>> min(xxx)
0

Sequence deletion
>>> del(xx[3])
>>> xx
['h', 'e', 'l', 'o']

Item Assignment
>>> xx
['h', 'e', 'l', 'l', 'o']
>>> xx[2]="a"
>>> xx
['h', 'e', 'a', 'l', 'o']

Slice Assignment
>>> xx[2:]=list("llo")
>>> xx
['h', 'e', 'l', 'l', 'o']

Convert to list
>>> list("hello")
['h', 'e', 'l', 'l', 'o']

string is not changable, like tuple.
>>> x="hello"
>>> x[3]="a"
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
x[3]="a"
TypeError: 'str' object does not support item assignment
>>> xx=list(x)
>>> xx[3]="a"
>>> xx
['h', 'e', 'l', 'a', 'o']

Membership check -- in
>>> xxx=[1,2,3,4,5,6,7,8,9,0]
>>> 3 in xxx
True
>>> 10 in xxx
False

List methods - object.method(argument)
append(value)
count(value) - count the occurances of the given value
extend(list_object)
index(value) - find the index of the given value
insert(pos,value)
pop(pos) - remove the element of the given position, the last one if pos not given
remove(value)
reverse()
sort()
sort(cmp)
sort(key=len)
sort(reverse=True|False)


Tuple
>>> 1
1
>>> 1,
(1,)
>>> (1,)
(1,)
>>> (1)
1

Convert list to tuple
>>> tuple([1,2,3])
(1, 2, 3)
>>>


Strings
single quote '
double quote "
escape \

String Concatenation +
String representations
str(x)
repr(x) or backticks `x`

Long string """ or '''
Raw string r"xxx"
Unicode string u"xxx"


Dictionary
>>> xx={'x':1,'y':2,'z':3}
>>> xx['y']
2
>>> dict([('name','alice'),('age',22)])
{'age': 22, 'name': 'alice'}
>>> dict(name='ann',age=27)
{'age': 27, 'name': 'ann'}


>>> xx=dict(name='ann',age=27)
>>> 'name' in xx
True
>>> 'ann' in xx
False



Functions
float(object)
int(object)
long(object)
str(object)
repr(object)
list(object)
tuple(object)

print(string)
input(string)
raw_input(string)
pow(x,y[,z]) (x**y)%z
abs(number)
cmath.sqrt(number)

round(number[,ndigits])

sorted(seq)
reversed(seq)
math.ceil(number)
math.floor(number)
math.sqrt(number)
floor
ceil

Module
math
cmath

import <module>
from <module> import <function>

沒有留言: