简介
Python 由 Guido van Rossum(荷兰 🇳🇱)开发。
Python 是一门解释型语言、动态类型(弱类型)语言。
Python 的名字来源于 Monty Python's Flying Circus。
保存词
不能使用保存词(reserved words)来命名变量名称,这样的词有:
False, class, return, is, finally, None, if, for, lambda, continue, True, def, from, while, nonlocal, and, del, global, not, with, as, elif, try, or, yield, assert, else, import, pass, break, in, raise
Python 的关键字很接近自然语言:
True,False
布尔值,相当于“真,假”,类似于其他语言中的true, false
。None
相当与“空”,类似于其它语言中的null
。is,is not
运算符用于逻辑表达式,前者的意思是“和什么相同”,相似于==
,但是更强。is
同时检查值和类型,常用在None
或者布尔值的判断,类似 JavaScript 中的===
。
0 == 0.0 # True 0 is 0.0 # False
构建块
赋值
赋值就是把变量名和数值联系起来,定义函数就是把函数名和表达式联系起来。
赋值运算符 =
。
常量
Python 中可以直接使用常量。
print(322) print(5.3) print("Hello World")
变量
Python 中的变量不需要用关键字声明,可以直接赋值。
x = 12.2 y = 14
变量命名规则
- 必须以字母或下划线
_
开头 - 必须由字母、数字和下划线组成
- Python 区分大小写
语句
x = 2 # 赋值语句 x = x + 2 # 赋值表达式 print(x) # print 语句
使用 =
把值赋值给某一个变量。赋值运算符是从右开始计算的。
环境图
环境图用于显示变量和其数值之间的对应关系。
表达式
表达式描述了一次计算和取值。
所有的表达式都可以通过函数表达式实现。
例如:max(1,2)
这样的称为调用表达式(call expression),它的结构如下:
add (2 , 3) operator operand operand
操作符和操作数也是表达式。
数字表达式
使用 +, -, *, /, **, %
做数学运算,其中 **
是幂运算。
print(4 ** 3) # 64
运算符的优先级
- 括号最高
()
- 幂运算
**
- 乘法、除法、求余
* / %
- 加法、减法
+ -
- 从左到右
from left to right
逻辑运算符
not
为非运算符,类似其他语言的!
and
为与运算符,类似其他语言的&&
or
为或运算符,类似其它语言的||
三元运算符
Python 中的三元运算符和其他编程语言不同: condition ? x : y
,而是 result = x if condition else y
。
类型
Python 的变量、常量、字面量都有类型。
有些运算是禁止的,例如:1 + string。
可以使用 type()
找出某个数据的类型。
Python 中有隐式类型转换。
type(1) # <class'int'>
数字
主要有 int, float, double
类型。
Python 中整数的除法结果是浮点数。
字符串转化
可以使用 int(),float()
,可以把字符串变成整数。如果字符串中不包含数字,那么会得到 error
。
字符串
Python 可以使用单引号 ''
或者双引号 ""
来表示字符串。
字符串包含数字,仍然是字符串。
字符串是不可变的(immutable)。例如:
s = "hello" s[0] = 'y' # error s = 'y' + s[1:len(s)] # 可以,因为 s 现在是一个新对象 s = "yello" # 可以
字符数字转换
可以使用 int()
把字符串转化为数字。
可以使用 str()
把数字转化为字符串。
通常使用字符串来接收输入,然后再转化为想要的类型。
Python 3 中所有的字符串编码都是 Unicode。
字符串索引
可以使用 []
来获取字符串中某个位置的字符。索引从 0
开始。
在 Python 中可以使用负值作为索引,最后一个元素的索引为 -1
,随着负值的减小,也就是绝对值的增大,实际上相当于从右往左访问字符串。
fruit = 'app' letter = fruit[0] print(letter) # a print(fruit[9]) # error print(fruit[-1]) # p
字符串长度
使用 len()
获得字符串的长度。
fruit = 'banana' x = len(fruit) print(x) # 6
字符串循环
下面两段代码是一样的效果,第二种更 Python。
s = "abcdef" for index in range(len(s)): if s[index] == 'i' or s[index] == 'u': print("there is i or u") for char in s: if char == 'i' or char == 'u': print("there is i or u")
可以使用 for 或 while 循环。
fruit = 'banana' index = 0 while index < len(fruit): letter = fruit(index) print(letter) index = index + 1 for letter in fruit: print(letter)
字符串切片
使用 :
运算符(colon operator)完成字符串的切片操作。
切片运算符 [start:stop:step]
第一个数字是切片的开始位置,第二个数字是指切片的结束位置(直到但不包含该位置),第三个数字代表步长(默认为 1)。
如果省略第一或第二个数字,只留下冒号,那么默认从头或到尾。
s = 'Monty Python' print(s[0:4]) # Mont print(s[8:]) # thon print(s[:2]) # Mo print(s[:]) # Monty Python s = "abcdefgh" s[3:6] # "def" 和 s[3:6:1] 相同 s[3:6:2] # "df" s[::] # "abcdefgh" 和 s[0:len(s):1] 相同 s[::-1] # "hgfedbca" 和 s[-1:-(len(s)+1):-1] 相同,相当于反转字符串 s[4:1:-1] # "ec"
字符串拼接
使用 +
连接(concatenate)字符串。
hello = "hello" world = "world" print(hello + world) # helloworld
检测子串
使用 in
作为逻辑运算符。可以检测一个字符串是否被包含在另一个字符串中,返回一个布尔值。
fruit = 'banana' 'n' in fruit # True 'm' in fruit # False
字符串比较
使用比较运算符比较字符串。
if word == 'banana': print("all right") if word < 'banana': print('your word' + word + ', coes before banana')
字符串重复
使用 *
运算符来对字符串重复。
silly = "hello" * 3 print(silly) # hellohellohello
字符串库
使用字符串库中的函数,这些函数不会改变原本的字符串,而是返回一个新字符串。
使用 type()
查看字符串类型,类似 JavaScript 的 typeof
,dir()
可以查看能够用在字符串上的所有方法。
s = "" type(s) >>> <type 'str'>
使用 find()
查找字符串的子串,它查找子串第一次出现的位置,如果没有找到返回 -1
,类似 JavaScript 的 indexOf()
fruit = 'banana' pos = fruit.find('na') print(pos) # 2
使用 lower(), upper()
把字符串转化为小写或者大写,类似 JavaScript 的 toUpperCase(), toLowerCase()
great = 'Hello World' zap = great.lower() print(zap) # hello world
使用 replace()
意思是查找并替换,它会替换所有查找到的子串。
great =