重学python入门知识

为什么重学

基础是保障,不重基础后面真的很难走。
神经网络学习遇到瓶颈了,那些代码真看不下去了,还是学长了解我们,安排了个看基础的任务 哈哈。
还是画上两个小时看看基础吧,找找自信的同时查缺补漏,希望能突破瓶颈吧!!!
我是小白,但想对小小白说,一定要打好基础,别只想着弄复杂代码,否则最后只会眼高手低。。。。
希望对新手有些用
从jupyter上导入的,黑色是代码,白色是输出

多谢B站up主:字节课
python原教程

函数

def 定义

内嵌函数

内嵌函数必须在上一个函数中调用,在外面调用无效,而且必须先定义后调用

如下,函数b是a的子函数,c是b的子函数,但a只能调用b这个子涵数,而不能调用子函数的子函数
下面函数不能调用上面的 会无限循环


def a():
    print("函数a")
    def b():
        print("函数b")
        def c():
            print("函数c")
        c()
    b()
    c()#这个c没找到
a()
函数a
函数b
函数c
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-1-06b4bfc54df9> in <module>
      8     b()
      9     c()#这个c没找到
---> 10 a()


<ipython-input-1-06b4bfc54df9> in a()
      7         c()
      8     b()
----> 9     c()#这个c没找到
     10 a()


NameError: name 'c' is not defined

函数名作为参数和返回值的调用

#作为参数调用
def a(x):
    x()
    x()
def b():
    print(666)
a(b)
666
666
#作为返回值
def a(x):
    print("hello",x)
def b():
    print("b函数")
    return a
i=b()#返回a函数 相当于i就是a函数
i('li si')
b函数
hello li si

函数闭包

def x(a):
    def y(b):
        return a+b
    return y
z=x(2)#函数作为返回值 a=2
z(3)#z相当于y() b=3

5

函数递归

就是自己调用自己

#阶乘
def a(n):
    if n==1:
        return 1
    else:
        return n*a(n-1)
a(5)
120

切片

a=np.arange(0,10)
b=a[:]#全部
c=a[:5]#前五个
d=a[1::2]#隔两个输出一次
e=a[-1:]#最后一个
f=a[::-1]#倒着输出
g=a[::-2]#倒着每隔两个输出
a,b,c,d,e,f,g
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
 array([0, 1, 2, 3, 4]),
 array([1, 3, 5, 7, 9]),
 array([9]),
 array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]),
 array([9, 7, 5, 3, 1]))
#字符串的切片处理
x=" shuaiqi "
while x[:1]==" ":
    x=x[1:]
while x[-1:]==" ":
    x=x[:-1] 
print(x)
shuaiqi

map函数

创建一个迭代器,使用来自的参数计算函数
每个迭代。当最短迭代器耗尽时停止。

两个参数,一个函数名,一个是函数自变量序列(可能有多个)

def a(x):
    return x * x
print(list(map(a,[1,2,3,4])))
[1, 4, 9, 16]
def add(x,y):
    return x+y
b=list(map(add,[1,2,3],[3,2,1,5]))# 先加起来,
b,list(map(a,b))#在平方,多的舍去
([4, 4, 4], [16, 16, 16])

filter 函数

返回正确的值

def a(x):
    if x > 5:
        return True
    else :
        return False
x=[9,1,3,1,4,8,9,7]
m=list(filter(a,x))
m,set(m)#set 查重并排序
([9, 8, 9, 7], {7, 8, 9})
    

lambde匿名函数

def a(x,y):
    return x+y
g=lambda x,y:x+y
a(1,2),g(1,2)#两者等效
(3, 3)

函数可变参数

函数参数不确定时

#以元组的形式传参
def fun(*a):
    print(a[:2])
    print(len(a))
fun(1,2,5,8,7,6)
(1, 2)
6
#以字典的形式传参
def fun(**a):
    print(a)
    print(len(a))
fun(a=1,b=2,c=5,d=8)
{'a': 1, 'b': 2, 'c': 5, 'd': 8}
4
def fun(x,y,*a,**b):
        print(x,y,a,b)
        print(len(a),len(b))
fun(1,2,5,9,7,a=1,b=2,c=5,d=8)
1 2 (5, 9, 7) {'a': 1, 'b': 2, 'c': 5, 'd': 8}
3 4

读取文件

open函数读取文件


