Web编程技术营地
研究、演示、创新

Python快速导览

撰写时间:2024-11-03

修订时间:2025-09-08

概述

在众多编程语言中,Python语言近20年来,尤其是自2018年开始,取得了令人瞩目的长足的进步。在TIOBE排行榜中,它以29.90%的比例荣居榜首,并且上升幅度为+7.08%。相比之下,第3名的Java语言上升幅度仅为+1.59%,而其它语言要么是+0.XX%,要么是-0.XX%

Python能迅猛发展,受到了各个领域的程序员的普遍拥趸,个人认为,主要是基于以下几个原因:

  1. 语言特性简洁高效
  2. 社区活跃,周边支持库极其丰富
  3. 人工智能AI的激励
  4. 已经形成生命力旺盛的独有生态圈

在Anaconda, Jupyter, Matplotlib, SciPy, scikit-learn等行业翘楚的重磅加持下,Python真正成了天选之子,在AI、科学研究、学习教育等各个领域独占鳌头。

现在,越来越多的软件均已加入Python脚本的插件功能, 在视频制作领域,诸如Premiere, After Effect, Cinema 4D, Blender等等。而在文字表格处理领域方面,就连到微软的Excel也来凑热闹了。

基本语言要素

print函数

使用print函数以在标准输出终端输出信息。

print('Hello, Python')

类似C语言的字符串输出:

print('%d + %d = %d' % (2, 3, 2+3))

F-string,带格式的字符串字面符,以字符fF作为字符串字面符的前缀:

m = 2 n = 3 print(f'{m} + {n} = {m + n}')

使用字符串的format方法:

print('{0} + {1} = {2}'.format(25, 12, 25+12)) print('{:^10}{:^10}{:^10}'.format('姓名', '语文', '数学')) print('{:<10}{:>10}{:>10}'.format('张三', '85', '60')) print('{:<10}{:>10}{:>10}'.format('李四', '75', '82'))

数字的格式化:

print('int: {0:d}, hex: {0:#x}, oct:{0:#o}, bin: {0:#b}'.format(35)) print('{:,}'.format(1234567890)) print('{:_x}'.format(1234567890)) print('{:_b}'.format(1234567890))

时间的格式化:

import datetime d = datetime.datetime(2025, 3, 5, 8, 40, 25) print(d) print('{:%Y/%m/%d %H:%M:%S}'.format(d))

print函数有多个参数,在打印时,默认情况下,以空格来分隔每个参数,并在结果后面添加一个回车:

print(1, 2, 3) print(4, 5, 6)

可使用命名参数来设置不同的状态:

print(1, 2, 3, sep=' <===> ', end='\n\n') print(4, 5, 6)

注释语句

使用字符#来注释语句。在任一行语句中,字符#后面的语句将不被执行。

# this is a comment line print('Hello, Python') # comment after codes

没有块注释。但可通过多行字符串字面符 ('''...''') 或 ("""...""") 的方式将代码转换为字符串。字符串中的源代码不会被执行,从而实现了注释的效果。此外,在运行时,此字符串会被分配内存,但由于没有被赋值于变量,字符串不会被使用。这也是Python在类、函数、方法中进行文档注释的标准方式。

# the following statement would not run ''' print('Hello, Python') '''

基本算术运算符

print(5 + 3) print(5 - 3) print(5 * 3) print(5 / 3) # division, yields a float print(5 // 3) # floor division, yields a integer print(5 % 3) # mod print(5 ** 3) # power

复合赋值运算符:

x = 5 y = 3 x += y x -= y x *= y x **= y x /= y x //= y x %= y

简单的数据类型

简单的数据类型包括整数、浮点数、字符串,以及布尔型。

a = 25 print(type(a)) b = 23.2 print(type(b)) c = 'abc' print(type(c)) d = True print(type(d))

JavaScript不同的是,Python不支持数据类型的自动转换:

aStr = '33' num = 25 print(aStr + num)

此时,应使用int()str()函数来进行转换:

aStr = '33' num = 25 print(int(aStr) + num)

语句与变量

Python声明无需指定数据类型。一行为一个语句,语句后面无需带有分号;结尾。

str1 = 'Hello, Python' print(str1) x = 10 y = 20 z = x + y print(z)

