小甲鱼Python教程,截图 + 代码 + 学习笔记,Python入门【12000字】【原创】


❤2023年3月重新理解记录

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

一、前言

Python可在windows/mac os/www/linux系统上运行
实现相同功能是java代码量的五分之一
云计算/操作系统/3d动画/web/企业应用
Python常用语法/面向对象编程思维/运用模块进行编程/游戏编程/计算机仿真
鱼c论坛
学习的捷径:验证例子/课后实践/擅用搜索/放轻松
IDLE是python shell/就是输入文本与程序交互的途径/就相当于windos cmd黑乎乎命令窗口(CMD是COMMAND的缩写,CMD窗口模拟以前的DOS系统,可以通过命令一个一个的执行任务,但不能同时执行多个。关于CMD命令,你可以在CMD窗口下输入help,回车后你会在这儿找到很多常用的命令,如cd,dir,等等)


二、初识Python

Alt+n返回上一语句Alt+p返回下一语句

>>>print  “I love fishc.com”  #最新编辑器错误

>>>printf  (“I love fishc.com”) #错误

>>>print  (5+3)      #这两个结果一样好像有一点区别不明白
>>> 5+3

>>>112345678987654321*9876543210123456789
>>>print(“well water”+”river”)
Well waterriver
>>>print(“I love fishc.com”*8)
>>> print(“I love fishc.com\n”*8)
>>> print(“I love fishc.com\n”+8) #编译错误

Python是脚本语言/不需要编译/语法和结构比较简单

IDEL就是上面解释过的了/python shell/shell就是外壳
Print()就是显示一些文本
为什么 >>>print('I love fishc.com ’ * 5) 可以正常执行,但 >>>print('I love fishc.com ’ + 5)/因为第二个是不同类型相加所以会报错

