在入门 Python 语言前,我们需要了解 Python 的语言基础,这些工作就像我们学英文的 26 个字母一样。
如果某个数的数值超出了某一个数值范围就称为“溢出”。
如果用一个字节表示整数,则能表示的最大正整数为 01111111
(最高位为符号位),即最大值为127,若数值 > 127,则“溢出”。
例如:128就溢出了。
一个Python程序由1个或多个模块构成,每个模块是一个源文件(文件后缀名:.py
)。模块由语句组成。
语句是程序的过程构造块,用于创建对象,给变量赋值,调用函数,控制分支,建立循环等。语句包含表达式。
用于创建和处理对象。
数据表示为对象,程序处理的一切皆为对象。
Python中有许多内置对象可供编程者使用,内置对象可直接使用。
例如,数字、字符串、列表、del、eval等。
对象类型 | 类型名称 | 示例 | 简要说明 |
---|---|---|---|
数字 | int | 123 | 数字大小没有限制,内置支持复数及其运算 |
数字 | float | 3.14, 1.3e5 | 数字大小没有限制,内置支持复数及其运算 |
数字 | complex | 3+4j | 数字大小没有限制,内置支持复数及其运算 |
字符串 | str | ‘python’, “I’m student”, ‘’‘Python ‘’’,r’abc’, R’abc’ | 使用单引号、双引号、三引号作为定界符,以字母r或R引导的表示原始字符串 |
字节串 | bytes | b’hello world’ | 以字母b引导,可以使用单引号、双引号、三引号作为定界符 |
列表 | list | [1, 2, 3]、[‘a’, ‘b’, [‘c’, 2]] | 所有元素放在一对方括号中,元素之间使用逗号分隔,其中的元素可以是任意类型 |
字典 | dict | {‘张三’: 90, ‘李四’: 60, ‘王五’: 100, ‘赵六’: 50} | 所有元素放在一对大括号中,元素之间使用逗号分隔,元素形式为“键:值” |
元组 | tuple | (1,)、(-5, 7, 0) | 不可变,所有元素放在一对圆括号中,元素之间使用逗号分隔,如果元组中只有一个元素的话,后面的逗号不能省略 |
集合 | set、frozenset | {‘a’, ‘b’, ‘c’} | 所有元素放在一对大括号中,元素之间使用逗号分隔,元素不允许重复;另外,set 是可变的,而 frozenset 是不可变的 |
布尔型 | bool | True, False | 逻辑值,关系运算符、成员测试运算符、同一性测试运算符组成的表达式的值一般为True或False |
空类型 | NoneType | None | 空值 |
异常 | Exception、ValueError、TypeError | Python内置大量异常类,分别对应不同类型的异常 | |
文件 | f = open(‘data.txt’, ‘rb’) | open是Python内置函数,使用指定的模式打开文件,返回文件对象 | |
其他可迭代对象 | 生成器对象、range对象、zip对象、enumerate对象、map对象、filter对象等等 | 具有惰性求值的特点,除range对象之外,其他对象中的元素只能看一次 | |
编程单元 | 函数(使用 def 定义)、类(使用 class 定义)、模块(类型为 module ) |
类和函数都属于可调用对象,模块用来集中存放函数、类、常量或其他对象 |
需要导入模块才能使用。
例如,import math
例如,绝对值函数 abs,随机数产生函数 random 等。
标识(identity)用于唯一标识一个对象,通常对应于对象在计算机内存中的位置。使用内置函数id(obj1)可返回对象obj1的标识;
通过内置的id()函数,可以获取一个对象唯一的id标识(CPython的实现为内存存放位置)。
查看对象:
>>> id(1) # 数字 1 在计算机中的内存位置(结果不唯一)
140703752119080
查看内置函数对象:
>>> id(abs)
2357439994176
>>> id(range)
140703750650880
类型(type)用于表示对象所属的数据类型(类),数据类型(类)用于限定对象的取值范围,以及允许执行的处理操作。使用内置函数type(obj1)可以返回对象obj1所属的数据类型;
通过内置的type()函数,可以判断一个对象的类型。
查看对象:
>>> type(1)
<class 'int'>
查看内置函数对象:
>>> type(abs)
<class 'builtin_function_or_method'>
>>> type(range)
<class 'type'>
>>> print(1)
1
使用字面量创建实例对象:
>>> 123456
123456
>>> "abcd"
'abcd'
使用类对象创建实例对象:
>>> float(12)
12.0
>>> int(12.56)
12
>>> complex(2, 3)
(2+3j)
标识符是指在程序书写中程序员为一些特定对象的命名,包括变量、函数、类、模块和其他对象的名称。
a
和 A
不同)。例如:
类型 | 命名规则 | 举例 |
---|---|---|
模块/包名 | 全小写字母,简单有意义,如果需要可以使用下画线 | math、os、sys |
函数名 | 全小写字母,可以使用下画线增加可阅读性 | my_func()、spider() |
变量名 | 全小写字母,可以使用下画线增加可阅读性 | age、celebrity |
类名 | 采用 PascalCase 命名规则,即多个单词组成名称,每个单词除第一个字母大写外,其余的字母均小写 |
MyClass |
常量名 | 全大写字母,可以使用下画线增加可阅读性 | PI、TAX_RATE |
__init__
为类的构造函数,一般应避免使用;关键字是预定义的保留的标识符,也称为保留字。
注:关键字不能在程序中用作标识符,否则会产生编译错误
Python 3.11
有 35
个关键字,我们使用Python帮助系统查看关键字:
help()
>>> help()
Welcome to Python 3.11's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the internet at https://docs.python.org/3.11/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
keywords
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
关键字 help
除了上面那样输出 Python 的所有关键字外,还能查看每个关键字的简介,如下:
查看 if
:
help> if
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.
Related help topics: TRUTHVALUE
查看 for
:
help> for
The "for" statement
*******************
The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
for_stmt ::= "for" target_list "in" starred_list ":" suite
["else" ":" suite]
The "starred_list" expression is evaluated once; it should yield an
*iterable* object. An *iterator* is created for that iterable. The
first item provided by the iterator is then assigned to the target
list using the standard rules for assignments (see Assignment
statements), and the suite is executed. This repeats for each item
provided by the iterator. When the iterator is exhausted, the suite
in the "else" clause, if present, is executed, and the loop
terminates.
A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite. A "continue" statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the "else" clause if there is no next
item.
The for-loop makes assignments to the variables in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:
for i in range(10):
print(i)
i = 5 # this will not affect the for-loop
# because i will be overwritten with the next
# index in the range
Names in the target list are not deleted when the loop is finished,
but if the sequence is empty, they will not have been assigned to at
all by the loop. Hint: the built-in type "range()" represents
immutable arithmetic sequences of integers. For instance, iterating
"range(3)" successively yields 0, 1, and then 2.
Changed in version 3.11: Starred elements are now allowed in the
expression list.
Related help topics: break, continue, while
使用 quit
退出 help
:
help> quit
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
这些数据是不会改变的,也称为字面常量。
例如,整数389,浮点数23.56,字符串'hello',
但是 Python 语言不支持常量,即没有语法规则限制改变一个常量的值。
Python语言使用约定,声明在程序运行过程中不会改变的变量为常量,通常使用全大写字母(可以使用下划线增加可阅读性)表示常量名。
>>> PI = 3.1415 # 浮点类型常量PI
>>> WHU = '武汉大学' # 字符型常量WHU
将数据存储在内存中,然后用一个名称来引用内存空间,这个名称称为变量,其值是可以变化的。
变量名 = 值 / 表达式
变量的声明和赋值示例:
>>> x=0; y=0; z=0 # 变量x、y和z均指向int对象0
>>> s1 = "123" #变量s1指向值为"123"的str型实例对象
>>> s2 #变量s2未声明和定义(NameError: name 's2' is not defined)
Traceback (most recent call last):
File "" , line 1, in <module>
NameError: name 's2' is not defined. Did you mean: 's1'?
链式赋值:
链式赋值用于为多个变量赋值同一个值。
>>> x = y = z = 1 # 变量x、y和z均指向int对象1
>>> x
1
>>> y
1
>>> z
1
复合赋值:
运算符 | 含义 | 例子 | 等价于 |
---|---|---|---|
+= | 加法 | sum += i | sum = sum + i |
+= | 字符串拼接 | str += “abc” | str = str + “abc” |
-= | 减法 | cnt -= 1 | cnt = cnt - 1 |
*= | 乘法 | x *= y+1 | x = x * (y+1) |
/= | 除法 | x /= y+1 | x = x / (y+1) |
//= | 整除 | x /= y+1 | x = x // (y+1) |
%= | 取模 | x %= 2023 | x = x % 2023 |
**= | 幂运算 | x **= 2023 | x = x ** 2023 |
<<= | 左移 | x <<= y | x = x << y |
>>= | 右移 | x >>= y | x = x >> y |
&= | 按位与 | x &= y | x = x & y |
= | 按位或 | x | = y |
^= | 按位异与 | x ^= y | x = x ^ y |
>>> i = 1 # 变量i指向int对象1
>>> i += 1 # 先计算表达式i+1的值,然后创建一个值为2的int对象,并绑定到变量i
>>> i
2
>>> i *= 3 # 先计算表达式i*3的值,然后创建一个值为6的int对象,并绑定到变量i
>>> i
6
del
语句删除不再使用的变量。
>>> x = 2023 # 变量x指向int对象2023
>>> del x # 删除变量x
>>> x # 变量x未声明和定义
Traceback (most recent call last):
File "" , line 1, in <module>
NameError: name 'x' is not defined
将系列数据类型解包为对应相同个数的变量。
>>> x, y = 1, 2 # 变量x指向int对象1,变量y指向int对象2
>>> x
1
>>> y
2
如果只需要解包部分值,则可以采用特殊变量 “_”:
>>> _, age, hobby, _ = ['小邓在森林', 18, "篮球", '2023-11-25']
>>> age
18
>>> hobby
'篮球'
使用系列解包实现变量交换:
以前我们交换两个数据可能是这么写的:
# 交换 a 和 b
temp = a
a = b
b = temp
现在用 Python 可以这么写:
>>> a, b = (1, 2) # 变量a指向int对象1,变量b指向int对象2
>>> a, b = b, a # 两个变量a和b的值进行交换
>>> a
2
>>> b
1
表达式:
表达式的组成
表达式的书写规则
运算符:
Python是动态类型语言。
对于数字 2023:
>>> type(2023)
<class 'int'>
>>> id(2023)
2357439544976
>>> a = 2023
>>> id(a)
2357447026320
>>> b = 2023
>>> id(b)
2357447026288
>>> c = a
>>> id(c)
2357447026320
对于数字 10:
>>> type(10)
<class 'int'>
>>> id(10)
140703752119368
>>> a = 10
>>> id(a)
140703752119368
>>> b = 10
>>> id(b)
140703752119368
>>> c = a
>>> id(c)
140703752119368
可见对于小的数字(10),它是存放在一个固定的内存位置的;而较大的数字(2023)则是随机存放!
对于字符串 ‘abc’:
>>> id('abc')
140703750754080
>>> a = 'abc'
>>> id(a)
140703750754080
对于声明的字符串,它是存放在一个固定的内存位置的。
Python是强类型语言。
>>> a = 1 # a指向值为1的int型实例对象
>>> b = '1' # b指向值为"1"的str型实例对象
>>> a + b # 错误:int型和str型对象不能直接相加,即str型对象不能自动转换为int型对象
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> b = 1 # 赋值语句:b指向值为1的int型实例对象
>>> a + b # 表达式运算结果,返回值为2的int型实例对象
2
对象的值比较(==
)
== 运算符判断两个变量指向的对象的值是否相同。
引用判别(is
)
is运算符判断两个变量是否指向同一对象。
对象操作示例:
>>> x = '123'
>>> y = x
>>> z = '1234'
>>> x == y
True
>>> x is y
True
>>> x == z
False
>>> x is z
False
不可变对象一旦创建,其值就不能被修改,例如:int、str、complex等。
>>> a = 20
>>> id(a)
140703752119688
>>> a = 23
>>> id(a)
140703752119784
>>> b = 23
>>> id(b)
140703752119784
>>> id(23)
140703752119784
可变对象的值可以被修改。Python对象的可变性取决于其数据类型的设计,即是否允许改变其值。
>>> x = y = [1, 2, 3] # 变量x和y指向list对象[1, 2, 3]
>>> id(x) # 输出:2357441373696。表示变量x指向的list对象[1, 2, 3]的id
2357441373696
>>> id(y) # 输出:2357441373696。表示变量y指向的list对象[1, 2, 3]的id
2357441373696
>>> x.append(4) # 变量x指向的list对象[1, 2, 3]附加一个元素4
>>> x # 输出:[1, 2, 3, 4]。表示变量x指向的list对象[1, 2, 3, 4]
[1, 2, 3, 4]
>>> id(x) # 输出:2357441373696。变量x指向的list对象[1, 2, 3, 4]的id未改变
2357441373696
>>> x is y # 输出:True。表示变量x和y指向同一个list对象[1, 2, 3, 4]
True
>>> x == y # 输出:True。表示变量x和y指向的list对象值相等
True
>>> z = [1, 2, 3, 4] # 变量z指向的list对象[1, 2, 3, 4]
>>> id(z) # 输出:2357446628672。表示变量z指向的list对象[1, 2, 3, 4]的id
2357446628672
>>> x is z # 输出:False。表示变量x和z指向不同的list对象[1, 2, 3, 4]
False
>>> x == z # 输出:True。表示变量x和z指向的list对象值相等
True
语句是Python程序的过程构造块,用于定义函数、定义类、创建对象、变量赋值、调用函数、控制分支、创建循环等。
Python语句分为简单语句和复合语句。
简单语句包括:
复合语句包括:
Python语句的书写规则:
# 这里是注释
# 长注释方式 1:
'''
用 3 个单引号写的注释
'''
# 长注释方式 2:
"""
用 3 个双引号写的注释
"""
函数是可以重复调用的代码块。
(1)定义函数时,可以声明函数的参数,即形式参数,简称形参。
(2)调用函数时,需要提供函数需要的参数的值,即实际参数,简称实参。
(3)函数可以有返回值,即计算结果。
Python语言提供了海量的内置函数、标准库函数、第三方模块函数。
(1)内置函数,例如dir()、type()、id()、help()、len()等。
(2)标准库函数,例如math库的sqrt()。
(3)第三方模块函数,例如Pandas库中的DataFrame。
模块函数
(1)通过import语句,可以导入模块module,然后使用module.function(arguments)的形式调用模块中的函数。
(2)每个import语句只导入一个模块,最好按标准库、扩展库、自定义库的顺序依次导入。
上一篇文章:【人生苦短,我学 Python】(1)初识 Python
下一篇文章:【人生苦短,我学 Python】(3)Python 常用内置数据类型 I —— 数值数据类型(int、float、complex、bool)