可以同时声明多个变量并赋于初始值。

a, b, c = 5, 10, 15 print(a, b, c)

无需第三方变量,可直接实现两数值交换。

a, b = 5, 10 print(a, b) a, b = b, a print(a, b)

字符串

基本用法

行内分隔符为 ('...') 或 ("..."),多行分隔符为 ("""...""")。

str1 = 'Hello' print(str1) str2 = "Python" print(str2) str3 = """ This is a string which has multiple lines. """ print(str3)

当有些字符串太长,我们希望在输入时断行,但输出时却作为一个整个字符串输出,则可在各个字符串字面符之间加上空格,且在每一行的字符串字面符后面加上一个反斜杆\ (backslash) 字符,表示,下行的内容不另起新行,而应与本行的内容合并

myStr = 'This is a string ' \ 'which is too long to display ' \ 'in a line.' print(myStr)

字符串是由字符组成的数组,因此可使用数组的特性。

myStr = 'Hello, Python. Good to see you.' print(myStr[7:13])

使用len函数来计算基于Unicode编码的字符串长度。

myStr = '中国北京' print(len(myStr))

字符串可以乘以一个数值n,即使用n个相同的字符串来构建一个新的字符串。

myStr = 'ho' newStr = myStr * 3 print(newStr)

字符串的join()方法

字符串有一join方法,可用于生成一个使用特定连接符来连接序列(元素类型须为字符串)各个元素的字符串。

separator = ' -- ' string = 'abcde' print(separator.join(string))

将字符串中的每个字母拆开后,使用separator来连接。需注意的是,须调用separatorjoin方法而不是stringjoin方法。

join方法的参数可以是tuplelist,但其元素的数据类型须为字符串。

tuple = ('Hello', 'Python') print(', '.join(tuple)) aList = ['Python', 'programming', 'language'] print(' '.join(aList))

如果一个tuple对象的元素的数据类型为非字符串时,可以使用str函数来将整个tuple对象转换为一个字符串,但需注意结果字符串中也包含了括号()、空格、以及逗号)。这些元素也将参与连接。结果看起来很怪异。

tuple = (1, 2, 3) string = str(tuple) print(string) print('-'.join(string))

此时,可自行先将每个元素转换为字符串,然后再拼接为一个新字符串,最后在新字符串上进行连接。

tuple = (1, 2, 3) wholeStr = ''; for ele in tuple: char = str(ele) wholeStr += char print(wholeStr) print('-'.join(wholeStr))

List

Python中的list,就是其他编程语言中的数组。

声明

list1 = [1, 2, 3, 4, 5] print(list1) list2 = list((1, 2, 3)) print(list2)

上面的list()函数是list的构造函数,参数类型为可遍历对象 (iterable)。

Python有多个内置的数据类型,其类名均为小写,如int, list, tuple, str, dict,等等。它们都有名称与类名相同的构造函数。如int(), list(), tuple(), str(), dict(),等等。

下面的代码将犯下一个无意之错:

list = [1, 2, 3, 4, 5] print(list) list2 = list((1, 2, 3)) print(list2)

1行先声明了一个名为list的变量,第3行准备调用list构造函数时出错了:变量list不是可被调用的对象。

因此在声明变量时,变量名称最好不要与这些内置数据类型的名称相同。

使用range()函数构建

内置函数range可用以生成一系列可遍历的数值,其结果可用作list函数的参数。

print(list(range(1, 10))) # [inclusive : exclusive] print(list(range(1, 10, 2))) # start to stop, stepping print(list(range(0, -10, -2))) # negative stepping print(list(range(0))) # empty list

List comprehensions

可以基于一个序列的值,使用简短的方式来生成一个list

list1 = [1, 2, 3] list2 = [x * 2 for x in list1] print(list2)

这种方式,称为list comprehensions

可以将上面的x * 2这一部分,再换成另一个list comprehensions,从而构建嵌套的list comprehensions

list1 = [1, 2, 3] range1 = range(0, 10) nestedList = [ [j for j in range1] for i in list1 ] print(nestedList)

切割

设有以下list

element510152025
index01234

下面进行各种各样的切割:

