一、注释
1. #单行注释
2. """多行注释"""
二、数据类型和操作符
1. 数字及计算
四则混合运算:2+3、9-5、6*7、36/9
整数除法取整:9%7 =>1
精确浮点数:10.0/4.0 =>2.5
括号优先级(2+3)*3 =>15
2. 布尔类型
True、False、not True、not False
3. 逻辑判断
==、!=、>、<、>=、<=
4. 字符串由单引号'*'或双引号"*"
"hello world",'hello world'
5. 字符串拼接加号+实现
'hello' + ' world' => 'hello world'
6. 字符串可视为字符列表
'welcome to China!'[0] =>'w'
7. %、format 可用来格式化字符串
"%s can be %s" % ("strings", "interpolated")
"{0} can be {1}".format("strings", "formatted")
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
8. None是对象,不能用'=='进行对象的逻辑比较,而要用'is'
"etc" is None => False
None is None => True
9. None、0、空字符串都被算作False,其他均为True
0 == False => True
"" == False => True
二、变量和集合
1. 输出
print "How are you!"
2. 变量赋值不用提前声明
var = 8
3. 访问未赋值变量会抛出异常
var_value => NameError
4. if语句可以作为表达式使用
"yahoo" if 3 > 2 else 2 => "yahoo!"
5. 列表用来保存序列
li = []
6. 可直接初始化列表
other_li = [4,5,6]
7. 列表元素操作
添加:li.append(1) => li 即 [1]
li.append(2) => li 即 [1,2]
li.append(3) => li 即 [1,2, 3]
li.append(4) => li 即 [1,2, 3, 4]
移除:li.pop() => li即[1, 2, 3]
访问:li[0] => 1
li[3] => 越界异常
li[:3] =>切片语法,左闭右开,li即[1, 2, 3]
删除:del li[2] => li即[1,2]
合并:li + other_li => [1,2,4,5,6],并不会改变这两个列表
li.extend(other_li) => li即 [1,2,3,5,6]
查询:1 in li => True,in来返回元素是否在列表中
长度:len(li) => 5
8. 元组,类似列表,但是不可改变
tup = (1,2,3)
tup[0] => 1
tup[0] = 3 => 类型错误
长度:len(tup) => 1
拼接:tup + (4, 5, 6) =>(1,2,3,4,5,6)
切片操作:tup[:2] =>(1,2)
查询:2 in tup => True
解包:a, b, c = (1, 2, 3)
默认元组(不加括号):d, e, f = 4, 5, 6
数值交换:e, d = d, e => d为5,e为4
9. 字典
存储映射:empty_dict = {}
字典初始化:filled_dict = {"one":1, "two":2, "three":3}
字典用中括号访问:filled_dict["one"] => 1
所有键保存在列表中:filled_dict.keys() => ["three", "two", "one"],键顺序不唯一
所有值保存在列表中:filled_dict.values() =>[3, 2, 1],和键的顺序相同
判断一个键是否存在:"one" in filled_dict =>True
查询不存在的键:filled_dict["four"] => KeyError
get方法避免KeyError:
filled_dict.get("one") =>1
filled_dict.get("four") =>None
setdefault是一个更安全的添加字典元素的方法:
filled_dict.setdefault("five", 5) => filled_dict["five"] 值为5
filled_dict.setdefault("five", 6) => filled_dict["five"] 值仍为5
10. 集合
存储无顺序的元素:empty_set = set()
初始化一个集合:some_set = set([1, 2, 2, 3, 4]) => some_set现在是set([1, 2, 3, 4])
大括号表示集合:filled_set = {1, 2, 2, 3, 4} =>{1, 2, 3, 4}
向集合添加元素:filled_set.add(5) => filled_set 现在是{1, 2, 3,4,5}
用&来计算集合的交:other_set = {3, 4, 5, 6}
filled_set & other_set => {3, 4, 5}
用 | 来计算集合的并:filled_set | other_set => {1, 2, 3, 4, 5, 6}
用 - 来计算集合的差:{1, 2, 3, 4} - {2, 3, 5} => {1, 4}
用 in 来判断元素是否存在于集合中:2 in filled_set => True
三、控制流程
1. 新建变量:some_var = 5
2. 调用if,主意缩进:
if some_var > 10:
print "some_var is totally bigger than 10."
elseif some_var < 10:
print "some_var is smaller than 10."
else:
print "some_var is indeed 10."
3. for 循环遍历:
for animal in ["dog", "cat", "mouse"]:
print "%s is a mammal" % animal = > dog is a mammal\n cat is a mammal\n mouse is a mammal
'range(number)' 返回0到给定数字的列表:
for i in range(4):
print i => 0, 1, 2, 3
4. while 循环遍历
x=0
while x < 4:
print x
x += 1
5. 异常处理,try/except
try:
#raise 抛出异常
raise IndexError("This is an index error")
except IndexError as e:
pass #pass即什么都不做,通常会做一些恢复工作
四、函数
1. 用def新建函数
def add(x, y):
print "x is %s and y is %s" % (x, y)
return x + y
调用带参数的函数
add(5, 6) => 输出"x is 5 and y is 6"返回11
通过关键字赋值来调用函数
add(y=6, x=5) =>顺序无影响
2. 可定义接受多个变量的函数,这些变量按顺序排列
def varargs(*args):
return args
varargs(1, 2, 3) =>(1, 2,3)
3. 可定义接收多个变量的函数,这些变量按照关键字排列
def keyword__args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness") =>{"big":"foot", "loch":"ness"}
4. 同时将一个函数定义成两种形式
def all_the_args(*args, **kwargs):
print args
print kwargs
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a":3, "b":4}
5. 调用函数时,可进行相反操作,把元组和字典展开为参数
args = (1, 2, 3, 4)
kwargs = {"a":3, "b":4}
all_the_args(*args) =>等价于 foo(1, 2, 3, 4)
all_the_args(**kwargs) =>等价于 foo(a=3, b=4)
all_the_args(*args, **kwargs) =>等价于foo(1,2,3,4,a=3,b=4)
6. 函数是一等公民
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) =>13
7. 匿名函数
(lambda x: x > 2)(3) => True
8. 内置高阶函数
map(add_10, [1, 2, 3]) => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) => [6, 7]
9. 可以用列表方法来对高阶函数进行更巧妙的引用
[add_10(i) for i in [1, 2, 3]] => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] => [6, 7]
五、类
1. 从object类中继承
Class Human(object):
类属性:species = "H. sapiens" => 由所有类的对象共享
基本构造函数:
def __int__(self, name):
self.name = name => 将参数赋给对象成员属性
def say(self, msg): =>成员方法,参数要有self
return "%s: %s" % (self.name, msg)
def get_species(cls): =>类方法由所有类对象共享,类方法调用时,会把类本身传给self参数
return cls.species
def grunt(): =>静态方法是不需要类和对象的引用就可以调用的方法
return "*grunt*"
2. 实例化一个类
i = Human(name = "Ian")
print i.say("hi") => "Ian: hi"
j = Human("Joel")
print j.say("hello") => "Joel: hello"
3. 访问类的方法
i.get_species() => "H. sapiens"
4. 改变共享属性
Human.species = "H. neanderthalensis"
i.get_species() => "H. neanderthalensis"
j.get_species() => "H. neanderthalensis"
5. 访问静态变量
Human.grunt() => "*grunt*"
六、模块
1. 可以导入其他模块
import math
print math.sqrt(16) =>4
2. 从一个模块中导入特定的函数
from math import ceil, floor
print ceil(3.7) => 4.0
print floor(3.7) => 3.0
3. 模块中导入所有函数(不推荐使用)
from math import *
4. 简写模块名
import math as m
math.sqrt(16) == m.sqrt(16) => True
5. 查看模块中属性和方法
import math
dir(math)
python的模块其实只是普通的python文件,可以创建自己模块并导入,模块名字和文件名字相同
阅读(738) | 评论(0) | 转发(0) |