第1章 Python基础
时间:2022-10-17 22:30:00
目录
- 0. Jupyter Notebook简介
- 0.1 Jupyter Notebook简介及启动
- 0.1.1 Jupyter Notebook简介
- 0.1.2 Jupyter Notebook安装与启动
- 0.2 Jupyter Notebook最常用的操作:
- 0.2.1 更改文件名
- 0.2.2 模式切换
- 0.2.3 命令模式快捷键
- 0.2.4 查询帮助
- 0.1 Jupyter Notebook简介及启动
- 1. Python基础语法
- 1.1 编码
- 1.2 标识符
- 1.3 注释
- 1.4 行与缩进
- 1.5 多行语句
- 1.6 多变量赋值
- 1.7 输入输出
- 1.8 包的导入
- 1.9 pip
- 2. Python运算符
- 2.1 算术运算符
- 2.2 比较(关系)运算符
- 2.3 赋值运算符
- 2.4 逻辑运算
- 2.5 位运算
- 2.6 成员运算符
- 2.7 身份运算符
- 2.8 运算符优先级
- 3. Python数据类型
- 3.1 Number(数字)
- 3.1.1 包括的类型
- 3.1.2 数值运算
- 3.1.3 数字类型转换
- 3.1.4 与数值型相关的函数
- 3.2 String(字符串)
- 3.2.1 索引字符串
- 3.2.2 字符串的切片
- 3.2.3 字符串的操作符
- 3.2.4 字符串函数
- 3.3 List(列表)
- 3.3.1 list的声明
- 3.3.2 list索引和切片
- 3.3.3 List运算符
- 3.3.4 List函数和方法方法
- 3.4 Tuple(元组)
- 3.4.1 tuple的声明
- 3.4.2 tuple索引和切片
- 3.4.3 tuple的常用函数
- 3.5 Set(集合)
- 3.5.1 set的声明
- 3.5.2 set不可以索引与切片
- 3.5.3 set的运算
- 3.6 字典
- 3.6.1 字典的创建
- 3.6.2 访问字典值
- 3.6.3 字典的keys()方法与values()方法
- 3.6.4 字典的键只能是不可变数据类型
- 3.7 使用和访问稍复杂的数据结构
- 3.1 Number(数字)
- 4. Python条件控制
- 4.1 单分支if语句
- 4.1.1 单分支if语句流程图
- 4.1.2 单分支if语句语法格式
- 4.1.3 单分支if语句例子
- 4.2 双分支if语句
- 4.2.1 双分支if语句流程图
- 4.2.2 双分支if语句语法格式
- 4.2.3 双分支if语句例子
- 4.3 if嵌套
- 4.3.1 if嵌套流程图
- 4.3.2 if嵌套语法格式
- 4.1 单分支if语句
- 5. Python循环控制
- 5.0 引子
- 5.1 While循环
- 5.1.1 基本语法结构
- 5.1.2 while循环嵌套
- 5.1.3 while嵌套循环的例子
- 5.1.4 条件句的一些特殊说明
- 5.1.5 while循环中的continue和break语句
- 5.1.6 while循环与else语句配合使用
- 5.2 for循环
- 5.2.1 for循环的一般格式
- 5.2.2 for循环的continue与break语句
- 5.2.3 for与else语句
- 5.3 range函数
- 5.4 课堂练习
- 6. Python各种导出式
- 6.1 列表导出式
- 6.2 字典导出式
- 6.3 集合导出式
- 6.4 元组导出式
- 7.异常处理
- 7.1 异常处理方法
- 7.2 主动抛出异常
- 8. 函数
- 8.1 基本语法
- 8.2 函数的参数
- 8.2.1 必需参数
- 8.2.2 关键字参数
- 8.2.3 默认参数
- 8.2.4 不定长参数
- 8.2.5 输出参数
- 8.3 匿名函数
- 8.4 几个特殊函数:map(),filter(), reduce()
- 8.4.1 遍历函数map()
- 8.4.2 筛选函数filter()
- 8.4.3 累计函数reduce()
本文的jupyter notebook脚本文件等 百度网盘下载
0. Jupyter Notebook简介
0.1 Jupyter Notebook简介及启动
0.1.1 Jupyter Notebook简介
Jupyter Notebook它是一个基于网页的交互计算应用程序。可应用于全过程计算:开发、文档编写、操作代码和显示结果。
Jupyter Notebook以网页的形式玩,可以在网页页面中直接编写代码和运行代码,代码的运行结果也会直接在代码块下显示。如在编程过程中需要编写说明文档,可在同一个页面中直接编写,便于作及时的说明和解释。
a = 1
b = 2
print(a+b)
0.1.2 Jupyter Notebook安装与启动
安装
- 随anaconda安装
- 单独安装
pip install jupyter
0.2 Jupyter Notebook里面的最常用的操作:
0.2.1 更改文件名
File–>Rename
0.2.2 模式切换
当前cell侧边为蓝色时,表示此时为命令模式,按Enter切换为编辑模式
当前cell侧边为绿色时,表示此时为编辑模式,按Esc切换为命令模式
0.2.3 命令模式快捷键
-
Y:把当前cell内容转换为代码形式
-
M:把当前cell内容转换为markdown形式
-
Ctrl+Enter:运行当前cell
-
Shift+Enter:运行当前cell并跳转到下一cell
-
Alt+Enter:运行当前cell并在下方新建cell
-
Tab:缩进
-
Shift+Table:减少缩进
-
A:在上方新建cell
-
B:在下方新建cell
-
双击D:删除当前cell
0.2.4 查询帮助
help(print)
print?
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
print("abc",end="*")
print("def")
abc*def
print?
1. Python基础语法
1.1 编码
默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。
当然你也可以为源码文件指定不同的编码:
# -*- coding: gbk -*-
上述定义允许在源文件中使用 Windows中的简体中文字符编码,对应适合语言为非unicode的简体中文。
1.2 标识符
- 只能由字母、数字或下划线组成
- 只能由字母或下划线开头
- 严格区分大小写
- 不能够用保留字
- 提倡用驼峰命名法命名
- 标识符命名应做到见名知意
True
int32, true, 40XL,__name__, self
# 小驼峰
studentName = "RJG"
# 大驼峰
StudentName = "RJG"
a1 = 1
a_1 = 2
_a1 = 3
1a = 4
File "", line 4
1a = 4
^
SyntaxError: invalid syntax
import keyword
keyword.kwlist
['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
and=1
File "", line 1
and=1
^
SyntaxError: invalid syntax
And=1
1.3 注释
- python中单行注释以#开头
- 多行注释可以每行用#,也可以用"““注释内容””",‘’’ ‘’’
"""python中单行注释以#开头 多行注释可以每行用#,也可以用'''注释内容''' """
# a是第一个输入
a= input("输入第一个参数:")
print(a)
输入第一个参数:a
a
1.4 行与缩进
python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {}
。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。
实例如下:
实例
if True:
print("True")
else:
print("False")
以下代码最后一行语句缩进数的空格数不一致,会导致运行错误:
if True:
print("Answer")
print("True")
else:
print("Answer")
print("False")# 缩进不一致,会导致运行错误
if True:
print("True1")
print("True2")
else:
print("False1")
print("False2")
print("这是后续语句1")
print("这是后续语句2")
True1
True2
这是后续语句1
这是后续语句2
1.5 多行语句
Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠\
来实现多行语句,例如:
total = item_one + \
item_two + \
item_three
在[]
,{}
,或()
中的多行语句,不需要使用反斜杠\
,例如:
total = ['item_one',
'item_two',
'item_three',
'item_four',
'item_five']
1.6 多个变量赋值
Python允许你同时为多个变量赋值。例如:
a = b = c = 1
以上实例,创建一个整型对象,值为 1,三个变量都指向同一个内存位置。
您也可以为多个对象指定多个变量。例如:
a, b, c = 1, 2, "PythonTest"
以上实例,两个整型对象 1 和 2 的分配给变量 a 和 b,字符串对象 “PythonTest” 分配给变量 c。
aa = bb = cc = 33
bb
33
a = 1
type(a)
int
b = 1.5
type(b)
float
b = 3
type(b)
int
a,b,c,d = 1,1.5,"abc",True
a
1
b
1.5
a,b=b,a
a
1.5
b
1
c
'abc'
d
True
type(c)
str
type(a)
int
type(d)
bool
a
1.7 输入输出
-
控制台输入 input
- 接收到的输入为字符串类型,若需数值类型参与运算,需对接收到的结果采用int、float等强制转换
- 采用input(“…”)增加输入提示
-
控制台打印输出 print
- print默认输出是换行,如果要实现不换行则需要在输入参数中增加end=“”
- print的格式化输出:
- A. print(“num:%d” %num)
- B. print(“num:{}”.format(num))
- C. print(f"num:{num}")
m=10
n = int(input())
123
m+n
133
type(n)
int
name
'RJG'
name = input("姓名:")
姓名:rjg
name
'rjg'
num = 5.555
print("num:",num)
num: 5.555
print("num: %.2f" %num)
num: 5.55
num = 5
print("num:%d" %num)
num:5
print("num:{}".format(num))
num:5
print(f"num:{
num}")
num:5
1.8 包的导入
- import 包的名称
- import 包的名称 as 包的别名
- from 包的名称 import 模块的名称
- from 包的名称 import 模块的名称 as 模块的别名
import os
os.getcwd()
'D:\\01130'
import numpy as np
np.
from matplotlib import pyplot
pyplot.plot()
from matplotlib import pyplot as plt
1.9 pip
- 在线安装方式
- pip install 包的名称 (这种是从pypi这个服务器上下载)
- pip install 包的名称 -i http://mirrors.aliyun.com/pypi/simple/
- 在线安装方式
pip install numpy #在线安装numpy,从pypi服务器上下载
pip install scrapy -i http://mirrors.aliyun.com/pypi/simple/ #在线安装scrapy,从后面指定源
- 离线安装方式
先下载.whl文件
pip install xxxxx.whl
- 安装jupyter notebook自动目录生成插件
https://www.cnblogs.com/xiaoniu-666/p/10973911.html
主要三步:
- pip install jupyter_contrib_nbextensions -i https://pypi.mirrors.ustc.edu.cn/simple/ --trusted-host https://pypi.mirrors.ustc.edu.cn/
- jupyter contrib nbextension install --user --skip-running-check
- 取消最上面的的"disable。。。"前面的复选框,勾选下面的"Table of Contents(2)“前面的复选框”
-
pip国内的一些镜像
阿里云 http://mirrors.aliyun.com/pypi/simple/
豆瓣(douban) http://pypi.douban.com/simple/
清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/ -
修改源方法:
临时使用:
可以在使用pip的时候在后面加上-i参数,指定pip源
eg: pip install scrapy -i https://pypi.tuna.tsinghua.edu.cn/simple
2. Python运算符
- 算术运算符
- 比较算术符
- 赋值运算符
- 位运算符
- 成员运算符
- 身份运算符
- 运算符优先级
2.1 算术运算符
- +,-,*,**, /,// ,%
- 特别需要注意的是:
- /与//
- %
- **
5/2
2.5
5//2
2
8//3
2
13%3
1
13//3
4
13-3*(13//3)
1
2**4
16
2.2 比较(关系)运算符
- >,<,==,>=,<=,!=
- 需要注意的是:
- 相等的判断:==而不是=(赋值)
- 不相等的符号:!= ,不是~=,><
3>2
True
3==2
False
3>=2
True
3!=2
True
3>'3'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 3>'3'
TypeError: '>' not supported between instances of 'int' and 'str'
2.3 赋值运算符
- =, +=, -=,*=,/=,//=,%=
- python中没有没有自增"++“或自减”–"
a = 3
a += 1 # a = a+1
a
4
a -=2
a
2
2.4 逻辑运算
- 与(and)、或(or),非(not)
b
a = 2
b = 1
c = 3
(a ==1) and (b == 2) and (c == 3)
False
a = 1
b = 1
(a ==1) or (b == 2)
True
not(a==1)
False
2.5 位运算
- &,|, ~,- ,<<,>>
2.6 成员运算符
- in,not in
a = "abcd"
b = "b"
b in a
True
a = [11,12,13,14]
b = 13
b in a
True
stuNames = {
"张三","李四","王五"}
stuN = "张三3"
stuN in stuNames
False
if stuN in stuNames:
print("请输入密码:")
else:
print("你还没注册")
你还没注册
2.7 身份运算符
- is,is not
a = 20
b = 20
a is b
True
b = 30
a is b
False
id(a)
8791380370416
id(b)
8791380370736
a is not b
True
id(a)
8791380370416
id(b)
8791380370416
2.8 运算符优先级
详见: https://www.runoob.com/python3/python3-basic-operators.html#ysf8
建议用圆括号改变运算顺序
3. Python数据类型
-
Python3中的标准数据类型:
- Number(数字)
- String (字符串)
- List (列表)
- Tuple(元组)
- Set(集合)
- Dictionary(字典)
-
可分为两大类:
- 不可变数据类型(3个): Number、String、Tuple
- 可变数据类型(3个):List、Dictionary、Set
不可变数据类型: 当该数据类型的对应变量的值发生了改变,那么它对应的内存地址也会发生改变,对于这种数据类型,就称不可变数据类型。
可变数据类型 :当该数据类型的对应变量的值发生了改变,那么它对应的内存地址不发生改变,对于这种数据类型,就称可变数据类型。
-
另外一种分法:
- 有序的:String,Tuple,List,Dictionary(3.6版本之后是有序的)。有序才可索引与切片
- 无序的:Set,Dictionary(3.6之前是无序的)
alist = [1,2,3]
alist[1]
2
alist[1]=22
astr = "abcd"
astr[1]
'b'
astr[1]='e'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 astr[1]='e'
TypeError: 'str' object does not support item assignment
aList = [1,2,3]
id(aList)
166826632
aList[1] = 200
aList
[1, 200, 3]
id(aList)
166826632
3.1 Number(数字)
3.1.1 包括的类型
Python3支持int、float、bool、complex(复数)
var11,var12 = 1,True
del var11,var12
var1 = 1
var2 = 10
print(var1)
1
del var1
print(var1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
----> 1 print(var1)
NameError: name 'var1' is not defined
3.1.2 数值运算
- 包括: +,-,*,/,**,%,//
- 在混合运算时,Python会把整型转换位浮点型
1 + 1.5
2.5
import math
math.ceil(1.3)
2
math.floor(1.9)
1
3.1.3 数字类型转换
- int(x) 将x转换为整型
- float(x) 将x转换为浮点型
- complex(x) 将x转换为复数,实部是x,虚部是0
- complex(x,y) 将转换为一个复数,实部是x,虚部是y
a = input("num:")
num:1.23
a
'1.23'
float(a)
1.23
int(1.23)
1
3.1.4 数值型相关的函数
详见 : https://www.runoob.com/python3/python3-number.html
3.2 String(字符串)
字符串在python中是用一对双引号(“”)或一对单引号(‘’)括起来的。
print( "What's your name?" )
What's your name?
3.2.1 字符串的索引
- 索引值从左向右为从0开始逐渐递增
- 索引值从右向左为从-1开始逐渐递减
- 可通过
变量名[索引值]
获取到字符串该索引位置的字母
aStr = "abcdef"
aStr
'abcdef'
aStr[0]
'a'
aStr[2]
'c'
aStr[-1]
'f'
aStr[-2]
'e'
3.2.2 字符串的切片
- 切片的表示:
- 变量名
[起始索引:终止索引]
起始间所有元素切片 - 变量名
[起始索引:终止索引:步长]
起始间按步长进行元素切片 - 索引区间是左闭右开的(能取到左边索引的元素,取不到右边的)
- 变量名
aStr
'abcdef'
aStr[1:4]
'bcd'
aStr[1:4:]
'bcd'
aStr[1:4:1]
'bcd'
aStr[:4]
'abcd'
aStr[2:]
'cdef'
aStr[4]
'e'
aStr[1:4:2]
'bd'
aStr[-1]
'f'
aStr[-1:-4]
''
aStr[-1:-4:-1]
'fed'
bStr = "abcdefgh"
bStr[::-1]
'hgfedcba'
bStr[-1::-2]
'hfdb'
3.2.3 字符串的操作符
- "+"运算是进行字符串连接
- "*n"运算是字符串重复n次
- in,not in : 成员运算
- r/R : 原生字符串
- % :格式化字符串
print("hello\n world!")
hello
world!
print("hello\\n world!")
hello\n world!
print(r"hello\n world!")
hello\n world!
1+2
3
aStr
'abcdef'
bStr
'abcdefgh'
aStr + bStr
'abcdefabcdefgh'
"我错了 "*100
'我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 '
'A' in "ABC"
True
'A' not in "abc"
True
print("hello \n world!")
hello
world!
print(r"hello \n world!")
hello \n world!
"%s ,I love you" %("CQTBI")
'CQTBI ,I love you'
a = 3.1415926
b = 1.57
"%.2f + %.2f=%.1f" %(a,b,a+b)
'3.14 + 1.57=4.7'
3.2.4 字符串函数
- str.capitalize(),str.lower(),str.upper(),str.title()
- str.strip(),str.lstrip(),str.rstrip(),str.replace()
- str.split()
-
- str.capitalize(),str.lower(),str.upper(),str.title()
s = "hello world. chong qing."
s.capitalize()
'Hello world. chong qing.'
s.title()
'Hello World. Chong Qing.'
s1 = s.upper()
s1
'HELLO WORLD. CHONG QING.'
s1.lower()
'hello world. chong qing.'
-
- strip()/lstrip()/rstrip()/replace()
a1 = input("input a num:")
input a num:1234
a1
'1234'
a2 = input("input a num:")
input a num: 1234
a2
' 1234 '
a1==a2
False
a1.strip()==a2.strip()
True
s = "hello world!world!world!"
s.replace("world","cqtbi")
'hello cqtbi!cqtbi!cqtbi!'
3.3 List(列表)
3.3.1 list的声明
- alist = [1,2,3]
- alist = list()
- alist = []
alist = [1,2,3,1.5,"abc",True]
type(alist)
list
blist = []
blist
[]
blist[0] = 1
blist
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in
----> 1 blist[0] = 1
2 blist
IndexError: list assignment index out of range
clist = list元器件数据手册
、IC替代型号,打造电子元器件IC百科大全!