list1 = [5, 10, 15, 20, 25] print(list1[1:3]) # [inclusive : exclusive] print(list1[2:]) # from 2nd to end print(list1[:3]) # from 1st to 3rd print(list1[:]) # slice all print(list1[0:4:2]) # from 1st to 4th, step 2 print(list1[:-2]) # from 1st to last 2nd

切割出的list对象是新对象。

list1 = [5, 10, 15, 20, 25] list2 = list1[:]; print(list1) print(list2) print(list1 == list2) print(id(list1) == id(list2))

但当在切割出的list对象上直接赋值时,却是针对原来的对象来操作。

list1 = [5, 10, 15, 20, 25] list1[2:3] = [7, 8, 9]; print(list1)

删除list元素

可以很方便地删除list中的元素。

arr = [5, 10, 15, 20, 25] del(arr[1]) print(arr)

删除一组连续排列的元素。

arr = [5, 10, 15, 20, 25] del(arr[1:3]) print(arr)

使用clear方法来删除list的所有元素。

arr = [5, 10, 15, 20, 25] arr.clear() print(arr)

in操作符

list1 = [5, 10, 15, 20, 25] print(25 in list1)

max(), min()

内建函数max, min可直接求出list的最大值与最小值。

list1 = [5, 10, 15, 20, 25] print(min(list1), max(list1))

count()

listcount方法返回特定元素出现的次数。

list1 = [3, 2, 3, 5, 7] print(list1.count(3))

append()

listappend方法用于添加新元素。

list1 = [1, 2, 3, 4, 5] list1.append(9) print(list1) print(len(list1))

判断list是否为空

第一种方法:使用not操作符。

list1 = [] print(not list1) list1.append(5) print(not list1)

第二种方法:使用len函数。

list1 = [] print(len(list1) == 0)

第三种方法:使用bool函数。

list1 = [] if (bool(list1) == False): print('list is empty')

bool函数返回list的状态。当list为空值时,返回False

Tuple

tuple,中文为元组,几乎与list一样。最主要的区别在于,list的内容是可以改写的 (mutable),而tuple的内容是不可改写的 (immutable)。

声明一个tuple时,有2种形式。一种是将序列值使用(...)括起来;另一种是不使用括号。

tuple1 = (1, 2, 3) print(tuple1) print(type(tuple1)) tuple2 = 4, 5, 6 # tuple packing print(tuple2) print(type(tuple2))

上面第二种方式,将序列中的各个元素都打包为一个tuple中。因此称为tuple packing元组打包)。

声明一个空tuple

emptyTuple = () print(emptyTuple) print(type(emptyTuple))

声明一个只带有1个元素的tuple时,须在元素后面加上一个逗号,

tuple1 = (5,) print(tuple1) print(type(tuple1)) print(len(tuple1)) tuple2 = 5, print(tuple2) print(type(tuple2)) print(len(tuple2))

Dictionaris

dict是一种含有键、值的对象, 中文为字典

基本用法

aDict = { 'name': 'Mike', 'age': 25 } print(aDict) print(type(aDict))

上面,当键的数据类型为字符串时,需显式地使用字符串字面符。这一点与JavaScript不同。作为对比,JavaScript的代码如下:

let obj = { name: 'Mike', age: 25 } pc.log(obj); pc.log(obj.name); pc.log(obj['name']);

使用[]操作符来访问dict的键值。但不能使用.操作符。

aDict = { 'name': 'Mike', 'age': 25 } print(aDict['name'], aDict['age']) # the following wouldn't work # print(aDict.name) # print(aDict.'name')

可以在声明dict后,动态地添加或删除键值对。

aDict = { 'name': 'Mike', 'age': 25 } aDict['gender'] = 'male' del aDict['age'] print(aDict)

可以设置为键的数据类型

键的类型为不可修改 (immutable) 的类型。因此字符串与数字 (numbers) 可以设置为键。

aDict = { 1: 5, 2: 10, 3: 15 } print(aDict) print(aDict[1], aDict[2], aDict[3])

tuple如果只包含字符串、数字、或tuple时,则该tuple可以设为键。

aDict = { (1, 2): 5, ('a', 'b'): 10, (1, 'a'): 15, ((1, 2), (3, 4)): 20 } print(aDict)

list因是可改写的,因此不能成为dict的键名。

与键相关的函数与操作符

可对dict调用list函数,返回由dict的键名组成的list