如果我需要在一个字符串中嵌入一个双引号,正确的做法是?
你有两个选择:可以利用反斜杠(\)对双引号转义:“,或者用单引号引起这个字符串。例如:’ I l"o"ve fishc.com ’ >>>print (” I l"o"ve fishc.com ")

>>> print ('365*24*60*60')
365*24*60*60
>>> print ("365*24*60*60")
365*24*60*60
>>> print(365*24*60*60)
31536000

Alt+n新建窗口
Untitled/未命名的;没有标题的;无头衔的;无爵位的;非冠军的

print("wufangfangzhizuo")
temp = input("猜猜数字吧:")     变量没有声明?没有大括号像main?
guess = int(temp)            python中变量是没有类型的  python用缩进表示/缩进是python灵魂
if guess == 8:                注意别少了分号
	print("caizhongle")       if 对应一个print
    print("nizhencongming")
else:
	print("caiduile")         else对应一个print
print("youxijiehsu")    

程序流程解读
在这里插入图片描述

BIF == build-in function就是内置函数
Print函数 input函数 int函数 都是内置函数
输入>>>dir(builtins)得到所有小写都是内置函数 directory目录
输入>>>help(函数)得到内置函数用法

1 单引号和双引号的区别

今天在网上爬虫的时候,很奇怪的发现python的字符串既可以用双引号又可以用单引号,于是就上网百度了一下原因。
原来由于字符串中有可能既有双引号又有单引号,例如:
字符串:demo’1’。
这时候就可以:str  = “demo’1’”;这样看更直观,当然也可以使用转义字符’代替单引号:str  = ‘demo’1’'。
字符串:demo"1"。
这时候就可以:str  = ‘demo"1"’。

>>> print("sss"sss"")
	  
SyntaxError: invalid syntax
>>> print("22'sss'")	  
22'sss'
>>> print('777"ss"')	  
777"ss"
>>> print('sss\'9\'')	  
sss'9'
>>> print("hh\'77")	  
hh'77
>>> print("hhj\'11\'")	  
hhj'11'
>>> print("ggg\"ddd"\")	  
SyntaxError: unexpected character after line continuation character
>>> print("sss\"123"")	  
SyntaxError: EOL while scanning string literal

如:‘I’ + ‘Love’ + ‘FishC’ 会得到 ‘ILoveFishC’,在 Python 里,这种做法叫做拼接字符串。
Python 不允许 if 条件中赋值,所以 if c = 1: 会报错!

i = “ss”
print(i)
等价于
Print(“ss”)

i = “wu”
y = “fangfang”
x = i+y
print(x)/输出wufangfang

使用变量之前需要先赋值(C语言还要定义类型)
变量名不能以数字开头
大小写变量名不同

>>>5+8
>>>5+8>>>5+8” #报错
>>>’let\’s go’  #\进行转义
>>>str=’C:\now’
>>>str=’C:\\now’  #可以不实用
>>>str=r’C:\now’  #原始字符串正确
>>>str=r’C:\now\’  #错误

三对引号(单双三都可以要上下成对)输出跨越多行字符串

>>> print("let's go")	  
let's go
等价于
>>> print(‘let\’s go’)	  
let's go
>>> print(‘let\’s go“)	 #错误 
error

如果非要在原始字符串结尾输入反斜杠,可以如何灵活处理?

>>>str = r'C:\Program Files\FishC\Good''\\'

在例子中小甲鱼起了个 str 名字的变量,但事实上我们发现,str 的颜色跟普通变量貌似不同?没错,str() 和 print() 都是内置函数,但 Python 貌似不介意我们对内置函数进行赋值操作,所以这点我们以后就要注意啦,否则可能会出现以下的 BUG:

2 条件分支

>
<
>=
<=
==
!=
If:
缩进
Else:
缩进
While循环

在这里插入图片描述

3 操作符and

>>>3>2 and 1<2
>>>(3>2)and(1<2)

4 产生随机数

random模块里面有一个randint()是产生随机的整数
random.randint(1,10)

三、数据类型

整型(包括长整型)/布尔类型/e记法/浮点型(小数)
数据类型转换
str()/int()/float()
type(数据)函数获得类型
isinstance(数据,类型)函数获得类型

1 常用操作符

>>> 3.8/2
1.9
>>> 3.8//2
1.0
>>> 3/2
1.5
>>> 3//2
1
>>> 3.0/2
1.5

**幂运算
运算优先级顺序
and逻辑与/or逻辑或

>>> -3**2
-9
>>> 3**-2
0.1111111111111111

在这里插入图片描述

四、分支和循环

打飞机框架
加载背景音乐
播放单曲循环
我方飞机诞生
while True:
   if用户点击关闭
   	 退出程序
     小飞机诞生
     小飞机移动
   屏幕刷新
   if用户鼠标移动
     我方飞机=鼠标
   if飞机撞机
     修改飞机图案
     game over
     退出游戏
     停止音乐

1 分支

第一种方法就是if 浪费cpu时间
第二种if…else
第三种if…elif 相比第一种省时间

python有效避免悬挂else

2 三元操作符

small = x if x < y else y
如果条件为真赋给x/如果条件为假赋给y

assert
例如>>> assert 3 > 4

五、While循环

For循环
For 目标 in 表达式
  循环体
>>> t = ["ss","fhd"]
>>> for i in t:
	print(i,len(i))	
ss 2
fhd 3

range()
range([start,]stop[,step=1])作用生成数字序列
与for循环套用
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> range(5)
range(0, 5)
>>> range(0,5)
range(0, 5)

>>> for i in range(0,5):    #for与range套用
	print(i)

	
0
1
2
3
4

>>> for i in range(1,10,2):  #三个参数
	print(i)

	
1
3
5
7
9

Break与continue
t = "方方"
y = input("请输入中文名字:")
while True:
    if y == t:
        break
    print("你猜错了")
    y = input("请继续输入中文名字:")
print("你猜对了")
print("游戏结束")
>>> for i in range(10):
    if i%2 !=0:
        print(i)
        continue
    i += 2
    print(i)

    
2
1
4
3
6
5
8
7
10
9

六、列表

1 整数/浮点数/字符串/对象

>>> t = ["aa","123","45gf"]
>>> t
['aa', '123', '45gf']
>>> t = [11,'23',[1,2,3]]
>>> t
[11, '23', [1, 2, 3]]

>>> t = []  #空列表
>>> t
[]

2 向列表添加元素

append()
>>> t = [11,'23',[1,2,3]]
>>> t
[11, '23', [1, 2, 3]]
>>> t.append('11')
>>> t
[11, '23', [1, 2, 3], '11']

Extend()扩展         列表
>>> t
[11, '23', [1, 2, 3], '11']
>>> t.extend(['11','556'])
>>> t
[11, '23', [1, 2, 3], '11', '11', '556']

insert()插入      两个参数从0开始算
>>> t.insert(0,'fangfang')
>>> t
['fangfang', 11, '23', [1, 2, 3], '11', '11', '556']

index()从列表中获取值

从列表中删除元素
remove()
>>> t
['fangfang', 11, '23', [1, 2, 3], '11', '11', '556']
>>> t.remove(11)
>>> t
['fangfang', '23', [1, 2, 3], '11', '11', '556']

del   删除
>>> t
['fangfang', '23', [1, 2, 3], '11', '11', '556']
>>> del t[1]
>>> t
['fangfang', [1, 2, 3], '11', '11', '556']
>>> del t
>>> t
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    t
NameError: name 't' is not defined

pop()出栈
>>> t = [11,'23',[1,2,3]]
>>> t
[11, '23', [1, 2, 3]]
>>> t.pop(11)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    t.pop(11)
IndexError: pop index out of range
>>> t.pop()
[1, 2, 3]
>>> t
[11, '23']

3 列表分片

>>> t = ['fangfang', 11, '23', [1, 2, 3], '11', '11', '556']
>>> t
['fangfang', 11, '23', [1, 2, 3], '11', '11', '556']
>>> t[2:4]
['23', [1, 2, 3]]
>>> t[:4]
['fangfang', 11, '23', [1, 2, 3]]
>>> t[:]
['fangfang', 11, '23', [1, 2, 3], '11', '11', '556']
['fangfang', 11, '23', [1, 2, 3], '11', '11', '556']
>>> y = t[:]
>>> y
['fangfang', 11, '23', [1, 2, 3], '11', '11', '556']

>>> z = [123.456]
>>> z
[123.456]
>>> z*3
[123.456, 123.456, 123.456]

在这里插入图片描述

>>> list = [123,"456",'吴方方']
>>> list*5
[123, '456', '吴方方', 123, '456', '吴方方', 123, '456', '吴方方', 123, '456', '吴方方', 123, '456', '吴方方']
>>> 123 in list
True
>>> 吴方方 in list
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    吴方方 in list
NameError: name '吴方方' is not defined
>>> '吴方方' in list
True
>>> "吴方方" in list
True
>>> '吴方方'in list
True

4 列表成员

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> dir(z)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>


>>> list.index(123)
0
>>> list.index(123,0,15)
0
>>> list.count(123)
1
>>> list
[123, '456', '吴方方']
>>> list.index(123,0,3)
0
>>> list.index(123,0,2)
0
>>> list.index("456",0,2)
1
>>> list.index(456,0,2)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    list.index(456,0,2)
ValueError: 456 is not in list


reverse()       重要  翻转      无参数
>>> list.reverse()
>>> list
['吴方方', '456', 123]


Sort()   对列表成员进行顺序排序   无参数
>>> list
['吴方方', '456', 123]
>>> list.sort()
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    list.sort()
TypeError: '<' not supported between instances of 'int' and 'str'

>>> list2 = [1,34,2,34,25,7,9,34,12]
>>> list2
[1, 34, 2, 34, 25, 7, 9, 34, 12]
>>> list2.sort()
>>> list2
[1, 2, 7, 9, 12, 25, 34, 34, 34]
>>> list2.reverse()
>>> list2
[34, 34, 34, 25, 12, 9, 7, 2, 1]

5 一步倒序排列

>>> list3 = [87,54,2,87,24,08]
SyntaxError: invalid token
>>> list3 = [87,54,2,87,24,8]
>>> list3.sort(reverse=True)
>>> liat3
Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    liat3
NameError: name 'liat3' is not defined
>>> list3
[87, 87, 54, 24, 8, 2]

在这里插入图片描述
在这里插入图片描述

七、语法

1 一行可以书写多个语句吗?

可以,语句之间用分号隔开即可,不妨试试:

>>> print('I love fishc');print('very much!') 

2 一个语句可以分成多行书写吗?

可以,一行过长的语句可以使用反斜杠或者括号分解成几行,不妨试试:

1. >>> 3 > 4 and \ 
2. 1 < 2 
复制代码 
或者 
4. >>> ( 3 > 4 and 
5. 1 < 2 ) 
复制代码

>>> a,b = 0,1
>>> while b < 1000:
	print(b,end=",")
	a,b = b,a+b

	
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
>>> a,b=0,1
>>> while b < 1000:
	print(b,end=",")
	a,b = b,a+b
	if b > 700:
		break
print(b)
SyntaxError: invalid syntax
>>> a,b=0,1
>>> while b < 1000:
	print(b,end=",")
	a,b = b,a+b
	if b > 700:
		print(b)
		break

	
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987

八、元组

>>> t=(1,2,3,4,5)
>>> t
(1, 2, 3, 4, 5)
>>> t(1)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    t(1)
TypeError: 'tuple' object is not callable
>>> t[2]
3
>>> y=t[:]
>>> y
(1, 2, 3, 4, 5)
>>> t[2:3]
(3,)
>>> t[1:3]
(2, 3)
>>> t[:6]
(1, 2, 3, 4, 5)

>>> t[:6]
(1, 2, 3, 4, 5)
>>> type(t)
<class 'tuple'>
>>> t[]
SyntaxError: invalid syntax
>>> t=t[]
SyntaxError: invalid syntax
>>> t=[]
>>> t
[]
>>> t=()
>>> t
()
>>> type(t)
<class 'tuple'>


>>> t=t(4)          #不能赋值
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    t=t(4)
TypeError: 'tuple' object is not callable
>>> (6)
6
>>> 4*(6)
24
>>> t=(6,)
>>> 4*t
(6, 6, 6, 6)
>>> t=[1]
>>> 4*t
[1, 1, 1, 1]

1 元组拼接

>>> t
[1, 23, 4, 5]
>>> t=t[:2]+(44,)+t[2:]
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    t=t[:2]+(44,)+t[2:]            #不同类型错误
TypeError: can only concatenate list (not "tuple") to list
>>> t=(1,23,4,5)
>>> t=[:2]+(44,)+[2:]
SyntaxError: invalid syntax
>>> t=t[:2]+(44,)+t[2:]
>>> t
(1, 23, 44, 4, 5)

九、字符串

1 字符串的方法及注释

如在使用上有不懂可以看视频教程:《零基础入门学习Python》第014讲

capitalize()	把字符串的第一个字符改为大写
casefold()	把整个字符串的所有字符改为小写
center(width)	将字符串居中,并使用空格填充至长度 width 的新字符串
count(sub[, start[, end]])	返回 sub 在字符串里边出现的次数,start 和 end 参数表示范围,可选。
encode(encoding='utf-8', errors='strict')	以 encoding 指定的编码格式对字符串进行编码。
endswith(sub[, start[, end]])	检查字符串是否以 sub 子字符串结束,如果是返回 True,否则返回 False。start 和 end 参数表示范围,可选。
expandtabs([tabsize=8])	把字符串中的 tab 符号(\t)转换为空格,如不指定参数,默认的空格数是 tabsize=8find(sub[, start[, end]])	检测 sub 是否包含在字符串中,如果有则返回索引值,否则返回 -1,start 和 end 参数表示范围,可选。
index(sub[, start[, end]])	跟 find 方法一样,不过如果 sub 不在 string 中会产生一个异常。
isalnum()	如果字符串至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False。
isalpha()	如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False。
isdecimal()	如果字符串只包含十进制数字则返回 True,否则返回 False。
isdigit()	如果字符串只包含数字则返回 True,否则返回 False。
islower()	如果字符串中至少包含一个区分大小写的字符,并且这些字符都是小写,则返回 True,否则返回 False。
isnumeric()	如果字符串中只包含数字字符,则返回 True,否则返回 False。
isspace()	如果字符串中只包含空格,则返回 True,否则返回 False。
istitle()	如果字符串是标题化(所有的单词都是以大写开始,其余字母均小写),则返回 True,否则返回 False。
isupper()	如果字符串中至少包含一个区分大小写的字符,并且这些字符都是大写,则返回 True,否则返回 False。
join(sub)	以字符串作为分隔符,插入到 sub 中所有的字符之间。
ljust(width)	返回一个左对齐的字符串,并使用空格填充至长度为 width 的新字符串。
lower()	转换字符串中所有大写字符为小写。
lstrip()	去掉字符串左边的所有空格
partition(sub)	找到子字符串 sub,把字符串分成一个 3 元组 (pre_sub, sub, fol_sub),如果字符串中不包含 sub 则返回 ('原字符串', '', '')
replace(old, new[, count])	把字符串中的 old 子字符串替换成 new 子字符串,如果 count 指定,则替换不超过 count 次。
rfind(sub[, start[, end]])	类似于 find() 方法,不过是从右边开始查找。
rindex(sub[, start[, end]])	类似于 index() 方法,不过是从右边开始。
rjust(width)	返回一个右对齐的字符串,并使用空格填充至长度为 width 的新字符串。
rpartition(sub)	类似于 partition() 方法,不过是从右边开始查找。
rstrip()	删除字符串末尾的空格。
split(sep=None, maxsplit=-1)	不带参数默认是以空格为分隔符切片字符串,如果 maxsplit 参数有设置,则仅分隔 maxsplit 个子字符串,返回切片后的子字符串拼接的列表。
splitlines(([keepends]))	在输出结果里是否去掉换行符,默认为 False,不包含换行符;如果为 True,则保留换行符。。
startswith(prefix[, start[, end]])	检查字符串是否以 prefix 开头,是则返回 True,否则返回 False。start 和 end 参数可以指定范围检查,可选。
strip([chars])	删除字符串前边和后边所有的空格,chars 参数可以定制删除的字符,可选。
swapcase()	翻转字符串中的大小写。
title()	返回标题化(所有的单词都是以大写开始,其余字母均小写)的字符串。
translate(table)	根据 table 的规则(可以由 str.maketrans('a', 'b') 定制)转换字符串中的字符。
upper()	转换字符串中的所有小写字符为大写。
zfill(width)	返回长度为 width 的字符串,原字符串右对齐,前边用 0 填充。

2 字符串格式化

在这里插入图片描述

>>> "{0}Love{1}.{2}".format("I","fangfang","com")
'ILovefangfang.com'
>>> "{0} Love {1}.{2}".format("I","fangfang","com")
'I Love fangfang.com'
>>> "{a} Love {b}.{c}".format(a="I",b="fangfang",c="com")
'I Love fangfang.com
![在这里插入图片描述](https://img-blog.csdnimg.cn/47dbce71ddaa41c1839c1bbe076d5cae.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5oOF57O75reu5oCd,size_19,color_FFFFFF,t_70,g_se,x_16)

>>> "{{0}}".format("com")
'{0}'
>>> "{0:.1f}{1}".format("25.234","GB")
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    "{0:.1f}{1}".format("25.234","GB")
ValueError: Unknown format code 'f' for object of type 'str'
>>> "{0:.1f}{1}".format(25.234,"GB")
'25.2GB'
>>> "{0:.1f}{1}".format(25.234,GB)
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    "{0:.1f}{1}".format(25.234,GB)
NameError: name 'GB' is not defined


>>> (%c) % a
SyntaxError: invalid syntax
>>> "%c" % a
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    "%c" % a
NameError: name 'a' is not defined
>>> '%c' % a
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    '%c' % a
NameError: name 'a' is not defined
>>> "%c" % 97
'a'
>>> "%c" % 97
'a'
>>> "%c"%97
'a'
>>> "%c"% 255
'ÿ'
>>> "%5.1f" % 27.7869
' 27.8'
>>> "%e" % 27.1829
'2.718290e+01'
>>> "%.3f" % 27.1829
'27.183'
>>> "%.3e" % 27.1829
'2.718e+01'


>>> "%c" % 97
'a'
>>> "%c"%97
'a'
>>> "%c"% 255
'ÿ'
>>> "%5.1f" % 27.7869
' 27.8'
>>> "%e" % 27.1829
'2.718290e+01'
>>> "%.3f" % 27.1829
'27.183'
>>> "%.3e" % 27.1829
'2.718e+01'

3 总结:元组/数组/字符串/列表

在这里插入图片描述

>>> char="123456"
>>> g=(1,2,3,4,5)
>>> sum.g
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    sum.g
AttributeError: 'builtin_function_or_method' object has no attribute 'g'
>>> sum g()
SyntaxError: invalid syntax
>>> sum g
SyntaxError: invalid syntax
>>> sum(g)
15
>>> sum(char)
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    sum(char)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> sort(g)
Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    sort(g)
NameError: name 'sort' is not defined
>>> sorted(g)
[1, 2, 3, 4, 5]
>>> reversed(g)
<reversed object at 0x00000160BBB09D30>   #迭代对象
>>> list(reversed(g))
[5, 4, 3, 2, 1]
>>> enumerate(g)
<enumerate object at 0x00000160BBB2A558>
>>> list(enumerate(g))
	 
SyntaxError: invalid character in identifier
>>> list(enumerate(g)) 
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]


>>> a=[1,2,3,4,5,6,7] 
>>> b=[5,6,7,8,9] 
>>> zip(a,b) 
<zip object at 0x00000160BBB53408>
>>> list(zip(a,b))	     #列表转换
[(1, 5), (2, 6), (3, 7), (4, 8), (5, 9)]

在这里插入图片描述

十、函数/对象/模块

>>> def jia(a,b):
	c=a+b
	print(c)
>>> jia(1,2)
3

>>> jia(1,2)
3
>>> def jia(a,b):
	return(a+b)
>>> jia(1,2)
3

1 函数文档

>>> hanshuwendang("吴方方")
我叫吴方方我好帅
>>> hanshuwendang.__doc__
'这就是wendang'
>>> help(hanshuwendang.__doc__)
No Python documentation found for '这就是wendang'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

2 关键字参数

在这里插入图片描述

3 默认参数

在这里插入图片描述

4 收集参数

>>> def test(*params):
	print("参数长度:",len(params))
	print("第二个参数:",params[1])
>>> test(1,"吴方方"13,2,18,"suibian")
SyntaxError: invalid character in identifier
>>> test(1,"吴方方",13,2,18,"suibian")
参数长度: 6
第二个参数: 吴方方


>>> def test(*params,exp):
	print("参数长度:",len(params))
	print("第二个参数:",params[1])

	
>>> test(1,"吴方方",13,2,18,"suibian")
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    test(1,"吴方方",13,2,18,"suibian")
TypeError: test() missing 1 required keyword-only argument: 'exp'
>>> 
KeyboardInterrupt
>>> test(1,"吴方方",13,2,18,"suibian",exp=5)
参数长度: 6
第二个参数: 吴方方

5 函数与过程

>>> def hello():
	print('hello world')	
>>> t=hello()
hello world
>>> t
>>> type(t)
<class 'NoneType'>

6 函数变量的作用域

在这里插入图片描述

def discount(price,rate):
    final_price = price * rate    #这里若是强制转换float会报错自动结果就是float
#print("试图在函数内部打印全局变量",new_price)   这一句是正确的
    return final_price

price = float(input("请输入原价:"))
rate = float(input("请输入比率:"))
new_price = discount(price , rate)
print("最终价钱是:",new_price)
#print("最终价钱是:",final_price)    这一句会报错因为其是局部变量

在这里插入图片描述

>>> t=5
>>> t
5
>>> def ceshi():
	t=4
	print(4)

	
>>> t
5

函数里面修改全体变量可在函数内部修改,可是在函数外面,全体变量仍是原值

7 内嵌函数和闭包

def fun1():
	print("fun1...")
	def fun2():
		print("fun2...")
	fun2()           #这一句如果不加则无法打印出fun2()
>>> fun1()
fun1...
fun2...
>>> fun2()
Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    fun2()
NameError: name 'fun2' is not defined

8 闭包

>>> def funX(x):
	def funY(y):
		return(x*y)
	return funY

>>> funX(5)
<function funX.<locals>.funY at 0x00000210D0C7C158>
>>> type(funX(5))
<class 'function'>
>>> funX(8)
<function funX.<locals>.funY at 0x00000210D0C7C1E0>
>>> i=funX(5)
>>> i(5)
25
>>> funX(5)(6)
30
>>> funY(8)
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    funY(8)
NameError: name 'funY' is not defined



>>> def fun1():
	x=5
	def fun2():
		return (x *= x)
	return fun2()
SyntaxError: invalid syntax


>>> def fun1():
	x=5
	def fun2():
		x *= x
		return x
	return fun2()
>>> fun1()
Traceback (most recent call last):
  File "<pyshell#107>", line 1, in <module>
    fun1()
  File "<pyshell#106>", line 6, in fun1
    return fun2()
  File "<pyshell#106>", line 4, in fun2
    x *= x
UnboundLocalError: local variable 'x' referenced before assignment  # 局部变量不可修改全局变量
解决方法如下:s
>>> def fun1():
	x=[5]                #x=5//下一步x【0】就是5,前提就是首先令x为组
	def fun2():
		x[0] *= x[0]
		return x[0]
	return fun2()
>>> fun1()
25

第二种方法
>>> def fun1():
	x=5
	def fun2():
		nonlocal x         #说明它不是局部变量就可覆盖上面的x
		x *= x
		return x
	return fun2()

>>> fun1()
25



Lambda表达式            这个表达式太厉害害了吧
一个参数
>>> def ds(x):
	return 2*x+1

>>> ds(5)
11
>>> lambda x:2*x+1
<function <lambda> at 0x00000210D0C7C2F0>
>>> g=lambda x:2*x+1
>>> g(5)
11

两个参数
>>> lambda x,y :x+y
<function <lambda> at 0x00000210D0C7C2F0>
>>> z=lambda x,y:x+y
>>> z(3,4)
7

9 两个牛逼的BIF

Filter 过滤器

![在这里插入图片描述](https://img-blog.csdnimg.cn/d0cba9eed1254b18993abae7c292a748.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5oOF57O75reu5oCd,size_19,color_FFFFFF,t_70,g_se,x_16)
>>> filter(None,[1,0,False,True])
<filter object at 0x00000210D0C59D30>
>>> list(filter(None,[1,0,False,True]))
[1, True]
>>> def odd(x):
	return x%2
>>> t=range(10)
>>> show=filter(odd,t)
>>> list(show)
[1, 3, 5, 7, 9]

>>> list(filter((lambda x:x%2),range(10)))
[1, 3, 5, 7, 9]        /过滤出奇数

>>> list(filter((lambda x:x%2-1),range(10)))
[0, 2, 4, 6, 8]         /过滤出偶数


Map()函数
>>> list(map(lambda x:x*2,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]       //生成0~9数字

十一、递归

>>> def recursion():
	return recursion()

def jieceng(n):
    t = 1
    for i in range(1,n+1):
        t *= i
    return t
number = int(input("输入正整数:"))
jieceng(number)
#print("输入正整数的阶层是:",jieceng(number))
print("%d的阶层是%d" % (number,jieceng(number)))

def jieceng(i):
    if i == 0:
        return 1
    elif i == 1:
        return i
    elif i != (0 and 1):
        return i * jieceng(i-1)
y = int(input("请输入整数:"))
t = jieceng(y)
print("%d的阶层为%d"%(y,t))

1 fab数列函数

在这里插入图片描述

#def fab(i):
#    if i == 1:
#        return 1
#    elif i == 2:
#        return 1
#    else:
#        for j in range(1,i-1):
def  fab(t):
    z = [0,1,1]
    i = 2
    while t > i:
        z.append(z[i]+z[i-1])
        i += 1
    return z[t]    

在这里插入图片描述

def fab(x):
    list1 = [0,1,1]
    for i in range(3,x+1):
        y = list1[i-2] + list1[i-1]
        list1.append(y)
    return list1[x]

在这里插入图片描述
在这里插入图片描述

def fab(i):
    if i < 1:
        print("错误")         #迭代速度慢效率低理解简单
        return 0
    if i == 1 or i == 2:
        return 1
    else:
        return (fab(i-1) + fab(i-2))
t = fab(20)
if t != -1:
print("结果是:%d"% t)

2 迭代汉诺塔

在这里插入图片描述

def hanoi(n,x,y,z):
    if n == 1:
        print(x,"->",z)
    else:
        hanoi(n-1,x,z,y)
        print(x,"->",z)
        hanoi(n-1,y,x,z)

n = int(input("输入层数:"))
hanoi(n,"x","y","z")

十二、索引

>>> brand=["李宁","耐克","方方"]
>>> sloge=["一切皆有可能","just do it","我必成功"]
>>> print("方方口号:",sloge[brand.index("我必成功")])
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    print("方方口号:",sloge[brand.index("我必成功")])
ValueError: '我必成功' is not in list
>>> print("方方口号:",sloge[brand.index("方方")])
方方口号: 我必成功

十三、映射 、字典(大括号)

>>> t={"李宁":"一切皆有可能","耐克":"just do it","方方":"我必成功"}
>>> print("方方口号":,t["方方"])
SyntaxError: invalid syntax
>>> print("方方口号:",t["方方"])
方方口号: 我必成功



>>> dict1 = {1:"one",2:"two",3:"three"}
>>> dict1
{1: 'one', 2: 'two', 3: 'three'}
>>> dict2{}
SyntaxError: invalid syntax
>>> dict2 = {}
>>> dict2
{}


>>> dict3 = dict(("编程":"真的"),("好难":2))
SyntaxError: invalid syntax
>>> dict3 = dict(("编程":"真的"),("好难":2))
SyntaxError: invalid syntax
>>> dict3 = dict((("编程":"真的"),("好难":2)))
SyntaxError: invalid syntax
>>> dict3 = dict(("编程","真的"),("好难",2))
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    dict3 = dict(("编程","真的"),("好难",2))
TypeError: dict expected at most 1 arguments, got 2
>>> dict3 = dict((("编程","真的"),("好难",2)))    #最外层是函数中间是元组里面是映射
>>> dict3
{'编程': '真的', '好难': 2}

在这里插入图片描述
在这里插入图片描述

>>> dict4=dict("方方"="fang","fangfang"="方方")
SyntaxError: keyword can't be an expression
>>> dict4=dict("方方"="fang","fangfang"="方方")
SyntaxError: keyword can't be an expression
>>> dict4=dict(方方="fang",fangfang="方方")
>>> dict4
{'方方': 'fang', 'fangfang': '方方'}
>>> dict4=["方方"]="吴方方"
SyntaxError: can't assign to literal
>>> dict4["方方"]="吴方方"
>>> dict4
{'方方': '吴方方', 'fangfang': '方方'}

十四、字典

>>> dict5={}
>>> dict5.fromkeys{(1,2,3)}
SyntaxError: invalid syntax
>>> dict5.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict5.fromkeys((1,2,3),"number")
{1: 'number', 2: 'number', 3: 'number'}
>>> dict5.fromkeys((1,3),"number")
{1: 'number', 3: 'number'}
>>> dict5 = dict5.frombers(range(32),"赞")
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    dict5 = dict5.frombers(range(32),"赞")
AttributeError: 'dict' object has no attribute 'frombers'
>>> dict5 = dict5.fromkeys(range(32),"赞")
>>> dict5
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}
>>> for i in dict5.keys():
	print(i)

	
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> for i in dict5.values():
	print(i)

	
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
>>> for i in dict5.items():
	print(i)

	
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
(5, '赞')
(6, '赞')
(7, '赞')
(8, '赞')
(9, '赞')
(10, '赞')
(11, '赞')
(12, '赞')
(13, '赞')
(14, '赞')
(15, '赞')
(16, '赞')
(17, '赞')
(18, '赞')
(19, '赞')
(20, '赞')
(21, '赞')
(22, '赞')
(23, '赞')
(24, '赞')
(25, '赞')
(26, '赞')
(27, '赞')
(28, '赞')
(29, '赞')
(30, '赞')
(31, '赞')
>>> print(dict5[2])>>> dict5.clear()
>>> dict5()
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    dict5()
TypeError: 'dict' object is not callable
>>> dict5
{}

1 赋值不等于拷贝

>>> a=a(1:"wu",2:"fang",3:"fang")
SyntaxError: invalid syntax
>>> a={1:"wu",2:"fang",3:"fang"}
>>> b=a.copy()
>>> c=a
>>> id(a)
1409664323376     
>>> id(b)
1409664231536       #拷贝         不可改变原值
>>> id(c)
1409664323376        #赋值        可改变原值
>>> c[4]="shuaige"
>>> c
{1: 'wu', 2: 'fang', 3: 'fang', 4: 'shuaige'}
>>> a
{1: 'wu', 2: 'fang', 3: 'fang', 4: 'shuaige'}
>>> b[4]="chou"
>>> b
{1: 'wu', 2: 'fang', 3: 'fang', 4: 'chou'}
>>> a
{1: 'wu', 2: 'fang', 3: 'fang', 4: 'shuaige'}

在这里插入图片描述

>>> a.pop(2)
'fang'
>>> a
{1: 'wu', 3: 'fang', 4: 'shuaige'}
>>> a()
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    a()
TypeError: 'dict' object is not callable
>>> a.popitem()                      #随机弹出 字典弹出没有一定顺序
(4, 'shuaige')
>>> a
{1: 'wu', 3: 'fang'}


>>> b = {"xiaobai":"gou"}
>>> a.updata(b)
Traceback (most recent call last):
  File "<pyshell#75>", line 1, in <module>
    a.updata(b)
AttributeError: 'dict' object has no attribute 'updata'
>>> a.update(b)
>>> a
{1: 'wu', 3: 'fang', 'xiaobai': 'gou'}

十五、集合

>>> a={}
>>> type(a)
<class 'dict'>          #字典
>>> b={1,2,3}
>>> type(b)
<class 'set'>           #集合        无序性      唯一性



>>> b={1,2,4,2,2,2,2,2,23,3,3,3,3,3,3,31,6,4,93,22}
>>> b
{1, 2, 3, 4, 6, 22, 23, 93, 31}
>>> c = set([111111,2222,33333])
>>> c
{33333, 2222, 111111}
>>> c = set([1,1,1,1,2,2,2,2,2,3,3,3])
>>> c
{1, 2, 3}

1 运用数组与列表排序

>>> num = [1,1,1,3,38,8,8,8,3,3,2,4,4,4,4,4]
>>> num = list(set(num))
>>> num
[1, 2, 3, 4, 38, 8]
>>> num.sort()
>>> num
[1, 2, 3, 4, 8, 38]


Add
>>> num
[1, 2, 3, 4, 8, 38]
>>> num.add(6)                      #数组不行,集合可以
Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    num.add(6)
AttributeError: 'list' object has no attribute 'add'
>>> 
KeyboardInterrupt
>>> c = set([1,1,1,1,2,2,2,2,2,3,3,3])
>>> c
{1, 2, 3}
>>> c.add(6)
>>> c
{1, 2, 3, 6}
>>> c.add(4)
>>> c
{1, 2, 3, 4, 6}



Frozen    frozenset 不可变函数
>>> c = frozenset(c)
>>> c
frozenset({1, 2, 3, 4, 6})
>>> c.add(5)
Traceback (most recent call last):
  File "<pyshell#107>", line 1, in <module>
    c.add(5)
AttributeError: 'frozenset' object has no attribute 'add'

十六、文件

在这里插入图片描述
在这里插入图片描述


>>> f = open("D:\\xiaojiayu.txt")
>>> f
<_io.TextIOWrapper name='D:\\xiaojiayu.txt' mode='r' encoding='cp936'>
>>> f.read()
'这是小甲鱼\n测试\n测试'             #读完之后指到末尾
>>> f.read()
''


>>> f = open("D:\\xiaojiayu.txt")
>>> f.read(3)
'这是小'
>>> f.tell()
6
>>> f,read()
Traceback (most recent call last):
  File "<pyshell#115>", line 1, in <module>
    f,read()
NameError: name 'read' is not defined
>>> f = open("D:\\xiaojiayu.txt")
>>> f.read()
'这是小甲鱼\n测试\n测试'
>>> f.tell()
22

在这里插入图片描述

>>> f = open("D:\\xiaojiayu.txt")
>>> f.seek(12,0)           #一个汉字两个字节
12
>>> f.readline()
'测试\n'


>>> f = open("D:\\xiaojiayu.txt")
>>> list(f)
['这是小甲鱼\n', '测试\n', '测试']


>>> f.seek(0.0)
0.0
>>> f.read()
'这是小甲鱼\n测试\n测试'
>>> f.seek(0,0)
0
>>> for each in f:
	print(each)
这是小甲鱼
测试
测试

创建test.txt文件
>>> f.write("我叫吴方方")
Traceback (most recent call last):
  File "<pyshell#132>", line 1, in <module>
    f.write("我叫吴方方")
io.UnsupportedOperation: not writable
>>> f = open("D:\\test.txt","w")
>>> f.write("我叫吴方方")
5
>>> f = open("D:\\test.txt""r")
Traceback (most recent call last):
  File "<pyshell#135>", line 1, in <module>
    f = open("D:\\test.txt""r")
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\test.txtr'
>>> f = open("D:\\test.txt","r")
>>> f.read(f)
Traceback (most recent call last):
  File "<pyshell#137>", line 1, in <module>
    f.read(f)
TypeError: argument should be integer or None, not '_io.TextIOWrapper'
>>> f.read()
'我叫吴方方'
>>> f.close()

1 文件操作(味道极吴方方)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

>>> f=open("D:\\test2.txt")
>>> print((f.read()).split())
['吴方方:加油', '味道极:嗯嗯', '吴方方:努力', '========', '味道极:好的', '吴方方:奋斗', '味道极:哦哦', '========', '吴方方:励志', '味道极:可以', '吴方方:吃苦', '味道极:必须']

十七、模块

在这里插入图片描述

>>> import random
>>> t = random.randint(1,10)
>>> t
5

>>> getcwd()
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    getcwd()
NameError: name 'getcwd' is not defined
>>> import os
>>> getcwd()
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    getcwd()
NameError: name 'getcwd' is not defined
>>> os.getcwd()
'D:\\Python3.7.0'
>>> os.listdir("D:\\")
['$RECYCLE.BIN', '(A盘)大黄蜂(MINI和精英版)', '17级信息学院电工微机视频.7z', '2013office', '360Downloads', '51单片机', 'AD', 'Altium', 'BaiduNetdiskDownload', 'Config.Msi', 'Desktop', 'Documents', 'emu8086', 'Examples', 'Excel', 'FileRecv', 'Help', 'Keil5', 'KuGou', 'Licenses', 'MSOCache', 'multisim 14.0三个', 'PanData', 'Pictures', 'PotPlayer', 'Pr CC2019', 'Premiere Pro CC2019', 'Products', 'Program Files', 'Program Files (x86)', 'python', 'Python3.7.0', 'Supportfiles', 'System Volume Information', 'test.txt', 'test2.txt', 'test3.txt', 'TIM', 'TIMQQ下载文件注明', 'VC++2010', 'WPS文档', 'xiaojiayu.txt', '二级C无纸化考试模拟软件', '二级C语言', '仿真压缩包', '卜宁波串口取模示波器软件', '坚果office', '大黄蜂(MINI和精英版)(B盘)', '戚有利office', '手机发送电脑文件', '杂乱乱码文件放置不懂', '正点原子战舰资料', '电赛', '百度网盘资料总汇国赛自选', '聊天文件与图片', '遥控光立方加单片机资料']
#RECYCLE.BIN是回收站

在这里插入图片描述
在这里插入图片描述

1 Try函数

f = open("我为什么是一个文件.txt")
print(f.read())
f.close()
====================== RESTART: D:/Python3.7.0/try函数.py ======================
Traceback (most recent call last):
  File "D:/Python3.7.0/try函数.py", line 1, in <module>
    f = open("我为什么是一个文件.txt")
FileNotFoundError: [Errno 2] No such file or directory: '我为什么是一个文件.txt'
>>>
另一种方式
try:
    f = open("我为什么是一个文件.txt")
    print(f.read())
    f.close()
except OSError:
    print("文件出错啦T_T")
>>> 
====================== RESTART: D:/Python3.7.0/try函数.py ======================
文件出错啦T_T
第三种方式
try:
    f = open("我为什么是一个文件.txt")
    print(f.read())
    f.close()
except OSError as reason:
    print("文件出错啦T_T\n错误的原因是:"+str(reason))
>>> 
===================== RESTART: D:\Python3.7.0\try函数2.py =====================
文件出错啦T_T
错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'



try:
    int("abc")
    sum = i + "1"
    f = open("我为什么是一个文件.txt")
    print(f.read())
    f.close()
except OSError as reason:
    print("文件出错啦T_T\n错误的原因是:"+str(reason))
except TypeError as reason:
    print("类型相加出错啦T_T\n错误的原因是:"+str(reason))
except ValueError as reason:
    print("类型转换出错啦T_T\n错误的原因是:"+str(reason))
>>> 
===================== RESTART: D:/Python3.7.0/try函数3.py =====================
类型转换出错啦T_T
错误的原因是:invalid literal for int() with base 10: 'abc'
>>>

在这里插入图片描述
丰富的else语句和with语句
在这里插入图片描述
在这里插入图片描述

While与else连用
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

这样不用写f.close() 较为方便

十八、图形用户界面入门(EasyGui)

第一种方法

>>> import easygui
>>> easygui.msgbox("sss")
'OK'
第二种方法
>>> from easygui import *
>>> msgbox("吴方方")
'OK'
第三种方式    (推荐这种方法)
>>> import easygui as g
>>> g.msgbox("www")
'OK'

十九、类和对象(无处不对象)

class Turtle:    #类名词约定以大写字母开头
    """关于类的简单例子"""
    #属性
    color = "green"
    weight = 10
    legs = 4
    shell = True
    mouth = "大嘴"

    #方法
    def climb(self):         #一定要加self
        print("一")
        
    def run(self):
        print("二")
        
    def bite(self):
        print("三")
        
    def eat(self):
        print("四")
        
    def sleep(self):
        print("五")
>>> tt = Turtle()
>>> tt.eat()

1 类、属性、方法

上面只能说是类对象,还不是所说的对象,其实差不多,我现在半斤八两
用类来创建对象,创建的这个对象叫做实例,也叫实例对象
为啥对象非要用类来创建,可以一步到位吗?
盖房子先要有图纸,然后才有房子,没有图纸怎么建房子呢?
盖房子也就是实例,也就是类对象
上面tt就是实例,而后面的就是类

在这里插入图片描述

Turtle()本身就是将类实例化了,只是没有赋给变量,于是被python垃圾机理处理了。
类里面有属性 和 方法,方法就是def定义的类似函数那样
在这里插入图片描述

上面的sort和append就是平时常用的操作,而它就是类中的方法,我们才可以使用
还有继承也来说一下
在这里插入图片描述

上面定义myclass继承了上面的list,pass意思是只继承其他事不做,于是将此时类mylist实例化为list2,那么此时调用类中的sort方法都是可以的,由此可知平时所用的列表就是类了,而.sort就是类中的方法
在这里插入图片描述

A和b都是调用fun方法,结果却不一样,这就是多态

2 面向对象编程

类是图纸,类实例化的房子也就是对象也就是类对象才可以住人,一张图纸可以建造成千上万房子,这些房子都很相似,可是每位房子门牌号不同,于是门牌号就是self,
Self是什么?
Python无处不对象
在这里插入图片描述

注意上面Ball()中括号是没有参数,默认参数是setname中的name参数也就是需要两行第三下才可以kick打印出来
为什么都是调用kick方法,结果不一样呢?因为调用kick时会调用self,self就会找到上面的name属性,然后打印出来。
魔方方法
init(self) // 构造方法,实例化对象时,方法就会在创建时自动调用
在这里插入图片描述

注意这个里面是直接一行参数,第二行就可以kick打印了,就好像默认输入了函数,所以省略了一行代码。
其中ball()括号中也必须要有参数

公有和私有?
在这里插入图片描述

Name就是定义class类的属性
而第二个__name就是定义为了私有变量,所以下面出错了
在这里插入图片描述

只有内部才可以调用这个私有变量,只能从内部调用方法可以调用了
在这里插入图片描述

也可以这样调用,python只是将变量伪装了,采用上面也可以直接得出属性
继承,只是将名字修改为上面那样了。
在这里插入图片描述

注意上面是父类,而下面是子类,子类可以调用父类中的方法
在这里插入图片描述
在这里插入图片描述

注意上面报错的原因是,下面鲨鱼子类调用中本可以和上面一样下面来个pass就行了,可它右行__init__了父类中的self,因此就会报错了,我现在还不明白hungry是什么意思?init就是魔法方法,使用它较为方便。
在这里插入图片描述

此时就可以正常调用了,增加了一行调用
//类就是相当于c++中的this指针
继承者就是子类,被继承者就是父类,
在这里插入图片描述

使用super函数跟易用,因此它会自动帮你找到子类继承的父类,而不会出错了,hungry就相当于是定义的变量,也是使用了魔法方法,使用了魔法方法就很方便前面可以看到。为什么shark.move()就会报错呢?因为重写了self方法,而这个中没有x,一般使用super函数解决这个问题。
在这里插入图片描述

上面就是多重继承,一般不怎么使用

3 组合

下面就是组合
在这里插入图片描述

4 类对象、实例对象

在这里插入图片描述

注意里面的区别

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

我可一点也没懂,弹幕一群说懂了的,不行我要返回去看一看,我也要明白。刚刚重刷了一遍,这时我来理解一下,类对象和实例对象和类是三种不同的概念,无处不对象,上面class就是类写完之后就是类对象,然后下面的abc就是实例化对象,类定义到类对象到实例对象,C是类对象,c是实例对象,下面显示.count()时覆盖率C,所以还是10,而ab并没有赋值还是0,所以没有覆盖就是100。
在这里插入图片描述

上面是属性覆盖了方法,C是类对象,c是实例对象,x是C中的属性,c.x = 1是将属性赋值为1,那么此时再用c调用C中x方法就会出问题了。
在这里插入图片描述

此时上面正常进行,可是下面bb调用方法时却出了问题,为啥呢?
__dict__为对象属性字典
在这里插入图片描述

可我现在还不是特别明白。。。
在这里插入图片描述

这张图我就明白了,因为dd就是self,就是上面的dd.x=x dd.y=y 怪不得说self时默认呢?哈哈哈哈
在这里插入图片描述

已经十点半了,我要睡觉了,还有那个魔法方法我明白要弄明白。删除了CC,但是dd还存在,一个弹幕解释道,你烧毁了图纸,可是你建造的房子还存在鸭?哈哈哈哈我要早睡了。

额,昨晚我失眠了,大概十二点半左右睡着的,其实还好啦,可是可是,我早上睡到八点半,然后又很困,睡到了十点半,磨磨唧唧十一点才起来,这就是身体虚的表现啊,身体虚才会嗜睡,还是说明自己身体很差很差,我也需要有个人来陪我,来陪我,陪我戒让我不会很孤独。今天是第三天,第三天啊,我依旧是闷在这个小房间里,这个阴暗潮湿的房间里。
一些相关的BIF
不想看这个了,先不看了,就是这么任性哈哈

5 魔法方法构造和析构

在这里插入图片描述
在这里插入图片描述

Python就是面向对象编程,无处不对象,也就是类的实例化编程,上述过程中,你也可以单独def好几个函数,可是此时你就要调用每一个函数这个每个函数都要添加很多形参,而都封装在class中,你可以看到是多么的方便鸭。
至于下面的报错是因为,你不能在init时返回什么值,你可以看到上面中,都是下面def函数中才可以返回什么。下面警告中也说明了必须返回none,也就是不需要返回。
最重要一点就是,你看rect = rectangle(3,4)这句话吗?如果你此时不用__init__魔法方法时,你必须 首先rect = rectangle()然后后面还有一步赋值,上面有记录去翻翻看看。
在这里插入图片描述

这一块我没有理解好,还不会,不管了。

在这里插入图片描述
在这里插入图片描述

这些是弹幕,反正我还是不怎么明白。

6 模块

在这里插入图片描述
在这里插入图片描述

上面的hello.py与python.exe编译器在同一文件夹下,也就是hello.py python编译后缀文件放在了python3.7的安装包中,可是上面那个也会出错,下面就对了,因为上面中的hi函数,python必须要知道是哪个模块中的hi函数,模块就是程序就是==hello.py

在这里插入图片描述
在这里插入图片描述

这种导入模块名,可是模块名好长,每次都要应用,注意上面两个.py文件小甲鱼是建在了同一文件夹下面,我暂时还不知道分开建不同文件夹行不行呢?
在这里插入图片描述
在这里插入图片描述

上面两种调用方式等价,下面是调用所有函数,可是小甲鱼不建议使用上述两种方式,因为函数名字也不好记,容易看错
在这里插入图片描述

这种方式最好啦
在这里插入图片描述

此时运行这个temperatureConversion.py文件当然自然一定可以正常调用test函数,那么如果我们在刚刚上面calc.py模块中调用temperatureConversion.py文件也就是程序也就是模块的话,结果是?
在这里插入图片描述

怎么会这样呢?我们只需要temperatureConversion模块中的上面两个def函数,不需要下年tese函数也打印出来呀?那么我们可以使用_name_变量
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

这样调用就不会出现上面那种情况了,下面一个弹幕解释得很形象啊

在这里插入图片描述
在这里插入图片描述

上面是列表,列表里面存放各地址,python会从列表中寻找到有没有寻找到的导入模块,其中最佳存放模块位置就是site-packages,放在其它路径也行,但是推荐放在这个里面
在这里插入图片描述

注意上面出错的原因就是,IDLE外壳也就是python编译器找不到这个模块的路径,因为IDLE的文件夹下面找不到这个,注意看下面,test存放的是temper模块和calc模块
在这里插入图片描述

你可以把上面两个模块加到上面列表中路径中
在这里插入图片描述
在这里插入图片描述

上面红色弹幕的意思是替代\转义更方便
上面弹幕说了,添加路径只是暂时的,
在这里插入图片描述

模块是模块,后面还有包,包存放模块,因为python模块==程序太多了,所以都放在一起形成了包,函数的类,模块的包
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

像个极客一样去思考
Python自带电池就是自己的标准库

二十、爬虫

在这里插入图片描述

哈哈哈哈,满屏
论一只爬虫的自我修养
在这里插入图片描述
在这里插入图片描述
url就是网页
在这里插入图片描述

Urllib是包是package,里面有四个模块也就是程序也就是.py文件
在这里插入图片描述

上面这个是python官方文档网站接口,也就是入口
在这里插入图片描述

首先学会爬网页的心情是激动的,于是我第一次打开了我都QQ空间,于是太大卡住,第二次准备爬学校官网,爬之前在想不是改名了吗?于是还是抱着侥幸心理打开看还在,于是准备点进去看看,点进去已不是原来了,唉都变了,我母校就没有了,第二次打开淮师大爬,还是卡,于是第三次爬小甲鱼网站才成功。
在这里插入图片描述

不知为什么,这一节视频里最后还有彩蛋,就是下面的,原来还有彩蛋,不太清楚小甲鱼表达什么?但是,可以肯定的就是,人家的经历你没有经历过,就不会理解,也不可能理解,最后我还想说,妈的老污龟你有女朋友?老子还特么单身呢?
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

上面这个是与最上面那个等价的功能,

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

爬虫,我心都累了。下面还有优化后的爬虫程序,小甲鱼优化的。
在这里插入图片描述

这看起来很有意思啊,比如你将这段程序放在自己写的APP里面,不就有趣了吗?
在这里插入图片描述

哈哈哈哈,同感同感!

  • 7
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值