重學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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章