探究
实验室
计算
公开
Python基础语法(2025版)
notebook
python
Tutorial
notebookpythonTutorial
陈乐天 Letian Chen
爱学习的王一博
更新于 2025-05-12
推荐镜像 :Basic Image:bohrium-notebook:2023-04-07
推荐机型 :c2_m4_cpu
赞 8
48
22
Python 基础 1:基础语法
注释
缩进规则
标准输出
格式化输出
标准输入
练习
Python 基础 2:基本数据类型
变量赋值
基础类型
字符串(str)
布尔型(bool)
整型(int)
浮点型(float)
复数(complex)
字符串类型的处理
序列(sequence)
创建列表
索引
更新列表
删除列表元素
把元素插入到指定的位置
切片和拼接
嵌套列表
元组(tuple)
集合(set)
字典(dictionary)
练习
Python 基础 3:运算符
基本运算符
逻辑运算符
运算符实例
1. 判断输入数的奇偶
2. 判断是否为闰年
3. 练习
Python 基础 4:流程控制
什么是流程控制
分类
4.1 if语句
4.1.1 语法
4.1.2 示例
4.1.3 练习
4.2 while循环
4.2.1 语法
4.2.2 示例
4.2.3 练习
4.3 for循环
4.3.1 语法
4.3.2 示例
关于range()
4.3.3 练习
其他流程控制关键词
break
continue
pass
4.4 列表推导式
Python 基础 5:函数
什么是函数(function)?
函数的作用
定义一个普通函数
语法
函数调用
函数的默认参数
函数的位置参数
关键字参数
练习
帮助函数(help)
函数进阶
Python 基础 6:类
什么是类(class)?
类的作用
实例1. “小狗”
实例2. “圆形”
练习

©️ Copyright 2023 @ Authors
作者:斯坦福大厨 📨 何仁桀 📨 陈乐天 📨
更新日期:2023-11-9
共享协议:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
快速开始:点击上方的 开始连接 按钮,选择 Bohrium-notebook:2023-04-07 镜像及 c2_m4_cpu 节点配置,稍等片刻即可运行。

代码
文本

Python 基础 1:基础语法

Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言, 由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。

2020 年 1 月 1 日, Python 2 停止更新。Python 2.7 被确定为最后一个 Python 2.x 版本。 现在的主流 Python 版本为 Python 3.x。

注释

注释的主要作用是增强代码可读性和生成文档,Python解释器会忽略所有注释。

