Python语言的特性
Python是一门具有强类型(即变量类型是强制要求的)、动态性、隐式类型(不需要做变量声明)、大小写敏感(var和VAR代表了不同的变量)以及面向对象(一切皆为对象)等特点的编程语言。
版本
python2与python3是目前主要的两个版本。如下两种情况下,建议使用python2:
- 你无法完全控制你即将部署的环境时;
- 你需要使用一些特定的第三方包或扩展时;
python3 是官方推荐的且是未来全力支持的版本,目前很多功能提升仅在python3版本上进行。从入门阶段来说使用哪个版本影响不大,可以后续继续深入。
搭建开发环境
- 对于Linux平台,目前Linux很多发行版本都
默认安装了Python(版本稍旧)。如果不满意,也可以到www.python.org下载安装包,然后通过configure、make、make install进行安装。
- 对于Windows平台,从官网可以下载二进制的安装包,直接安装即可。
目前有很多成熟的IDE,例如PyCharm、Eclipse+PyDev插件和Komodo等。如果初步学习可以使用VIM或者EditPlus等文本编辑器即可。
hello world
我们按照惯例先写一个hello world程序,使用任何纯文本编辑工具(例如vim)创建一个名为hello_world.py的文件,然后拷贝如下内容到文件中。
if __name__ == "__main__":
print "hello word"
完成后保存,然后在该文件的目录下执行如下命令:
python hello_world.py
注释
- 行注释以#加一个空格来注释,段注释通过三引号("""或者’’’)
- 如果需要在代码中使用中文注释,必须在python文件的最前面加上如下注释说明:
# -* - coding: UTF-8 -* -
- 如下注释用于指定解释器
#! /usr/bin/python
下面是一个适合有中文的,可以自运行的简单实例:
if __name__ == "__main__":
print "你好 世界"
语法
- Python中没有强制的语句终止字符,且代码块是通过缩进来指示的。缩进表示一个代码块的开始,逆缩进则表示一个代码块的结束。
- 声明以冒号(:)字符结束,并且开启一个缩进级别。
- 赋值(事实上是将对象绑定到名字)通过等号(=)实现,双等号(==)用于相等判断,”+=”和”-=”用于增加/减少运算(由符号右边的值确定增加/减少的值)。这适用于许多数据类型,包括字符串。
变量
- 变量可以理解成房间号,或者去快递的编码,通过这个(变量)可以找到需要的东西
- python中数据有类型,而变量没有类型。变量不需要声明,变量的赋值操作即使变量声明和定义的过程。
- python中一次新的赋值,将创建一个新的变量。即使变量的名称相同,变量的标识并不相同。用id()函数可以获取变量标识:
if __name__ == "__main__":
x = 1
print id(x)
x = 2
print id(x)
- 如果变量没有赋值,则python认为该变量不存在
- 在函数之外定义的变量都可以称为全局变量。全局变量可以被文件内部的任何函数和外部文件访问。
- 全局变量建议在文件的开头定义。
##【函数】
如果把一堆代码堆到一起会很难使用,也很难理解。Python也提供了函数的功能。函数是一段可以重复多次调用的代码,函数定义示例如下:
def itworld123_add(x,y):
return x+y
常量
python中没有提供定义常量的保留字。可以自己定义一个常量类来实现常量的功能。
class _const:
class ConstError(TypeError) : pass
def __setattr__(self, key, value):
if self.__dict__.has_key(key):
raise self.ConstError,"constant reassignment error!"
self.__dict__[key] = value
import sys
sys.modules[__name__] = _const()
简单数据类型
Python的数字类型分为整型、长整型、浮点型、布尔型、复数类型。
3
1 + 1
8 - 1
10 * 2
35 / 5
5 / 3
5 // 3
5.0 // 3.0
-5 // 3
-5.0 // 3.0
3 * 2.0
7 % 3
2**4
(1 + 3) * 2
True
False
0 and 2
-5 or 0
0 == False
2 == True
1 == True
"This is a string"[0]
None
运算符和表达式
python不支持自增运算符和自减运算符。例如i++/i-是错误的,但i+=1是可以的。
not True
not False
True and False
False or True
1 == 1
2 == 1
1 != 1
2 != 1
1 < 10
1 > 10
2 <= 2
2 >= 2
1 < 2 < 3
2 < 3 < 2
"这是个字符串"
'这也是个字符串'
"Hello " + "world!"
"{} can be {}".format("strings", "interpolated")
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
"%s can be %s the %s way" % ("strings", "interpolated", "old")
"etc" is None
None is None
bool(0)
bool("")
bool([])
bool({})
控制语句
Python中可以使用if、for和while来实现流程控制。Python中并没有select,取而代之使用if来实现。使用for来枚举列表中的元素。如果希望生成一个由数字组成的列表,则可以使用range()函数。
some_var = 5
if some_var > 10:
print("some_var比10大")
elif some_var < 10:
print("some_var比10小")
else:
print("some_var就是10")
"""
用for循环语句遍历列表
打印:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
print("{} is a mammal".format(animal))
"""
"range(number)"返回数字列表从0到给的数字
打印:
0
1
2
3
"""
for i in range(4):
print(i)
"""
while循环直到条件不满足
打印:
0
1
2
3
"""
x = 0
while x < 4:
print(x)
x += 1
try:
raise IndexError("This is an index error")
except IndexError as e:
pass
except (TypeError, NameError):
pass
else:
print("All good!")
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)
for i in our_iterable:
print(i)
our_iterable[1]
our_iterator = iter(our_iterable)
our_iterator.__next__()
our_iterator.__next__()
our_iterator.__next__()
our_iterator.__next__()
list(filled_dict.keys())
符合数据类型
Python具有列表(list)、元组(tuple)和字典(dictionaries)三种基本的数据结构,而集合(sets)则包含在集合库中(但从Python2.5版本开始正式成为Python内建类型)。列表的特点跟一维数组类似(当然你也可以创建类似多维数组的“列表的列表”),字典则是具有关联关系的数组(通常也叫做哈希表),而元组则是不可变的一维数组。
li = []
other_li = [4, 5, 6]
li.append(1)
li.append(2)
li.append(4)
li.append(3)
li.pop()
li.append(3)
li[0]
li[-1]
li[4]
li[1:3]
li[2:]
li[:3]
li[::2]
li[::-1]
del li[2]
li + other_li
li.extend(other_li)
1 in li
len(li)
tup = (1, 2, 3)
tup[0]
tup[0] = 3
len(tup)
tup + (4, 5, 6)
tup[:2]
2 in tup
a, b, c = (1, 2, 3)
d, e, f = 4, 5, 6
e, d = d, e
empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"]
list(filled_dict.keys())
list(filled_dict.values())
"one" in filled_dict
1 in filled_dict
filled_dict["four"]
filled_dict.get("one")
filled_dict.get("four")
filled_dict.get("one", 4)
filled_dict.get("four", 4)
filled_dict.setdefault("five", 5)
filled_dict.setdefault("five", 6)
filled_dict.update({"four":4})
filled_dict["four"] = 4
del filled_dict["one"]
empty_set = set()
some_set = {1, 1, 2, 2, 3, 4}
filled_set = some_set
filled_set.add(5)
other_set = {3, 4, 5, 6}
filled_set & other_set
filled_set | other_set
{1, 2, 3, 4} - {2, 3, 5}
2 in filled_set
10 in filled_set
类和对象
Python支持有限的多继承形式。私有变量和方法可以通过添加至少两个前导下划线和最多尾随一个下划线的形式进行声明(如“__spam”,这只是惯例,而不是Python的强制要求)。
class Human(object):
species = "H. sapiens"
def __init__(self, name):
self.name = name
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
@classmethod
def get_species(cls):
return cls.species
@staticmethod
def grunt():
return "*grunt*"
i = Human(name="Ian")
print(i.say("hi"))
j = Human("Joel")
print(j.say("hello"))
i.get_species()
Human.species = "H. neanderthalensis"
i.get_species()
j.get_species()
Human.grunt()
模块
import math
print(math.sqrt(16))
from math import ceil, floor
print(ceil(3.7))
print(floor(3.7))
from math import *
import math as m
math.sqrt(16) == m.sqrt(16)
import math
dir(math)
|