Python语言的特点
和shell脚本相比,shell 脚本擅长的是移动文件和改变文本数据,而不适合编写 GUI 应用或游戏。和C/C++/Java 相比,但即使只完成一个初始版的C/C++/Java程序也需要耗费很长的开发时间,而Python 则更为简单易用。
Python是真正的编程语言,提供了大量的数据结构,也支持开发大型程序,远超 shell 脚本或批处理文件;Python 提供的错误检查比 C 还多;作为一种“非常高级的语言”,它内置了灵活的数组与字典等高级数据类型。
Python 支持把程序分割为模块,以便在其他 Python 程序中复用。它还内置了大量标准模块,作为开发程序的基础 。
Python 是一种解释型语言,不需要编译和链接。
Python使用缩进,而不是括号实现代码块分组,无需预声明变量或参数。
Python 解释器
调用解释器
在linux/unix环境下, 可以使用命令
whereis python
查看python解释器的路径。在笔者使用的一台服务器上,显示结果如下:
python: /usr/bin/python /usr/bin/python3.8 /usr/bin/python3.8-config /usr/bin/python2.7-config /usr/bin/python2.7 /usr/bin/python3.6 /usr/bin/python 3.6m /usr/lib/python3.8 /usr/lib/python2.7 /usr/lib/python3.6 /usr/lib/python3.7 /etc/python3.8 /etc/python /etc/python2.7 /etc/python3.6 /usr/local /lib/python3.8 /usr/local/lib/python2.7 /usr/local/lib/python3.6 /usr/include/python3.8 /usr/include/python2.7 /usr/share/python
因为服务器已经安装好了python解释器,因此只需要命令:
python3.12
,便可以启动python解释器。直接敲python代码print("hello world"),然后回车,可以看到该语句可以被执行。
Python 3.8.16 (default, Dec 7 2022, 01:12:13)
[GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello world")
hello world
在 Windows 机器上可以从 Microsoft Store 安装 Python ,笔者的电脑上已经安装了python
可以直接点击这个,打开解释器。同样输出上述打印语句,可以执行
Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello world")
Hello world
上述打开解释器后进入的模式称为“交互模式”(interactive mode)。在这种模式中,会显示 主提示符,提示输入下一条指令。主提示符通常用三个大于号(>>>
)表示;输入连续行时,显示 次要提示符,默认是三个点(...
)。进入解释器时,首先显示欢迎信息、版本信息、版权声明,然后才是提示符。
例如,在下面的例子中,当输入if语句时,会认为时连续行,从而回车后,会自动使用(...)的次要提示符
>>> the_world_is_flat = True
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
Be careful not to fall off!
>>>
Python 速览
Python 注释以#开头,直到该物理行结束。
Python 用作计算器
数字
运算符+ - * /,以及圆括号(),和c语言的定义一样。
整数(如,2
、4
、20
)的类型是int,带小数(如,5.0
、1.6
)的类型是float。
除法运算 (/
) 总是返回浮点数,这点和c语言不一样。 如果要做一个向下取整的除法(c语言中的整数除法)得到一个整数结果你可以使用 //
运算符;要计算余数你可以使用 %
:
>>> 17 // 3
5
>>> 17 / 3
5.666666666666667
>>> 17 % 3
2
Python 用 **
运算符计算乘方
>>> 5 ** 2
25
交互模式下,上次输出的表达式会赋给变量 _
。把 Python 当作计算器时,用该变量实现下一步计算更简单,例如:
>>> tax=12.5/100
>>> price=100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>
除了 int 和 float,Python 还支持其他数字类型,例如 Decimal 或 Fraction。Python 还内置支持 复数,后缀 j
或 J
用于表示虚数(例如 3+5j
)
文本
字符串可以用成对的单引号 ('...'
) 或双引号 ("..."
) 来标示,结果完全相同。而要标示引号本身,我们需要对它进行“转义”,即在前面加一个 \
。 或者,我们也可以使用不同类型的引号:
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
print() 函数会略去标示用的引号,并打印经过转义的特殊字符,产生更为易读的输出。
如果不希望前置 \
的字符转义成特殊字符,可以使用 原始字符串,在引号前添加 r
即可:
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
使用三重引号:"""..."""
或 '''...'''
可以使字符串字面值可以包含多行
>>> print("""\
... Usage: thingy [OPTIONS]
... -h Display this usage message
... -H hostname Hostname to connect to
... """)
字符串可以用 +
合并(粘到一起),也可以用 *
重复:
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
相邻的两个或多个 字符串字面值 (引号标注的字符)会自动合并
>>> 'Py' 'thon'
'Python'
该功能常用于拼接分隔开的长字符串。这项功能只能用于两个字面值,不能用于变量或表达式。合并多个变量,或合并变量与字面值,要用 +。
Python没有专用的单字符类型,就是长度为一的字符串。
字符串可以用索引访问某个单一的字符。索引支持负数,用负数索引时,从右边开始计数:
>>> word = 'Python'
>>> word[-1] # last character
'n'
字符串支持索引切片。注意,输出结果包含切片开始,但不包含切片结束。因此,s[:i] + s[i:]
总是等于 s
:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[:2] + word[2:]
'Python'
索引越界会报错。但是,切片会自动处理越界索引:
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[4:42]
'on'
>>> word[42:]
''
注意,Python 字符串不能修改,是 immutable 的。因此,为字符串中某个索引位置赋值会报错
>>> word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
内置函数 len() 返回字符串的长度。
列表
Python 支持多种 复合 数据类型,可将不同值组合在一起。最常用的 列表 ,是用方括号标注,逗号分隔的一组值。列表 可以包含不同类型的元素,但一般情况下,各个元素的类型相同。
和字符串(及其他内置 sequence 类型)一样,列表也支持索引和切片。
>>> squares = [1, 4, 9, 16, 25]
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
以下切片操作会返回列表的 浅拷贝:
>>> squares[:]
[1, 4, 9, 16, 25]
与字符串不同, 列表是 mutable 类型,其内容可以改变。
可以在通过使用 list.append()
方法,在列表末尾添加新条目。
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> cubes[3] = 64 # replace the wrong value
>>> cubes.append(216) # add the cube of 6
>>> cubes
[1, 8, 27, 64, 125, 216]
为切片赋值可以改变列表大小,甚至清空整个列表
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E'] # replace some values
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = [] # remove some values
>>> letters
['a', 'b', 'f', 'g']
>>> letters[:] = [] # clear the whole list
>>> letters
[]
内置函数 len() 也支持列表。
还可以嵌套列表(创建包含其他列表的列表),有点像C中的多重数组
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[1]
[1, 2, 3]
>>> x[0][1]
'b'
走向编程的第一步
下面的例子给出了一个斐波那契数列的小程序
>>> # Fibonacci series:
>>> # the sum of two elements defines the next
>>> a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8
注意:
- 多重赋值:第一行和最后一行都是用了这种赋值形式。
- 比较操作符的写法和 C 语言一样:
<
(小于)、>
(大于)、==
(等于)、<=
(小于等于)、>=
(大于等于)及!=
(不等于) - 循环体是缩进的,而不需要括号