函数的定义:
def function_name(parameters):
block
return
expression
自带函数:
abs(-9)
#取绝对值
round(3.4) #浮点数四舍五入到整数
pow(2,4)
#2的4次方
raw_input()
#用户输入
例如:
>>> name=raw_input("Pls enter a
name: ")
Pls enter a name:
Obama
>>> name
‘Obama‘
模块:
>>>
import math
>>> math.sqrt(9)
3.0
定义自己的模块:name.py中存放function1、function2等,name.function1
常用的字符串处理方法:
S.lower()
#将S中所有字母转化成小写并输出
S.upper() #将S中所有字母转化成大写并输出
S.islower() #测试S中所有字母是否都为小写
S.isupper() #测试S中所有字母是否都为大写
S.swapcase() #大小写互换
S.capitalize()
#首字母大写
S.find(s,beg)
#返回S中索引beg之后首次出现s的索引,如没有返回-1
S.find(s,beg,end)
#返回S中索引beg与索引end之间首次出现s的索引,如没有返回-1
如:
>>>
"abcdefg".find("f",3)
5
>>>
"abcdefg".find("f",3,6)
5
S.replace(old,new)
#将S中所有old替换成new
如:
>>>
"abcdefg".replace("b","M")
‘aMcdefg‘
S.split(del)
#将del分割的子串以列表的形式返回
如:
>>>
"abcdefg".split("b")
[‘a‘,
‘cdefg‘]
S.strip(s)
#删除字符串中的s并返回
S.startswith(s)
#判断是否以s开始并返回
S.endswith(s)
#判断是否以s结尾并返回
如:
>>> "Computer
Science".swapcase().endswith("ENCE")
True
Dictionary数据类型:
大括号括起来,里边是多个元素,每个元素由"key":"value"组成,元素之间逗号间隔
如:d={"1":"Alsen","2":"Oxsel"}
可以发现输入命令行d["2"]时,系统返回‘Oxsel‘
key大小写敏感
增加元素时,只需要命令行
d["4"]="Fabien"即可,键值对在d中不排序
删除元素时,del
d["2"]
清空元素时,d.clear()
>>>
d={"1":"Alsen","2":"Oxsel"}
>>> d.keys()
[‘1‘,
‘2‘]
>>> d.values()
[‘Alsen‘, ‘Oxsel‘]
>>>
d.items()
[(‘1‘, ‘Alsen‘), (‘2‘, ‘Oxsel‘)]
>>> ["%s=%s" %(k,v)
for k,v in d.items()]
[‘1=Alsen‘, ‘2=Oxsel‘]
>>>
";".join(["%s=%s" %(k,v) for k,v in
d.items()])
‘1=Alsen;2=Oxsel‘
List数据类型:
>>> original=[‘H‘,‘He‘]
>>>
final=original+[‘Be‘]
>>> final
[‘H‘, ‘He‘,
‘Be‘]
>>> metals="Fe Ni".split()
>>>
metals*4
[‘Fe‘, ‘Ni‘, ‘Fe‘, ‘Ni‘, ‘Fe‘, ‘Ni‘, ‘Fe‘,
‘Ni‘]
for循环
>>> outer=[‘1‘,‘2‘,‘3‘,‘4‘]
>>>
inner=[‘A‘,‘B‘,‘C‘]
>>> for digi in
outer:
... for alp in
inner:
...
print digi+alp+‘\t‘,
...
1A
1B 1C 2A
2B 2C 3A
3B 3C 4A
4B 4C
切片:
>>> marker=["a","b","c","d","e"]
>>>
marker[1:4]
[‘b‘, ‘c‘,
‘d‘]
切片的list[i:j]从索引i(包含)开始,到索引j(不包含)结束
别名机制:A和B均引用了1个列表,通过A对该列表修改都能被B看到
>>>
A=[‘0‘,‘1‘,‘2‘,‘3‘]
>>> B=A[:]
>>>
A[2]=‘test‘
>>> A
[‘0‘, ‘1‘, ‘test‘, ‘3‘]
>>>
B
[‘0‘, ‘1‘, ‘2‘, ‘3‘]
>>>
A=[‘0‘,‘1‘,‘2‘,‘3‘]
>>> B=A
>>>
A[2]=‘test‘
>>> A
[‘0‘, ‘1‘, ‘test‘, ‘3‘]
>>>
B
[‘0‘, ‘1‘, ‘test‘, ‘3‘]
列表:
>>> number=‘1 2 3 4
5‘.split() #分割,结果是[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]
>>>
number.append(‘8‘)
#追加
>>> number.insert(3,‘8‘)
#索引3处添加值8
>>> number.remove(‘8‘)
>>> number.reverse()
#反转列表中的顺序
>>>
number.sort()
#升序排列
>>> number.pop()
#移除,并返回列表的最后1个元素
>>> number.strip()
#去掉行结束符
例如:
>>> line="marshal\n"
>>>
len(line)
8
>>>
len(line.strip())
7
Tuple数据类型:
不可变的list,小括号包围
不能向tuple中增加、删除、查找元素
但可以使用in来查看一个元素是否存在与tuple中
if语句:
注意的是(1)条件后边要加冒号,即if
condition:(2)要认真缩进。
for语句:
for variable in list:
block
例如:
for i in range(2000,2050,4):
print
i
enumerate()函数:
返回pair,第一个元素为索引,第二个元素为值
for i
in enumerate(range(2000,2050,4)):
print
i
while循环:
while condition:
block
break和continue:
break:跳出循环体
continue:跳回循环体顶部,重新开始下一次迭代
如:
entry_number
= 1
file = open("data.txt","r")
for line in file:
line = line.strip()
if
line.startswith("#"):
continue
if line == "Earth":
break
entry_number = entry_number
+ 1
print "Earth is the %d th-lightest planet."
%(entry_number)
也可以写成:
entry_number = 1
file =
open("data.txt","r")
for line in file:
line =
line.strip()
if not line.startswith("#"):
if line == "Earth":
break
entry_number = entry_number
+ 1
print "Earth is the %d th-lightest planet."
%(entry_number)
连续值赋值:
>>>
(m,tu,w,th,f,s)=range(6)
>>> tu
1
>>>
th
3
映射赋值:
>>> li=[1,3,4,7,5]
>>> [i*2 for i
in li]
[2, 6, 8, 14, 10]
>>> li
[1, 3, 4, 7,
5]
>>> [i for i in li if i>6]
[7]
and 和 or
:
执行布尔逻辑演算,但是它们并不返回布尔值,而是返回它们实际进行比较的值之一
从左到右演算表达式的值
>>>
a="first"
>>> b="second"
>>> 1 and a or
b
‘first‘
>>> 0 and a or b
‘second‘
导入模块:
方法一:import
module
方法二:from module import XXX
区别在于:
>>> import
types
>>> types.FunctionType
<type
‘function‘>
>>> FunctionType
Traceback (most recent call
last):
File "<stdin>", line 1, in <module>
NameError:
name ‘FunctionType‘ is not defined
>>> from types import
FunctionType
>>> FunctionType
<type
‘function‘>
如果要经常访问模块的属性和方法,且不想一遍又一遍地敲入模块名,使用 from module
import。
如果模块包含的属性和方法与你的某个模块同名,你必须使用 import module 来避免名字冲突。
尽量少用 from
module import *
,因为判定一个特殊的函数或属性是从哪来的有些困难,并且会造成调试和重构都更困难。
类class:
通过结构(struct),我们将简单数据类型(int,float,bool……)或简单数据类型的数组、指针,组合成一个新的数据类型。
世界是由“数据”和“动作”组成的。光能定义出各种数据类型,还只是编程世界的一半。
类(class)的定义中,加入了函数
“动作”与“数据”从这里开始合二为一,在类的定义里,同时可以包括数据及函数。由此开启了“面向对象”世界之门
1.
使用一个名为 __init__ 的方法来完成初始化。
2. 所有的实例方法都拥有一个 self 参数来传递当前实例,类似于 this。
3.
可以使用 __class__
来访问类型成员
例子:
*********************************************************************
class
Person():
population=0
def
__init__(self,name):
self.name=name
Person.population+=1
def
sayHi(self):
print ‘Hello
everyone, my nationality is %s‘% self.name
def
howMany(self):
if
Person.population==1:
print "I am the only one here"
else:
print "We have %d people here" %
Person.population
a=Person(‘China‘)
a.sayHi()
a.howMany()
b=Person(‘USA‘)
b.sayHi()
b.howMany()
c=Person(‘France‘)
c.sayHi()
c.howMany()
*********************************************************************
结果:
Hello
everyone, my nationality is China
I am the only one here
Hello everyone,
my nationality is USA
We have 2 people here
Hello everyone, my nationality
is France
We have 3 people
here
另一个例子:
*********************************************************************
class
Account(object):
"一个简单的类"
account_type="Basic"
def
__init__(self,name,balance):
"初始化一个新的Account实例"
self.name=name
self.balance=balance
def
deposit(self,amt):
"存款"
self.balance=self.balance+amt
def
withdraw(self,amt):
"取款"
self.balance=self.balance-amt
def
inquiry(self):
"返回当前余额"
return
self.balance
a=Account(‘1‘,50)
a.deposit(33)
a.withdraw(16)
print(a.balance)
*********************************************************************
结果:
67
Python用法摘要 BY 四喜三顺,布布扣,bubuko.com
原文:http://www.cnblogs.com/sxss/p/3664334.html