'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists
'b'       binary mode
't'       text mode (default)
'+'       open a disk file for updating (reading and writing)
'U'       universal newline mode (deprecated)

read查看文件

readline一行一行的读取

readlines读取所有的行

tell告诉你读取到那个位置了

close关闭文件用完后必须关闭

with —as 可以自动关闭文件

a = open(r'D:/11.txt','r')
a.read()
'abcd\n1234\n675\nasd\n'
a=open(r'D:/11.txt','r')
a.readlines()
['abcd\n', '1234\n', '675\n', 'asd\n']
a=open(r'D:/11.txt','r')
a.readline(),a.readline()
('abcd\n', '1234\n')
#可以用列表读取文件的内容
a=open(r'D:/11.txt','r')
item=list(a)
for i in item:
    print(i)
item
abcd

1234

675

asd






['abcd\n', '1234\n', '675\n', 'asd\n']
a=open(r'D:/11.txt','r')
a.read(5),a.tell(),a.read(),a.tell() #read 读取后会记住上次其读取的位置,在下次读取时会接着上次读取
('abcd\n', 6, '1234\n675\nasd\n', 22)
a=open(r'D:/11.txt','rb')
a.read(5),a.tell(),a.read(),a.tell()#二进制方式读取\r是回车  \n是换行 各占一个字节
(b'abcd\r', 5, b'\n1234\r\n675\r\nasd\r\n', 22)
with open(r'D:/11.txt','rb') as a:
    s=a.read(6)
    print(s)
b'abcd\r\n'

异常

python中,按自上而下的顺序执行代码,如果中间有一行程序出错了,则不再往下执行,所以我们要知道哪些地方容易出错,用try提前处理

# 原文件中并没有2.txt这个文件
with open(r'D:/2.txt','rb') as a:
    print(a.read())
#现在知道open(2.txt)错误 但不影响下面的代码 但现在下面正常的代码不能执行
print("hello wlord")
print(5+6)
---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-27-babf4496aaa1> in <module>
      1 # 原文件中并没有2.txt这个文件
----> 2 with open(r'D:/2.txt','rb') as a:
      3     print(a.read())
      4 #现在知道open(2.txt)错误 但不影响下面的代码 但现在下面正常的代码不能执行
      5 print("hello wlord")


FileNotFoundError: [Errno 2] No such file or directory: 'D:/2.txt'
# 原文件中并没有2.txt这个文件
try :
    with open(r'D:/2.txt','rb') as a:
        print(a.read())
except:
    print("文件不存在,或者格式错误打不开")
print("hello wlord")
print(5+6)
文件不存在,或者格式错误打不开
hello wlord
11

错误类型

上面没有文件报错是FileNotFoundError,当然还有很多其他error

# 原文件中并没有2.txt这个文件

try :
    a='f'+1
    with open(r'D:/2.txt','rb') as a:
        print(a.read())
except FileNotFoundError as f:
    print(str(f))
except TypeError as t:
    print(str(t))
#这里两个地方都有错误,但只输出了第一个错 因为他俩在一个try中 ,按顺序执行
#若想两个错误都输出,可以用两个try
can only concatenate str (not "int") to str

用日志处理异常

一般异常会直接给你错误的头,但不向下执行,如果想向下执行,但还想找到错误源头可以用logging

def a():
    n= "a"+1
    return n
def b():
    m=a() +1
    return m

def c():
    try :
         return b()+2
    except TypeError as t:
        print(str(t))
c()
print(666)
#现在能往下输出 但只能输出错误 却找不到源头
can only concatenate str (not "int") to str
666
import logging
def a():
    n= "a"+1
    return n
def b():
    m=a() +1
    return m

def c():
    try :
         return b()+2
    except TypeError as t:
        logging.exception(t)
c()
print(666)
#现在能往下输出 也能找到错误源头
ERROR:root:can only concatenate str (not "int") to str
Traceback (most recent call last):
  File "<ipython-input-48-b7fd2d2f9222>", line 11, in c
    return b()+2
  File "<ipython-input-48-b7fd2d2f9222>", line 6, in b
    m=a() +1
  File "<ipython-input-48-b7fd2d2f9222>", line 3, in a
    n= "a"+1
TypeError: can only concatenate str (not "int") to str


666

猜你喜欢

转载自blog.csdn.net/weixin_45755332/article/details/106062191
今日推荐