单行注释由任意数量的井号(#)开头,多行注释由三个双引号或三个单引号包围。

你知道吗?
Python 其实只有一种注释语法,即用#开头。因为 Python 会忽略未分配给变量的字符串,因此多行字符串可被用于多行注释。

例如在def函数的时候会使用两个三引号(''')夹住注释内容,python运行代码是会自动忽略掉如下字符串。

'''
第一行注释
第二行注释
第三行注释
'''
代码
文本
[63]
# 第一个注释
print("Hello, Python!") # 第二个注释
Hello, Python!
代码
文本

缩进规则

python 用强制缩进来区分代码层级.

建议使用四个空格来缩进代码,不建议使用制表符(不同终端对制表符的解释不同!)

代码
文本
[13]
# 利用缩进写if/else语句块,判断x与y大小
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
print("thanks!")
Enter a number for x:
Enter a number for y:
thanks!
代码
文本

标准输出

print() 在括号中加上字符串,就可以向屏幕上输出指定的文字。

print() 也可接受多个字符串,用“,”隔开。

字符串包含有单(双)引号,用双(单)引号表示即可。

代码
文本
[14]
print("This is python") # 字符串输出
print("This", "is", "python") # 多个字符串输出
print('“Hello” in “Quotes”') # 带引号的字符串输出
This is python
This is python
“Hello” in “Quotes”
代码
文本

print函数默认在输出后添加换行符。若不换行,需要在变量末尾加上end=""或其他非换行符字符串。

代码
文本
[15]
# 含变量的字符串输出
x = 11
print(x, end="**") # 字符串输出,以“***”结束
print("my fav num is", x) # 含变量的字符串输出
11**my fav num is 11
代码
文本

格式化输出

方法:

  1. 使用 str.format() 方法:
代码
文本
[16]
name = "Alice"
age = 20
print("My name is {}, and I'm {} years old.".format(name, age))
My name is Alice, and I'm 20 years old.
代码
文本
  1. 使用 f-string(Python 3.6+):
代码
文本
[17]
name = "Alice"
age = 20
print(f"My name is {name}, and I'm {age} years old.")
My name is Alice, and I'm 20 years old.
代码
文本

标准输入

input() 函数可读入用户输入内容,按字符串类型存储。

input() 函数可接受一个参数,表示输入时的提示信息。

代码
文本
[18]
# input函数的使用
text = input("Type anything... ")
print(type(text)) # 显示数据类型
num = int(input("Type a number... ")) # 强制转换为整数
print(type(num)) # 输入字符串
Type anything...
Type a number...
<class 'str'>
<class 'int'>
代码
文本
[19]
# 综合一下print和input
print("The area is ", 3.14159*float(input("What is your radius?"))**2)
What is your radius?
The area is  3.14159
代码
文本

练习

代码
文本
[12]
## 输入你的代码
代码
文本

Python 基础 2:基本数据类型

变量赋值

Python 中的变量不需要声明。

每个变量在使用前必须赋值,赋值以后该变量才会被创建。

在 Python 中,变量是个对象,没有类型;所谓“类型”是变量所指的内存中对象的类型

等号(=)用来给变量赋值

等号(=)运算符左边是一个变量名;等号(=)运算符右边是存储在变量中的值。

单个等号表示赋值, 如果要表示两变量相等,需要用双等号(==)。

  • !!!注意,python对大小写敏感,命名变量的时候需要区分大小写,并要避开下表中python程序的关键词。
代码
文本

基础类型

字符串(str)

用单引号或双引号表示,如 d = "Hello, world!"

布尔型(bool)

只有 True 和 False 两个值,表示真或假。

整型(int)

整数值

浮点型(float)

浮点型由整数部分与小数部分组成,科学计数法也属于浮点型(2.5e2 = 2.5×102 = 250)。
设置小数点保留位数 a = f"{原始浮点数:.保留位数f}"

复数(complex)

复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示,a 和 b 都是浮点型。

代码
文本
[20]
print(type(True), type(False), type(1), type(1.0), type(1 + 1j)) # 使用type函数输出数据类型
<class 'bool'> <class 'bool'> <class 'int'> <class 'float'> <class 'complex'>
代码
文本
[21]
print(float(1e3))
print(f'{float(1e3):.2f}')
1000.0
1000.00
代码
文本
[23]
a = 1
b = 2
print(a == b)
False
代码
文本

字符串类型的处理

双引号与单引号等价;字符串可通过 + 进行拼接。

代码
文本
[24]
hi = "hello there"
name = "Eric"
greet = hi + name
greeting = hi + " " + name
print(greet)
print(greeting)
hello thereEric
hello there Eric
代码
文本

字符串(string)可以进行索引、切片(与list类似),但不可部分赋值。

代码
文本
[25]
name = "Eric"
print(3 * name)
print(len(name))
print(name[1])
print(name[1:3])
EricEricEric
4
r
ri
代码
文本

序列(sequence)

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

包含列表(list),元组(tuple),集合(set)和字典(dict)

序列都可以进行的操作包括索引,切片,加,乘,检查。

列表的数据项不需要具有相同的类型。

代码
文本

创建列表

代码
文本
[77]
kobe_list = [2, 'Jump shot', 'Lakers','POR'] # 列表数据类型可以不同
print(kobe_list)
print(type(kobe_list))
[2, 'Jump shot', 'Lakers', 'POR']
<class 'list'>
代码
文本

索引

代码
文本

更新列表

列表中的元素是可以修改的(删除,替换,新增)

代码
文本
[78]
kobe_list = [2, 'Jump shot', 'Lakers', 'POR']
kobe_list[0] = 3
print(kobe_list)
[3, 'Jump shot', 'Lakers', 'POR']
代码
文本

删除列表元素

删除方式主要有3种

代码
文本
[ ]
kobe_list = [2, 'Jump shot', 'Lakers', 'POR']
del kobe_list[-2] # del 删除列表中某个元素
print(kobe_list)
[2, 'Jump shot', 'POR']
代码
文本
[80]
kobe_list = [2, 'Jump shot', 'Lakers', 'POR']
a = kobe_list.pop(-2) # pop去除列表中索引为-2的元素
print(a)
print(kobe_list)
Lakers
[2, 'Jump shot', 'POR']
代码
文本
[88]
kobe_list = [2, 'Jump shot', 'Lakers', 'POR']
b = kobe_list.remove(2) # remove 删除列表中第一个值为2的元素
print(b)
print(kobe_list)
None
['Jump shot', 'Lakers', 'POR']
代码
文本

把元素插入到指定的位置

代码
文本
[26]
kobe_list = [2, 'Jump shot', 'Lakers', 'POR']
kobe_list.insert(2, 'Win') # 添加新元素
print(kobe_list)
[2, 'Jump shot', 'Win', 'Lakers', 'POR']
代码
文本

切片和拼接

切片规则可以理解为数学区间中的前闭后开 [ )区间,也就是取左不取右。

代码
文本
[94]
kobe_list = ['Lakers', 'LAL @ POR', 'Jump shot', 'POR', 'Left Side(L)', '2000-10-31']
print(kobe_list[:-2])
print(kobe_list[:]) # 打印全部内容
print(kobe_list[::-1]) # 倒序输出
['Lakers', 'LAL @ POR', 'Jump shot', 'POR']
['Lakers', 'LAL @ POR', 'Jump shot', 'POR', 'Left Side(L)', '2000-10-31']
['2000-10-31', 'Left Side(L)', 'POR', 'Jump shot', 'LAL @ POR', 'Lakers']
代码
文本

嵌套列表

代码
文本

顾名思义,列表中的元素也可以是列表,并且可以通过多重索引搜索嵌套列表中的元素

代码
文本
[96]
nested_kobe_list = [['Lakers', 'LAL @ POR'], 'Jump shot']
print(nested_kobe_list[0][0])
Lakers
代码
文本

元组(tuple)

Python 的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。

代码
文本
[97]
tup = (1,2,(5,"name"))
print(tup)
print(type(tup))
(1, 2, (5, 'name'))
<class 'tuple'>
代码
文本

如果试图直接修改元组中的元素,就会报错;需要将元组转换成列表才能运行

代码
文本
[98]
tup[0] = 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[98], line 1
----> 1 tup[0] = 3

TypeError: 'tuple' object does not support item assignment
代码
文本
[99]
tup_list = list(tup)
tup_list[0] = 3
tup2 = tuple(tup_list)
print(tup2)
(3, 2, (5, 'name'))
代码
文本

集合(set)

set跟数学上的集合是一致的,不允许有重复元素,而且可以进行交集、并集、差集等运算。

代码
文本
[106]
# 创建集合
# 使用大括号 { } 或者 set() 函数
set1 = set("abracadabra")
set2 = {"a", "b", "c"}
print(set1, set2)

# 添加元素
set1.add("f")

# 移除元素
set1.remove("a")

# 数学运算
print(set1 & set2) # 交集
print(set1 | set2) # 并集
print(set1 - set2) # 差集
{'b', 'd', 'c', 'r', 'a'} {'c', 'b', 'a'}
{'c', 'b'}
{'c', 'f', 'b', 'r', 'd', 'a'}
{'d', 'f', 'r'}
代码
文本

字典(dictionary)

字典是另一种可变容器模型。与列表、集合不同的是,字典的每个元素都是由一个键和一个值组成的“键值对”,键和值通过冒号分开。

键必须是唯一的,但值则不必,值可以取任何数据类型,但键必须是不可变的,如字符串,数字,元组。

代码
文本
[111]
dict1 = {"key1": 0, "key2": 1, "key3": (2, 3)}
print(dict1)

# 访问字典里的值
print(dict1["key1"])

# 更新字典中的元素
dict1["key2"] = 10
print(dict1)

# 删除字典中的元素
del dict1["key3"]
print(dict1)
{'key1': 0, 'key2': 1, 'key3': (2, 3)}
0
{'key1': 0, 'key2': 10, 'key3': (2, 3)}
{'key1': 0, 'key2': 10}
代码
文本

练习

代码
文本
[11]
## 输入你的代码
代码
文本

Python 基础 3:运算符

代码
文本

基本运算符

算数运算符 比较运算符 赋值运算符
+加 ==等于 +=加法赋值
-减 !=不等于 -=减法赋值
*乘 >大于 *=乘法赋值
/除 <小于 /=除法赋值
//整除 >=大于等于 //=整除赋值
%取余 <=小于等于 %=取余赋值
**幂 **=幂赋值
代码
文本

逻辑运算符

运算符 逻辑表达式 描述
and x and y 如果两个操作数都为True,则返回True;否则返回False
or x or y 如果两个操作数中至少有一个为True,则返回True;如果两个操作数都为False,则返回False
not not x 用于取反操作,如果操作数为True,则返回False;如果操作数为False,则返回True
代码
文本

运算符实例

1. 判断输入数的奇偶

代码
文本
[115]
x = int(input("Enter an integer:"))
if x % 2 == 0:
print("Even")
else:
print("Odd")
Enter an integer: 5
Odd
代码
文本

2. 判断是否为闰年

闰年的计算方法是每4年一闰,但是每100年不闰,每400年又要闰。

闰年判定:能被400整除。或者能被4整除但不能被100整除。

代码
文本
[117]
year = int(input("Enter the year:"))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(year, " is leap year")
else:
print(year, "is not leap year")
Enter the year: 2400
2400  is leap year
代码
文本

3. 练习

代码
文本
[10]
## 输入你的代码
代码
文本

Python 基础 4:流程控制

代码
文本

什么是流程控制

在进行程序设计的时候,我们会经常进行逻辑判断,根据不同的结果做不同的事,或者重复做某件事,我们对类似这样的工作称为流程控制。

分类

  • 顺序控制
    从左到右,从上到下的顺序依次执行每条语句操作。

  • 条件控制(选择控制)
    基于条件选择执行语句,比方说,如果条件成立,则执行操作A,或者如果条件成立,则 执行操作A,反之则执行操作B。

  • 循环控制
    循环控制,又称为回路控制,根据循环初始条件和终结要求,执行循环体内的操作。

代码
文本

4.1 if语句

Python 中if语句的关键字为:if – elif – else

(elif = else if)

4.1.1 语法

if <条件1>:
    <语句1>
elif <条件2>:
    <语句2>
...
else:
    <语句n>
代码
文本

4.1.2 示例

代码
文本
[120]
x = float(input("x = "))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print(f"f({x}) = {y}")
x =  0
f(0.0) = 2.0
代码
文本

4.1.3 练习

代码
文本
[13]
# 添加代码
代码
文本

4.2 while循环

while 中的 else 是可选的,如果提供了 else 语句,则 else 语句一定执行。除非通过 break 语句退出循环。

4.2.1 语法

while <条件>:  
    #执行语句
 ...
[else:
    #执行语句
 ...]
代码
文本

4.2.2 示例

假如你在森林中迷路了,需要在路口选择左转(left)右转(right)

代码
文本
[122]
n = input("You are lost in a forest. Go left or right?")
while "right" == n:
n = input("You are lost in a forest. Go left or right?")
print("You got out of the forest!")
You are lost in a forest. Go left or right? right
You are lost in a forest. Go left or right? right
You are lost in a forest. Go left or right? right
You are lost in a forest. Go left or right? left
You got out of the forest!
代码
文本

4.2.3 练习

代码
文本
[ ]
# 添加代码
代码
文本

4.3 for循环

可遍历序列成员(字符串,列表,元组)。 可遍历任何可迭代对象(字典,文件等)。

4.3.1 语法

for <元素> in <序列>:
    #语句块
代码
文本

4.3.2 示例

代码
文本
[123]
# 计算0-100之间的奇数
sum = 0
for i in range(1, 100, 2):
sum += i
print("The sum of odd numbers from 0 to 100:", sum)
The sum of odd numbers from 0 to 100: 2500
代码
文本
[146]
# 判断字符串中是否有指定字母
s = "abcdefghiu"
for char in s: # 直接从字符串中取出元素
if 'i' == char or 'u' == char:
print("There is an i or u")
#else:
#print('Nothing')
There is an i or u
There is an i or u
代码
文本

关于range()

range(start, stop[, step]) 返回的是一个可遍历序列对象, 计数区间为 [start, stop), 两个数间隔(步长)为step

代码
文本
[27]
help(range)
已隐藏输出
代码
文本

4.3.3 练习

代码
文本
[14]
# 添加代码
代码
文本

其他流程控制关键词

break

用在for循环和while循环语句中。break语句是会立即退出循环,在其后边的循环代码不会被执行。

continue

使循环跳过其主体的剩余部分,并立即进入下一次循环。

pass

当语法需要但不需要执行任何命令或代码时,Python中就可以使用pass语句,此语句什么也不做,用于表示“占位”的代码。

代码
文本
[149]
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
continue
print(num)
print("-" * 9)

for num in numbers:
if num == 3:
break
print(num)
print("-" * 9)

for num in numbers:
if num == 3:
pass
print(num)
1
3
5
---------
1
2
---------
1
2
3
4
5
代码
文本

4.4 列表推导式

利用列表推导式能更简单的创建列表的方法,语法如下:

[表达式 for 迭代变量 in 可迭代对象 [if 条件表达式] ]

代码
文本
[151]
x = [1, 2, 3, 4, 5, 6]
out1 = [n ** 2 for n in x]
print(out1)

out2 = [n ** 2 for n in x if n % 2 == 0]
print(out2)
[1, 4, 9, 16, 25, 36]
[4, 16, 36]
代码
文本

Python 基础 5:函数

什么是函数(function)?

如果我们再开发程序的时候,某一段代码,需要执行很多次,但是为了提高编写的效率以及代码的复用,所以我们把这一段代码封装成一个模块,这个就是函数。

函数的作用

函数能提高应用的模块性,和代码的重复利用率。

注:Python提供了许多内置函数(built-in function),比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。

内置函数-Python官方文档

代码
文本

定义一个普通函数

语法

def 函数名(参数1,参数2,参数3....):
​    <函数体>
​    [<返回值>]

说明:

  1. 函数由两部分组成:声明部分和实现部分.
  2. 函数名:类似于变量名,尽量做到顾名思义.
  3. 参数1,参数2,参数3.... :参数列表【形式参数,简称为形参】,其实本质上就是一个变量名.
  4. 函数体:封装的功能代码.
  5. 返回值:一般用于结束函数,可有可无,如果有返回值,用return返回;如果没有返回值,则相当于返回None.
代码
文本

函数调用

要调用一个普通函数,需要知道函数的名称参数

代码
文本
[154]
def is_even(i): # 函数名和参数
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
return i % 2 == 0 # 函数体

print("", is_even(3)) # 函数调用
 False
代码
文本

函数的默认参数

函数的参数可以有一个默认值,默认参数以赋值语句的形式提供。

函数调用时如果没有提供这个参数, 它就取这个值做为默认值。

代码
文本
[155]
def my_abs(x=3):
if x >= 0:
return x
else:
return -x


print(my_abs())
print(my_abs(-4))
3
4
代码
文本

函数的位置参数

一个函数可以有多个参数,各个参数用逗号隔开。

在定义函数时有N个参数,在调用时,也需要提供N个参数。

代码
文本
[156]
def my_max(number1, number2):
if number1 > number2:
print(number1)
else:
print(number2)

my_max(4, 10)
10
代码
文本

关键字参数

如果在函数里面,定义了10个参数,输入时顺序需要一一对应,容易造成混乱。这时候,我们可以用关键字参数。使用关键字参数允许函数调用时参数的顺序与声明时不一致。

代码
文本
[159]
def my_hobby(name, hobby):
print("", name + " 喜欢 " + hobby)

my_hobby("DaChu", "Python")
my_hobby("Python", "DaChu")
my_hobby(hobby="Python", name="DaChu")
 DaChu 喜欢 Python
 Python 喜欢 DaChu
 DaChu 喜欢 Python
代码
文本

练习

代码
文本
[15]
# 添加代码
代码
文本

帮助函数(help)

在Python中,help()函数是一个内置函数,用于查看模块、类、函数、方法、关键字等的帮助文档。这个函数非常有用,尤其是当你想了解某个特定模块或函数的使用方法时。

下面是一个简单的代码示例,展示了如何使用help()函数:

代码
文本
[2]
# 导入一个模块,例如math模块
import math

# 使用help函数查看math模块的帮助文档
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.8/library/math
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to the mathematical functions
    defined by the C standard.

FUNCTIONS
    acos(x, /)
        Return the arc cosine (measured in radians) of x.
    
    acosh(x, /)
        Return the inverse hyperbolic cosine of x.
    
    asin(x, /)
        Return the arc sine (measured in radians) of x.
    
    asinh(x, /)
        Return the inverse hyperbolic sine of x.
    
    atan(x, /)
        Return the arc tangent (measured in radians) of x.
    
    atan2(y, x, /)
        Return the arc tangent (measured in radians) of y/x.
        
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(x, /)
        Return the inverse hyperbolic tangent of x.
    
    ceil(x, /)
        Return the ceiling of x as an Integral.
        
        This is the smallest integer >= x.
    
    comb(n, k, /)
        Number of ways to choose k items from n items without repetition and without order.
        
        Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
        to zero when k > n.
        
        Also called the binomial coefficient because it is equivalent
        to the coefficient of k-th term in polynomial expansion of the
        expression (1 + x)**n.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
    copysign(x, y, /)
        Return a float with the magnitude (absolute value) of x but the sign of y.
        
        On platforms that support signed zeros, copysign(1.0, -0.0)
        returns -1.0.
    
    cos(x, /)
        Return the cosine of x (measured in radians).
    
    cosh(x, /)
        Return the hyperbolic cosine of x.
    
    degrees(x, /)
        Convert angle x from radians to degrees.
    
    dist(p, q, /)
        Return the Euclidean distance between two points p and q.
        
        The points should be specified as sequences (or iterables) of
        coordinates.  Both inputs must have the same dimension.
        
        Roughly equivalent to:
            sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
    
    erf(x, /)
        Error function at x.
    
    erfc(x, /)
        Complementary error function at x.
    
    exp(x, /)
        Return e raised to the power of x.
    
    expm1(x, /)
        Return exp(x)-1.
        
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(x, /)
        Return the absolute value of the float x.
    
    factorial(x, /)
        Find x!.
        
        Raise a ValueError if x is negative or non-integral.
    
    floor(x, /)
        Return the floor of x as an Integral.
        
        This is the largest integer <= x.
    
    fmod(x, y, /)
        Return fmod(x, y), according to platform C.
        
        x % y may differ.
    
    frexp(x, /)
        Return the mantissa and exponent of x, as pair (m, e).
        
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(seq, /)
        Return an accurate floating point sum of values in the iterable seq.
        
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(x, /)
        Gamma function at x.
    
    gcd(x, y, /)
        greatest common divisor of x and y
    
    hypot(...)
        hypot(*coordinates) -> value
        
        Multidimensional Euclidean distance from the origin to a point.
        
        Roughly equivalent to:
            sqrt(sum(x**2 for x in coordinates))
        
        For a two dimensional point (x, y), gives the hypotenuse
        using the Pythagorean theorem:  sqrt(x*x + y*y).
        
        For example, the hypotenuse of a 3/4/5 right triangle is:
        
            >>> hypot(3.0, 4.0)
            5.0
    
    isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
        Determine whether two floating point numbers are close in value.
        
          rel_tol
            maximum difference for being considered "close", relative to the
            magnitude of the input values
          abs_tol
            maximum difference for being considered "close", regardless of the
            magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(x, /)
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(x, /)
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(x, /)
        Return True if x is a NaN (not a number), and False otherwise.
    
    isqrt(n, /)
        Return the integer part of the square root of the input.
    
    ldexp(x, i, /)
        Return x * (2**i).
        
        This is essentially the inverse of frexp().
    
    lgamma(x, /)
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x, [base=math.e])
        Return the logarithm of x to the given base.
        
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(x, /)
        Return the base 10 logarithm of x.
    
    log1p(x, /)
        Return the natural logarithm of 1+x (base e).
        
        The result is computed in a way which is accurate for x near zero.
    
    log2(x, /)
        Return the base 2 logarithm of x.
    
    modf(x, /)
        Return the fractional and integer parts of x.
        
        Both results carry the sign of x and are floats.
    
    perm(n, k=None, /)
        Number of ways to choose k items from n items without repetition and with order.
        
        Evaluates to n! / (n - k)! when k <= n and evaluates
        to zero when k > n.
        
        If k is not specified or is None, then k defaults to n
        and the function returns n!.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
    pow(x, y, /)
        Return x**y (x to the power of y).
    
    prod(iterable, /, *, start=1)
        Calculate the product of all the elements in the input iterable.
        
        The default start value for the product is 1.
        
        When the iterable is empty, return the start value.  This function is
        intended specifically for use with numeric values and may reject
        non-numeric types.
    
    radians(x, /)
        Convert angle x from degrees to radians.
    
    remainder(x, y, /)
        Difference between x and the closest integer multiple of y.
        
        Return x - n*y where n*y is the closest integer multiple of y.
        In the case where x is exactly halfway between two multiples of
        y, the nearest even value of n is used. The result is always exact.
    
    sin(x, /)
        Return the sine of x (measured in radians).
    
    sinh(x, /)
        Return the hyperbolic sine of x.
    
    sqrt(x, /)
        Return the square root of x.
    
    tan(x, /)
        Return the tangent of x (measured in radians).
    
    tanh(x, /)
        Return the hyperbolic tangent of x.
    
    trunc(x, /)
        Truncates the Real x to the nearest Integral toward 0.
        
        Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /opt/conda/lib/python3.8/lib-dynload/math.cpython-38-x86_64-linux-gnu.so


代码
文本
[3]
# 你也可以查看特定函数的帮助文档,例如math.sqrt函数
help(math.sqrt)
Help on built-in function sqrt in module math:

sqrt(x, /)
    Return the square root of x.

代码
文本
[5]
# 查看Python关键字的帮助文档,例如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" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  An iterator is created for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator.  Each
item in turn is assigned to the target list using the standard rules
for assignments (see Assignment statements), and then the suite is
executed.  When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
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 function "range()" returns an
iterator of integers suitable to emulate the effect of Pascal’s "for i
:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".

Note:

  There is a subtlety when the sequence is being modified by the loop
  (this can only occur for mutable sequences, e.g. lists).  An
  internal counter is used to keep track of which item is used next,
  and this is incremented on each iteration.  When this counter has
  reached the length of the sequence the loop terminates.  This means
  that if the suite deletes the current (or a previous) item from the
  sequence, the next item will be skipped (since it gets the index of
  the current item which has already been treated).  Likewise, if the
  suite inserts an item in the sequence before the current item, the
  current item will be treated again the next time through the loop.
  This can lead to nasty bugs that can be avoided by making a
  temporary copy using a slice of the whole sequence, e.g.,

     for x in a[:]:
         if x < 0: a.remove(x)

Related help topics: break, continue, while

代码
文本

当你运行这些命令时,Python解释器会显示相应的帮助文档。这些文档通常包括模块或函数的简短描述、参数列表、返回值说明以及一些示例代码。通过阅读这些帮助文档,你可以更好地理解如何使用Python的不同特性和模块。

help()函数是学习Python和解决编程问题的重要工具。当你对某个函数或模块不太熟悉时,不妨使用help()函数来查看它们的文档,这往往可以帮助你更快地找到解决问题的方法。

代码
文本

函数进阶

关于任意数量参数、解包等等,参考:

任意实参列表-Python官方文档

代码
文本

Python 基础 6:类

什么是类(class)?

在Python中,类(Class)是一种用来定义对象的模板,它描述了对象的属性方法
**对象(Object)**是类的实例化,即根据类的定义创建的具体实例。
类可以看作是用来创建对象的工具,而对象是类的具体实例,拥有类定义的属性和方法。

类的作用

类的主要作用是将数据和处理数据的方法封装在一起,使得代码更加模块化和易于维护。类还可以实现继承、多态等面向对象编程的特性,提高了代码的可重用性和灵活性。

下面是两个简单的类定义示例:

实例1. “小狗”

代码
文本
[162]
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print("Woof, woof!")

def sit(self):
print(self.name.title() + " is now sitting.")

def roll_over(self):
print(self.name.title() + " rolled over!")
代码
文本

这个示例定义了一个名为Dog的类,它具有两个属性(nameage)和三个方法(barksitroll_over)。__init__方法是一个特殊的方法,它在创建类的新实例时自动调用,用于初始化对象的属性。

要使用这个类,可以创建一个Dog对象并调用其方法,如下所示:

代码
文本
[161]
my_dog = Dog("Buddy", 3)
my_dog.bark()
my_dog.sit()
my_dog.roll_over()
Woof, woof!
Buddy is now sitting.
Buddy rolled over!
代码
文本

实例2. “圆形”

代码
文本
[164]
# 创建一个“圆”的类型
class Circle(object):
pi = 3.14 # 类属性

def __init__(self, r):
self.r = r # 对象的属性

circle1 = Circle(1) # 创建一个r = 1的圆
circle2 = Circle(2) # 创建一个r = 2的圆

print('----修改前-----')
print('pi=\t', Circle.pi)
print('circle1.pi=\t', circle1.pi) # 3.14
print('circle2.pi=\t', circle2.pi) # 3.14

print('----通过类名修改后-----')
Circle.pi = 3.14159 # 通过类名修改类属性,所有实例的类属性被改变
print('pi=\t', Circle.pi) # 3.14159
print('circle1.pi=\t', circle1.pi) # 3.14159
print('circle2.pi=\t', circle2.pi) # 3.14159

print('----通过circle1实例名修改后-----')
circle1.pi=3.14111 # 实际上这里是给circle1创建了一个与类属性同名的实例属性
print('pi=\t', Circle.pi) # 3.14159
print('circle1.pi=\t', circle1.pi) # 实例属性的访问优先级比类属性高,所以是3.14111
print('circle2.pi=\t', circle2.pi) # 3.14159
----修改前-----
pi=	 3.14
circle1.pi=	 3.14
circle2.pi=	 3.14
----通过类名修改后-----
pi=	 3.14159
circle1.pi=	 3.14159
circle2.pi=	 3.14159
----通过circle1实例名修改后-----
pi=	 3.14159
circle1.pi=	 3.14111
circle2.pi=	 3.14159
代码
文本

在“圆形”类中还可以加入对象的方法函数,例如加入面积计算函数

代码
文本
[167]
class Circle(object):
pi = 3.14 # 类属性

def __init__(self, r):
self.r = r # 实例属性

def get_area(self):
""" 圆的面积 """
return self.r**2 * Circle.pi # 通过实例修改pi的值对面积无影响,这个pi为类属性的值
#return self.r**2 * self.pi # 通过实例修改pi的值对面积,则圆的面积就会改变

circle1 = Circle(1)
circle1.pi = 3.14159
print("area =", circle1.get_area()) # 调用方法 self不需要传入参数,不要忘记方法后的括号
area = 3.14
代码
文本

练习

代码
文本
[16]
# 添加代码
代码
文本
代码
文本
notebook
python
Tutorial
notebookpythonTutorial
已赞8
本文被以下合集收录
AA_Python基础使用
陈乐天 Letian Chen
更新于 2024-09-07
5 篇2 人关注
python
微信用户J2cE
更新于 2025-04-09
4 篇0 人关注