aDict = { 'Tom': 15, 'Mike': 20, 'John': 25 } print(list(aDict))

dict调用len函数,返回dict的键值对的数量。

aDict = { 'Tom': 15, 'Mike': 20, 'John': 25 } print(len(aDict))

dict调用sorted函数,返回经排序的由dict的键名组成的list

aDict = { 'Tom': 15, 'Mike': 20, 'John': 25 } print(sorted(aDict))

in操作符用于判断dict中是否存在特定键名。

aDict = { 'Tom': 15, 'Mike': 20, 'John': 25 } print('Mike' in aDict)

构造器

dict构造函数用以创建dict实例。参数数量为1个,类型为可遍历对象 (iterable)。

aDict = dict([ ('a', 5), ('b', 10) ]) print(aDict)

上面使用一个list作为构造函数的参数,则此list中每个元素都用于设置dict的键名与键值。

每个元素都使用tuple的数据类型,且tuple的每个元素数量均为2

由于listtuple均属于可遍历对象,因此上面构造函数的参数中,里外两层都可以随意使用这两种数据类型。

当键名类型为字符串时,可使用关键字参数 (keyword arguments) 的方式。

week = dict(monday=1, tuesday=2, wednsday=3) print(week)

可使用以下代码来创建一个dict实例。

aDict = {x: x**2 for x in [1, 2, 3, 4, 5]} print(aDict)

这种方式,称为dict comprehensions

遍历

使用for语句遍历一个dict时,每次返回其键名。

week = dict(monday=1, tuesday=2, wednsday=3) for keyName in week: print(f'{keyName}: {week[keyName]}')

可显式地调用dictkeys方法,以供遍历。

week = dict(monday=1, tuesday=2, wednsday=3) for keyName in week.keys(): print(f'{keyName}: {week[keyName]}')

可调用dictitems方法,返回一个dict_items的对象。

week = dict(monday=1, tuesday=2, wednsday=3) items = week.items() print(items) print(type(items))

外层为list,里层为由键名值对所构成的tuple

使用for语句遍历该对象:

week = dict(monday=1, tuesday=2, wednsday=3) maxLen = len(max(list(week))) for key, value in week.items(): print('{:>{}}: {}'.format(key, maxLen, value))

可调用dictvalues方法,返回键值序列。然后调用zip函数以依序创建各个键的名值对序列,以供遍历。

week = dict(monday=1, tuesday=2, wednsday=3) keys = week.keys() values = week.values() seq = zip(keys, values) print(type(seq)) maxLen = len(max(keys)) for key, value in seq: print(f'{key:>{maxLen}}: {value}')

in操作符

当对dict使用in操作符时,其效果是判断dict是否存在特定的键名。

week = dict(monday=1, tuesday=2, wednsday=3) print('monday' in week);

等同于下面显式调用keys方法的代码:

week = dict(monday=1, tuesday=2, wednsday=3) print('monday' in week.keys());

若要判断dict是否含有特定的键值,可显式地调用values方法:

week = dict(monday=1, tuesday=2, wednsday=3) print(3 in week.values());

参考资源

  1. Dictionaries

流程控制语句

不能用{}来构成一个语句块。相反,在语句块开始的地方使用:来声明语句块开始,下面紧随的各行,只要有右缩进,则视为语句块内的内容;取消右缩进来结束语句块的声明。

if语句

num = 10 if num < 50: print('small num') elif num == 50: print('right equal 50') else: print('big num')

如果整个语句块只有1条语句,可将这条语句写在同一行上。

num = 10 if num == 10: print('ten')

布尔值分别为TrueFalse

fast = True if fast == True: print('The speed is fast.') else: print('The speed is slow.')

在测试布尔值时,可使用is操作符来代替==操作符。

fast = True if fast is True: print('The speed is fast.') else: print('The speed is slow.')

使用布尔操作符and, or, not来构建复合条件语句。

speed = 50 isNeedLimitSpeed = True if isNeedLimitSpeed and speed >= 50: speed -= 10 print(speed)

or操作符有短路功能。各表达式从左到右,如果左边的表达先返回True,则后续表达式不再被执行。

x = 10 y = 20 def evalExpr(): print('...in evalExpr()') return y > 20 print(x > 5 or evalExpr())

