1. Python简介
Python是一种解释型的编程语言. 和C/C++不同, 不是先将源代码文件转化成可执行文件, 再执行; 而是直接由Python 解释器一行一行的读取源代码, 每读一行就执行一行. 但严格意义上讲, Python算是一种 "半编译, 半解释" 型的语言. 一方面, Python解释器会按行读取源代码文件, 然后会 先将源代码转为供Python解释器直接执行的 "字节码". 然后再执行字节码.
例如, 我们执行一个.py文件之后, 会生成一个同名的.pyc文件. 这个.pyc文件就是Python解释器生成的字节码文件. 如 果已经存在了.pyc文件, 那么就不需要再 "翻译" 一次了, 这样也提高了执行效率.
Python是基于Python的解释器来进行执行. 只要某个操作系统/平台上能运行Python解释器, 就可以完美的运行 Python的源代码. 主流的Windows, Linux, Mac等操作系统上都能够很好的支持Python
Python可以很容易的调用C/C++语言. 如果觉得哪里的逻辑性能不满足要求, 可以用C/C++重构这部分模块, 用Python 调用
Python的代码也可以很容易的嵌入到C/C++中执行.
2. 变量和类型
2.1 变量
- Python中的变量不需要声明, 直接定义即可. 会在初始化的时候决定变量的 "类型"
- 使用 = 来进行初始化和赋值操作
- Python中也支持增量赋值
n = 10
n = n * 10
n *= 10 // 等价于n = n * 10
- Python中不支持++/--这种自增运算符,只能写成
n += 1 - 变量命名规则
- 变量名必须是字母, 数字, 下划线. 但是不能用数字开头(规则和C语言一样).
- 变量名大小写敏感, case 和 Case 是两个不同的变量.
2.2 数据类型
2.2.1 基本数据类型
- Python没有int, float, 这样的关键字, 但是实际上数字的类型是区分 "int" "float" 这样的类型的. 使用内建 函数 type 可以查看变量的类型
a = 1
print(type(a)) # <class 'int'>
a = 1.0
print(type(a)) # <class 'float'>
a = "aaa"
print(type(a)) # <class 'str'>
- Python中的数字变量的取值范围, 并没有限制(完全取决于你机器的内存多大), 而不是像C语言中int用4个 字节表示
a = 1000 * 1000 * 1000 * 1000 * 1000 * 1000
print(a) # 1000000000000000000
- Python中还有一种 "复数" 类型. 和数学中的 "复数" 是相同的概念
a = 10 + 5j
print(a) # 10 + 5j
2.2.1.1 字符串类型
- Python中可以使用 单引号
', 双引号", 三引号'''/"""来表示字符串
a = 'hello py'
print(type(a)) # <class 'str'>
a = "hello py"
print(type(a)) # <class 'str'>
a = '''hello py'''
print(type(a)) # <class 'str'>
a = """hello py"""
print(type(a)) # <class 'str'>
- 有三种形式可以表示字符串这样的好处是如果字符串中包含了
"这样的字符, 就不用进行转义了.
a = 'Hello "Python"'
print(a) # Hello "Python"
- 如果一个字符串中既有单引号, 又有双引号, 可以使用三引号
a = '''I say "haha", you say 'hehe'.'''
print(a) # I say "haha", you say 'hehe'.
- 但是有些不可见字符, 仍然得进行转义, 使用
\进行转义. 比如换行符\n
a = 'Hello \n "Python"'
print(a) # Hello
# "Python"
2.2.1.2 字符串常见操作
- 使用索引操作符
[]或者切片操作符[:]来获取子字符串(切片操作是一个前闭后开区间). - 字符串的索引规则是: 第一个字符索引是0, 最后一个字符索引是-1(可以理解成len-1).
str = 'hello python'
print(str[0]) # h
print(str[-1]) # n
print(str[1:3]) # el
print(str[1:-1]) # ello python
print(str[2:]) # llo python
print(str[:2])# he
print(str[:]) # hello python
+用于字符串连接运算,*用于字符串重复
str1 = 'hello'
str2 = 'python'
str3 = str1 + str2
print(str3) # hellopython
str4 = str1 * 2
print(str4) # hellohello
- 用内建函数 len 获取字符串长度
str1 = 'hello'
str2 = 'python'
str3 = str1 + str2
print(str3) # hellopython
print(len(str3)) #11
str4 = str1 * 2
print(str4) # hellohello
print(len(str4)) # 10
- Python没有 "字符类型" 这样的概念. 单个字符也是字符串
- 格式化字符串, 可以使用 % 这样的方式进行格式化的替换.
a = 100
str = 'a = %d'
ret = str % a
print(ret) # a = 100
print(type(ret)) # <class 'str'>
2.2.1.3 bool类型
- Python中用True和False来表示布尔值(注意, 第一个字符大写).
- 布尔类型的变量, 也是一种特殊的整数类型. 在和整数进行运算时, True被当做1, False被当做0.
a = True
b = False
print(a) # True
print(type(a)) # <class 'bool'>
print(b) # False
print(type(b)) # <class 'bool'>
2.2.2 复合数据类型
2.2.2.1 列表 和 元组
- 列表和元组类似于C语言中的数组
- 使用 [] 来表示列表, 使用 () 来表示元组.
list = [1, 2, 3, 4]
print(type(list)) # <class 'list'>
tuple = (1,2,3,4)
print(type(tuple)) # <class 'tuple'>
- 列表和元组能保存任意数量, 任意类型的Python对象
list = [1, 'py', 3, 4]
print(list)
tuple = (1,2,"py",4)
print(tuple)
- 可以使用下标来访问里面的元素, 下标从0开始. 最后一个小标为-1
list = [1, 'py', 3, 4]
print(list[0])# 1
print(list[1]) # py
tuple = (1,2,"py",4)
print(tuple[2]) # py
print(tuple[-1]) # 4
- 可以使用[:]切片操作得到列表或元组的子集. 这个动作和字符串操作是一样的
- 列表和元组唯一的区别是, 列表中的元素可以修改, 但是元组中的元素不能修改
list = [1, 'py', 3, 4]
list[1] = 100
tuple = (1,2,"py",4)
tuple[1] = 10 # tuple[1] = 10
# TypeError: 'tuple' object does not support item assignment
2.2.2.2 字典
- 字典是Python中的映射数据类型. 存储键值对(key-value).
- 几乎所有类型的Python对象都可以用作键.
- 使用 {} 表示字典
dist = {'ip':'127.0.0,1'}
print(dist['ip']) # 127.0.0.1
dist['port'] = 8000
print(dist['port'])# 8000
2.3 动态类型特性
- 同一个变量, 可以赋值成不同的类型的值
a = True
print(type(a)) # <class 'bool'>
a = 10
print(type(a)) # <class 'int'>
a = 'aaaa'
print(type(a)) # <class 'str'>
a = 10.9999
print(type(a)) # <class 'float'>
3. 注释
- Python中使用 # 作为单行注释. #后面的内容都是注释的内容
4. 运算符
4.1 算术运算符
- Python中支持
+-*/%这样的操作符. 并且它们的行为都和C语言一样. /是精确除法.
a = 1
b = 2
print(a / b) # 0.5
//是 "整除". 会对结果进行取整
a = 1
b = 2
print(a // b) # 0
- ** 表示乘方运算(记得Python的数据无上限)
a = 100
b = 20
print(a ** b) # 10000000000000000000000000000000000000000
4.2 关系运算符
- Python也支持标准的关系运算符. > < >= <= == != 这些运算符的表达式的结果, 是一个布尔值
a = 100
b = 20
print(a < b) # False
print(a <= b) # False
print(a > b) # True
print(a <= b) # False
print(a == b) # False
print(a != b) # True
4.3 逻辑运算符
Python也支持逻辑运算符. and or not
a = 100
b = 20
print(a > b and a != b) # True
print(a != b or a < b) # True
print(not a < b) # True
4.5 赋值运算符
基本赋值:=, 复合赋值:+=, -=, *=, /=, %=
4.6 其他运算符
- 成员运算符:
in,not in。 - 身份运算符:
is,is not。
5. 函数
Python使用def来定义一个函数. 使用return来返回结果
def Add(x, y):
return x + y
# 调用函数
print(Add(1,2))
Python中没有 "重载" 这样的概念. 相同名字的函数, 后面的会覆盖前面的
def Func():
print("111111")
def Func():
print("2222222")
# 调用函数
Func() # 2222222
- Python支持默认参数. 函数的参数可以具备默认值
def Func(debug=True):
if debug:
print('in debug mode')
print('done')
Func()
Func(False)
- Python解包(unpack)语法, 函数返回多个值
def GetPoint():
return 100, 200
x, y = GetPoint()
print(x) # 100
print(y) # 200
- 假如只关注第二个返回值, 不想关注第一个, 可以使用
_作为占位符.
def GetPoint():
return 100, 200
_, y = GetPoint()
print(y) # 200
- 函数也是 "对象". 一个函数和一个数字,字符串一样, 都可以定义 "别名" 来引用它
def Func():
print('aaa')
func = Func
func()
print(type(func))
6. 条件语句
6.1 代码块及缩进
Python中使用缩进来表示代码块. 相当于天然从语法的角度规定了代码风格.
Python是独一无二的使用缩进而不是{}, 这就避免了一场党派之争
- 党派1
if(a > b)
{
//...
}
- 党派2
if (a > b){
//....
}
- 使用Python就没有这个之争了.因为Python不用{}
6.2 if语句
标准的if条件语句语法为如下:
- 如果表达式的值非0或者为True,则执行do_something,否则执行吓一跳语句
if expression:
do_something1
do_something2
next_something
- Python也支持else语句
if expression:
do_something1
else:
do_something2
- Python里还有神奇的的elif(意思是else-if)
if expression1:
do_something1
elif expression2:
do_something2
else:
do_something3
a = 10
b = 20
if a == b:
print("-----")
elif a != b:
print("+++++++")
else:
print("*******")
- Python并不支持switch/case这样的语句. 也没有必要支持. 实际上 switch/case 语法并不优雅
7. 循环语句
7.1 while循环
- while循环语句和if语句语法类似. 只要表达式的值非0或者为True, 就会循环执行do_something
while expression:
do_something
a = 5
while a > 0:
print(a)
a -= 1
7.2 for循环
- Python中的for循环和传统的for循环不太一样.
- for循环接收可迭代对象(序列或者迭代器)作为参数, 每次迭代其中的一个元素.
a = 'Hello Python'
for i in a:
print(i)
# 遍历列表中的每一个元素
a = [1, 2, 3, 4]
for item in a:
print(item)
# 遍历字典中的所有key-value
a = {'ip':'192.168.1.1', 'port':80}
for key in a:
print (key, a[key])
- 内建函数range能够生成一个数字组成的列表, 方便进行for循环遍历
for i in range(0,3):
print(i)
# 第三个参数 表示每次步长为5
for i in range(0,100,5):
print(i)
7.3 break 和 continue
- 使用break语句跳出当前循环
- 使用continue语句, 回到循环, 判定循环条件;
- 循环条件满足, 则执行下一次循环;
for i in range(1,100):
if i % 3 == 0:
print(i)
break
# 打印 [0, 100) 所有3的倍数
for i in range(0, 100):
if i % 3 != 0:
continue
print(i)
7.4 pass语句
有时候需要用到空语句这样的概念, 什么都不做. 由于没有 {} , 需要有一个专门的语句来占位, 要不缩进就混乱了.
x = 2
if x % 2 == 0:
pass #空语句
else:
print(x);
8. 文件操作
- 使用内建函数 open打开一个文件
file1 = open("test1.txt","w")
- 第一个参数是文件名,可以是绝对路径或者相对路径
- 第二个参数是文件的打开方式,有以下几种
- 'r' : 只读
- 'w' : 只写
- 'a' : 追加写
- 't' : 按文本方式读写
- 'b' : 按二进制方式读写
- 返回值是一个文件描述符,是一个可迭代的对象. 可以直接使用for循环按行读取文件内容
file1 = open("test1.txt","w")
# 向文件写入
for i in range(0, 10):
file1.write("Hello Python\n")
file1.close()
file1 = open("test1.txt","r") # 以读方式打开
for line in file1:
print(line)
9. 模块
一个项目的代码量较大的时候, 需要把代码放到多个不同的.py文件中.
- 可以通过 import 关键字, 引用其他.py文件中的代码.
- 被引入的这个代码文件, 就称之为 "模块".
- 被引入的文件, 去掉.py后缀名, 就是模块名
# add.py
def Func():
print("Hello World")
# test.py
# 直接import 模块名
import add
add.Func()
# 只import add模块中的Func函数
from add import Func
Func()
# 导入模块 并给模块取别名
import add
a = add
a.Func()