上面,or操作符的左边表达式返回True,则不管右边表达式为True还是False,均不影响or的运算结果。因此,右边表达式将不被执行。

布尔操作符有以下权重优先次序:not > and > or。权重大的操作符优先执行。

x = 10 y = 20 print(x > 5 or not y < 20)

上面代码,先执行not y < 20,返回True,再执行x > 5 or True,最后结果为True

x = 10 y = 20 z = 30 print(x > 5 or y < 20 and not z == 3)

执行次序:

  1. let value = not z == 3
  2. let value = y < 20 and value
  3. let value = x > 5 or value

但一般情况下,我们无需记住这些操作符的权重次序,直接使用括号(...)即可。

x = 10 y = 20 z = 30 print( x > 5 or (y < 20 and (not z == 3)) )

布尔表达式可以形成一个链式比较 (chained comparison)。下面先使用and操作符来判断一个数值是否在特定值域内:

x = 10 print(x >= 5 and x<= 20)

使用链式比较,则可改写为:

x = 10 print(5 <= x <= 20)

JavaScript同样支持这种语法特性:

x = 10 pc.log(5 <= x <= 20)

可以通过三元运算符,将一条if ... else语句写成一行语句:

num = 3 # ternary operator # like (condition ? ifTrue : ifFalse) in JavaScript result = 'small' if num < 10 else 'big' print(result)

for语句

遍历各种对象

使用for语句以遍历可遍历的对象。

遍历str

for c in 'Python': print(c)

遍历range

for i in range(1, 6): print(i)

遍历list

words = ['one', 'two', 'three'] for item in words: print(item)

遍历list时若需要访问索引值,可对list对象依序调用lenrange函数,以生成索引序列值。

words = ['one', 'two', 'three'] for index in range(len(words)): print('{0}: {1}'.format(index, words[index]))

遍历dict

user = { 'name': 'Mike', 'id': 3, 'age': 15 } for key, value in user.items(): print(key, value)

流程流转控制

使用continue语句来跳过本轮遍历。

for i in range(1, 6): if i % 2 == 0: continue print(i)

使用break语句来中止遍历。

for i in range(1, 10): print(i) if i >= 3: break

经常有这种情况:在遍历过程中当找到特定元素时,调用break来中止遍历;而搜索全体元素后如果找不到,我们需要额外设置一个状态变量并在遍历完成后来检查它。下面是相应的JavaScript代码:

let arr = [7, 9, 3, 5]; let isFound = false; for (let item of arr) { if (item % 2 === 0) { isFound = true; break; } } if (isFound) { pc.log('find an even number.'); } else { pc.log('Not an even number is found.'); }

而在Python中的for语句中,我们可以使用一个else语句来实现此目标。

arr = [7, 9, 3, 5]; for num in arr: if num % 2 == 0: print('find an even number.') break else: print('Not an even number is found.')

Python的逻辑是:所有遍历完成后,如果break语句未被执行到,则执行else语句块。Python真的很体贴程序员啊。

在编写格式上,这种else须与for相对齐。

while语句

while语句中,只要条件为True,则继续执行。

index = 1; aList = [] while index <= 10: aList.append(index) index += 1 print([x**2 for x in aList])

需注意的是,Python没有++运算符, 因此可用+=代替。

while语句同样存在else语句:

index = 1; while index <= 5: print(index) if index == 15: break index += 1 else: print('no breaking')

同样,所有遍历完成后,如果break语句未被执行到,则执行else语句块。

match语句

基本形式:

num = 4 match(num): case 1: print('one') case 2 | 3: print('two or three') case 5: print('five') case _: print('others')

函数

def sum(a, b): return a + b print(3, 5)

更多细节,详见函数

参考资源

Python Docs

  1. Python.org
  2. The Python Language Reference
  3. The Python Tutorial
  4. The Python Standard Library
  5. Python Built-in Types
  6. Python Built-in Functions
  7. Python BeginnersGuide
  8. PEP 636 – Structural Pattern Matching: Tutorial
  9. pypi.org

Python IDE

  1. jetbrains.com
  2. PyCharm
  3. PyCharm Getting started

Others

  1. Anaconda
  2. Jupyter
  3. Matplotlib
  4. SciPy
  5. scikit-learn