Python基礎長文

  • 2019 年 10 月 5 日
  • 筆記

Python基礎

字數統計:4,576 | 閱讀時長 ≈ 22

最近發的一些都是python的一些實際應用篇,今天落地,從基礎出發,將我的python自學之路:本年4月開始學python的基礎筆記,分享給各位,本文字數跟閱讀時間非常長,建議收藏或者實戰! 點擊公眾號右下角->聯繫我可以進入交流總群哦!備註:加群!

一、Day10.print1.輸入輸出2.格式輸入輸出3.輸入密碼不可見4.驗證,python縮進5.指向—修改字元串6.注釋`''' '''`內涵7.模組初始sys與os8.三元運算9.python3特性10.bytes與str轉化11.循環12.練習—三級菜單二、Day21.編碼變換2.文件3.全局變數4.list操作5.Tuple操作6.Set操作7.字元串操作8.字典9.函數10.高階函數三、作者的話

一、Day1

0.print

name = input("What is your name?")  print("Hello "+name )  # 或者print("Hello",name ),print中逗號分隔直接將字元串用空格分隔,若用+號連接,並且想留空格,則在前一字元串留空格即可  

1.輸入輸出

username=input("username:")  password=input("password:")  print(username,password)  

2.格式輸入輸出

# 第一種方法  name=input("Name:")  age=input("age:")  job=input("job:")    info='''---------info of ---------''' + '''  Name:'''+name+'''  Age:'''+age+'''  Job:'''+job  print(info)    # 第二種方法    name=input("Name:")  age=int(input("age:"))  #如果不用int()就會報錯(雖然輸入為數字,但是print(type(age))為str型),因為python如果不強制類型轉化,就會默認字元型  job=input("job:")    info='''---------info of ---------  Name:%s  Age:%d  Job:%s'''%(name,age,job)  print(info)      # 第三種方法    name=input("Name:")  age=int(input("age:"))  #如果不用int()就會報錯(雖然輸入為數字,但是print(type(age))為str型),因為python如果不強制類型轉化,就會默認字元型  job=input("job:")    info='''---------info of ---------  Name:{_name}  Age:{_age}  Job:{_job}'''.format(_name=name,_age=age,_job=job)  print(info)      # 第四種方法    name=input("Name:")  age=int(input("age:"))  #如果不用int()就會報錯(雖然輸入為數字,但是print(type(age))為str型),因為python如果不強制類型轉化,就會默認字元型  job=input("job:")    info='''---------info of ---------  Name:{0}  Age:{1}  Job:{2}'''.format(name,age,job)  print(info)  

3.輸入密碼不可見

import getpass  pwd=getpass.getpass("請輸入密碼:")  print(pwd)  

4.驗證,python縮進

_username='Alex Li'  _password='abc123'  username=input("username:")  password=input("password:")  if _username==username and _password==password:      print(("Welcome user {name} login...").format(name=username))  else:      print("Invalid username or password!")  

5.指向—修改字元串

print("Hello World")  name = "Alex Li"  name2=name  print(name)  print("My name is", name,name2) # Alex Li Alex Li  name = "PaoChe Ge"  # name2=name指的是name2與name一樣指向Alex Li的記憶體地址,name指向改了,但是name2不變  print("My name is", name,name2) # PaoChe Ge Alex Li  print("您好,我來了")  

6.注釋`''' '''`內涵

# 第一種情況就是注釋  '''print("這是一行注釋")'''  #第二種情況就是列印多行字元串  str='''這是第一行內容  這是第二行內容'''  print(str)  # 3.單套雙,雙套單都可以  str1="i'am a student"  print(str1)  

7.模組初始sys與os

import sys  # 列印環境變數  print(sys.path)    print(sys.argv)  print(sys.argv[2])    # 進度條  import time  for i in range(50):      sys.stdout.write('#')      sys.stdout.flush()      time.sleep(0.5)  
import os  cmd_res = os.system("dir") # os.system()執行後直接輸出到終端,然後結束,最後cmd_res保存的是os.system()執行後的狀態碼  print("--->",cmd_res) # ---> 0    cmd_res1=os.popen("dir")  print("--->",cmd_res1) # 得到的是記憶體對象值 ---> <os._wrap_close object at 0x00000000029187B8>  cmd_res1=os.popen("dir").read()  print("--->",cmd_res1) # 讀取數據必須再後面加個read()    os.mkdir("new_dir3") # 創建一個目錄  os.removedirs("new_dir") # 刪除一個目錄  

8.三元運算

# 1.result = 值1 if 條件 else 值2  d=a if a>b else c  print(d)  

9.python3特性

python3中最重要的新特性大概是對文本和二進位數據作了更為清晰的區分。文本總是Unicode,由str類型表示,  二進位數據則由bytes類型表示。Python3不會以任意隱式的方式混用str和bytes,正是這使得兩者區分特別清晰。  即:在python2中類型會自動轉化,而在python3中則要麼報錯,要麼不轉化  str與bytes相互轉化  

10.bytes與str轉化

msg="我愛北京天安門"    print(msg)  print(msg.encode(encoding="utf-8")) # str轉bytes,編碼  print(msg.encode(encoding="utf-8").decode(encoding="utf-8")) # bytes轉str,解碼  

11.循環

print("第一種循環")  count = 0  while True:      print("count:",count)      count+=1      if(count==10):          break  print("第二種循環")  count = 0  for count in range(0,10,2):      print("count:", count)    for i in range(0,10):      if i<5:          print("loop ",i)      else:          continue      print("hehe....")  my_age=28  count = 0  while count<3:      user_input=int(input("input your guess num:"))        if user_input==my_age:          print("Congratulations,you got it!")          break      elif user_input<my_age:          print("Oops,think bigger!")      else:          print("think smaller!")      count+=1      print("猜這麼多次都不對,你個笨蛋.")  

12.練習—三級菜單

data={      '北京':{          "昌平":{              "沙河":["oldboys",'test'],              "天通苑":["鏈家地產","我愛我家"]          },          "朝陽":{              "望京":["oldboys",'默陌陌'],              "國貿":["CICC","HP"],              "東直門":["Advent","飛信"]          },          "海淀":{}      },      '山東':{          "德州":{},          "青島":{},          "濟南":{}      },      '廣東':{          "德州":{},          "青島":{},          "濟南":{}      },  }  exit_flag = False  while not exit_flag:      for i in data:          print(i)      choice=input("選擇進入1>>:")      if choice in data:          while not exit_flag:              for i2 in data[choice]:                  print("t",i2)              choice2=input("選擇進入2>>:")              if choice2 in data[choice]:                  while not exit_flag:                      for i3 in data[choice][choice2]:                          print("tt", i3)                      choice3 = input("選擇進入3>>:")                      if choice3 in data[choice][choice2]:                          for i4 in data[choice][choice2][choice3]:                              print(i4)                          choice4=input("最後一層,按b返回>>:")                          if choice4=='b':                              pass # pass可以理解為佔位符,表示什麼都不做,返回循環起始位置,以後可以在此處添加內容                          elif choice4=='q':                              exit_flag=True                      if (choice3 == 'b'):                          break                      elif choice3 == 'q':                          exit_flag = True              if (choice2 == 'b'):                  break              elif choice2 == 'q':                  exit_flag = True        if (choice == 'b'):          break  

二、Day2

1.編碼變換

# utf-8與gbk互相轉化需要通過Unicode作為中介  s="我愛北京天安門"  # 默認編碼為Unicode  print(s.encode("gbk")) # Unicode可直接轉化為gbk  print(s.encode("utf-8")) # Unicode可直接轉化為utf-8  print(s.encode("utf-8").decode("utf-8").encode("gb2312")) # 此時s.encode("utf-8")即轉為utf-8了,然後轉為gb2312,則需要先告訴Unicode你原先的編碼是什麼,即s.encode("utf-8").decode("utf-8"),再對其進行編碼為gb2312,即最終為s.encode("utf-8").decode("utf-8").encode("gb2312")  

2.文件

f=open('ly.txt','r',encoding='utf-8') # 文件句柄 'w'為創建文件,之前的數據就沒了  data=f.read()  print(data)  f.close()    f=open('test','a',encoding='utf-8') # 文件句柄 'a'為追加文件 append  f.write("n阿斯達所,n天安門上太陽升")  f.close()    f = open('ly.txt', 'r', encoding='utf-8')  # 文件句柄    for i in range(5):  print(f.readline().strip())  # strip()去掉空格和回車      for line in f.readlines():      print(line.strip())    # 到第十行不列印    for index,line in enumerate(f.readlines()):      if index==9:          print('----我是分隔符-----')          continue      print(line.strip())  # 到第十行不列印  count=0  for line in f:        if count==9:          print('----我是分隔符-----')          count += 1          continue      print(line.strip())      count += 1  f = open('ly.txt', 'r', encoding='utf-8')  # 文件句柄  print(f.tell())  print(f.readline(5))  print(f.tell())  f.seek(0)  print(f.readline(5))  print(f.encoding)  print(f.buffer)  print(f.fileno())  print(f.flush()) # 刷新緩衝區  # 進度條  import sys,time  for i in range(50):      sys.stdout.write('#')      sys.stdout.flush()      time.sleep(0.5)  f = open('ly.txt', 'a', encoding='utf-8')  # 文件句柄  f.seek(10)  f.truncate(20) # 指定10到20個字元,10個字元前面留著,後面20字元清除  f = open('ly.txt', 'r+', encoding='utf-8')  # 文件句柄  print(f.readline().strip())  print(f.readline().strip())  print(f.readline().strip())  f.write("我愛中華")  f.close()      # 實現簡單的shell sed替換功能    f=open("ly.txt","r",encoding="utf-8")  f_new=open("ly2.txt","w",encoding="utf-8")    for line in f:      if "肆意的快樂" in line:          line=line.replace("肆意的快樂","肆意的happy")      f_new.write(line)    f.close()  f_new.close()    import sys  f=open("ly.txt","r",encoding="utf-8")  f_new=open("ly2.txt","w",encoding="utf-8")  find_str = sys.argv[1]  replace_str = sys.argv[2]  for line in f:      if find_str in line:          line=line.replace(find_str,replace_str)      f_new.write(line)  f.close()  f_new.close()    # with語句---為了避免打開文件後忘記關閉,可以通過管理上下文  with open('ly.txt','r',encoding='utf-8') as f:      for line in f:          print(line.strip())  # python2.7後,with又支援同時對多個文件的上下文進行管理,即:  with open('ly.txt','r',encoding='utf-8') as f1,open('ly2.txt','r',encoding='utf-8'):      pass  

3.全局變數

names=["Alex","Jack","Rain"]    # 除了整數和字元串在函數內不能改,列表,字典這些可以改  def change_name():      names[0]="金角大王"      print("inside func",names            )    change_name()  print(names)    # 當全局變數與局部變數同名時,在定義局部變數的子程式內,局部變數起作用,在其它地方全局變數起作用。  

4.list操作

__author__="Alex Li"  names="zhang Gu Xiang Xu"  names=["zhang","Gu","Xiang","Xu"]  # 1.切片  print(names[0],names[1],names[2])  print(names[1:3])  # 顧頭不顧尾,切片  print(names[-1]) # 在不知道多長情況下,取最後一個位置  print(names[-1:-3]) # 切片是從左往右,此時不輸出  print(names[-3:-1]) # 顧頭顧尾,去最後三個  print(names[-2:])  # 取最後兩個  print(names[0:3]) # 切片 等價於 print(names[:3])    # 2.追加  names.append("Lei")  print(names)  # 3.指定位置插入  names.insert(1,"Chen") # Gu前面插入  print(names)  # 4.修改  names[2]="Xie"  print(names)  # 5.刪除  # 第一種刪除方法  names.remove("Chen")  print(names)  # 第二種刪除方法  del names[1]  print(names)  # 第三種刪除方法  names.pop() # 默認刪除最後一個  print(names)  names.pop(1) #刪除第二個元素  print(names)  print(names.index("Xu")) # 1  print(names[names.index("Xu")]) #列印出找出的元素值3  # 6.統計  names.append("zhang") #再加一個用於學習統計"zhang"的個數  print(names.count("zhang"))  # 7.排序  names.sort() #按照ASCII碼排序  print(names)  names.reverse() # 逆序  print(names)  # 8.合併  names2=[1,2,3,4]  names.extend(names2)  print(names,names2)  # 9.刪掉names2  '''del names2'''  print(names2) # NameError: name 'names2' is not defined,表示已刪除  # 10.淺copy  names2=names.copy()  print(names,names2) # 此時names2與names指向相同  names[2]="大張"  print(names,names2) # 此時names改變,names2不變  # 11.淺copy在列表嵌套應用  names=[1,2,3,4,["zhang","Gu"],5]  print(names)  names2=names.copy()  names[3]="斯"  names[4][0]="張改"  print(names,names2) # copy為淺copy,第一層copy不變,後面的嵌套全部都變,修改names2與names都一樣  # 12.完整克隆  import copy  # 淺copy與深copy  '''淺copy與深copy區別就是淺copy只copy一層,而深copy就是完全克隆'''  names=[1,2,3,4,["zhang","Gu"],5]  # names2=copy.copy(names) # 這個跟列表的淺copy一樣  names2=copy.deepcopy(names) #深copy  names[3]="斯"  names[4][0]="張改"  print(names,names2)    # 13.列表循環  for i in names:      print(i)  print(names[0:-1:2]) # 步長為2進行切片  # 0與-1都可以省略掉  print(names[::2]) # 步長為2進行切片    # 淺拷貝三種方式  person=['name',['a',100]]  p1=copy.copy(person)  p2=person[:]  #其實p2=person[0:-1],0與-1均可以不寫  p3=list(person)  print(p1,p2,p3)  

5.Tuple操作

# 元組相當於只讀列表,只有兩個方法一個是count,一個是index    names=('alex','jack','alex')    print(names.count('alex'))  print(names.index('jack'))  # 購物籃程式    product_list=[('Iphone', 5800),                ('Mac Pro', 9800),                ('Bike', 5800),                ('Watch', 10600),                ('Coffee', 31),                ('Alex Python', 120),]  shopping_list=[]  salary=input("Input your salary:")    if salary.isdigit():      salary=int(salary)      while True:          '''for item in product_list:              print(product_list.index(item),item)          '''          for index,item in enumerate(product_list):              print(index,item)          user_choice=input("選擇要買嘛?>>:")          if user_choice.isdigit():              user_choice=int(user_choice)              if user_choice<len(product_list) and user_choice>=0:                  p_item=product_list[user_choice]                  if p_item[1]<=salary:                      shopping_list.append(p_item)                      salary-=p_item[1]                      print("Added %s into shopping cart, your current balance is 33[31;1m%s33[0m"%(p_item,salary))                  else:                      print("33[41;1m你的餘額只剩[%s]啦,還買個毛線33[0m"%salary)              else:                  print("product code[%s] is not exist!"%user_choice)          elif user_choice=='q':              print('-----------shopping list----------------')              for p in shopping_list:                  print(p)                  print("Your current balance:",salary)              exit()          else:              print("invalid option")  

6.Set操作

# 集合set  集合關係測試  list_1=[1,4,5,7,3,6,7,9]  list_1=set(list_1)  print(list_1,type(list_1))  list_2=set([2,6,0,6,22,8,4])  print(list_2,type(list_2))  print("--------------------------------")  # 取交集  print("方法一")  print(list_1.intersection(list_2))  print("方法二")  print(list_1&list_2)  print("--------------------------------")  # 取並集  print("方法一")  print(list_1.union(list_2))  print("方法二")  print(list_1|list_2)  print("--------------------------------")  # 差集 in list_1 but not in list_2  print(list_1.difference(list_2))  print(list_1-list_2)  print("--------------------------------")  # 子集  list_3=[1,4,6]  list_4=[1,4,6,7]  list_3=set(list_3)  list_4=set(list_4)  print(list_3.issubset(list_4))  print(list_4.issuperset(list_3))  print("--------------------------------")  # 對稱差集 把list_1與list_2互相都沒有的元素放在一塊,其實就是去掉重複元素  print(list_1.symmetric_difference(list_2))  print(list_1^list_2)  print("--------------------------------")  # 是否沒有交集 Return True if two sets have a null intersection.  list_5=set([1,2,3,4])  list_6=set([5,6,7])  print(list_5.isdisjoint(list_6))  print("--------------------------------")  # 基本操作  # 添加一項  list_1.add('x')  print(list_1)  # 添加多項  list_1.update([10,37,42])  print(list_1)  # 刪除一項  list_1.remove(10)  print(list_1)  # set長度  print(len(list_1))  # 測試9是否是list_1的成員  print(9 in list_1)  # pop()刪除並且返回一個任意的元素  print(list_1.pop())  # 刪除一個指定的值  list_1.discard('x')  print(list_1)  

7.字元串操作

name="alex"  print(name.capitalize()) # 首字母大寫  print(name.count("a")) # 統計字母個數  print(name.count("a")) # 統計字母個數  print(name.center(50,"-")) #總共列印50個字元,並把nam放在中間,不夠的用-補上  print(name.endswith("ex")) # 判斷字元串以什麼結尾  name="alex tname is alex"  print(name.expandtabs(tabsize=30)) # 將name中t轉為30個空格  print(name.find("x")) # 取索引  print(name[name.find("x"):]) # 字元串切片  name="my tname is {name} and i am {year} old"  print(name.format(name="alex",year=23))  print(name.format_map({'name':'alex','year':23}))  print('ab123'.isalnum()) #isalnum()包含所有字母及數字,如果不是這兩個,則為False  print('ab123'.isalpha()) # False  isalpha()包含純英文字元  print('1A'.isdecimal()) # 是否是十進位 False  print('1A'.isdigit()) # 是否是整數 False  print('_'.isidentifier()) #判斷是否是合法的標識符,實質是否為合法變數名 True  print('aasd'.islower()) # 判斷是否是小寫 True  print(''.isspace()) # 是否是空格 False  print('My name is'.istitle()) # 字元串首字母大寫為title,否則不是  print('+'.join(['1','2','3'])) # 對一列表中所有元素進行join操作  print(name.ljust(50,'*')) # 左對齊字元串,多餘位用*補全  print(name.rjust(50,'-')) # 右對齊字元串,多餘位用*-補全  print('n Alex'.lstrip()) # 去掉左邊的空格/回車  print('nAlexn'.rstrip()) # 去掉右邊的空格/回車  print('nAlexn'.strip()) # 去掉左邊和右邊的空格/回車  print('Alex')    p=str.maketrans("abcdef","123456")  print("alex li".translate(p))  #把alex li換成上一行對應的值    print("alex li".replace('l','L',1)) # 替換 1表示替換幾個l,從左到右計算替換個數  print("alex li".rfind('l')) # 找到的最右邊的下標返回  print("alex li".split('l')) # 默認將字元串按照空格分隔成列表,也可以在()中填寫相應的分隔符,比如以字元l分隔,print("alex li".split(『l』)),而且分隔符在列表中不會出現  print("1+2+3+4".split('+')) # ['1', '2', '3', '4']  print("1+2n+3+4".splitlines()) # ['1+2', '+3+4']  print("Alex Li".swapcase()) # aLEX lI  print('lex li'.title()) # Lex Li  print('lex li'.zfill(50)) #不夠以0填充  print('---')  

8.字典

# 字典無序  info={      'stu1101':"tengxun",      'stu1102':"baidu",      'stu1103':"ali",  }    print(info)  # 0.查找  # 方法一:確定存在  print(info["stu1101"]) # 查找若不在,則報錯  # 方法二:不確定存在,安全查找方法  print(info.get("stu11004")) # 查找不在不會報錯,直接返回None,若有直接返回  print('stu1103' in info) # True  # 1.修改  info["stu1101"]="騰訊"  print(info)  # 2.增加  info["stu1104"]="zhubajie"  print(info)  # 3.刪除  # 方法一  del info["stu1101"]  print(info)  # 方法二  info.pop("stu1102")  print(info)  '''  # 隨機刪除  info.popitem()  print(info)  '''  # 4.多級字典嵌套及操作  av_catalog = {      "歐美":{          "www.youporn.com": ["很多免費的,世界最大的","品質一般"],          "www.pornhub.com": ["很多免費的,也很大","品質比yourporn高點"],          "letmedothistoyou.com": ["多是自拍,高品質圖片很多","資源不多,更新慢"],          "x-art.com":["品質很高,真的很高","全部收費,屌比請繞過"]      },      "日韓":{          "tokyo-hot":["品質怎樣不清楚,個人已經不喜歡日韓范了","聽說是收費的"]      },      "大陸":{          "1024":["全部免費,真好,好人一生平安","伺服器在國外,慢"]      }  }  b={      'stu1101':"Alex",      1:3,      2:5  }  info.update(b) #將兩個字典合併,存在key,則更新value,不存在key,則合併  print(info)  print(info.items()) #把一個字典轉成列表  c=info.fromkeys([6,7,8],"test")  print(c)  c=info.fromkeys([6,7,8],[1,{'name':'alex'},444])  print(c)  c[7][1]['name']='Jack Chen' # 3個key共用一個value,修改一個則所有的都修改了  print(c)  print("--------")  av_catalog["大陸"]["1024"][1]="可以在中國做鏡像" # 二級字典替換  av_catalog.setdefault("taiwan",{"www.baidu.com":[1,2]}) # 如果不重名,即創建一個新的值,如果重名,將找到的值返回  print(av_catalog)  print(info.keys()) # 列印出所有的key  print(info.values()) # 列印出所有的value    print("---------------")  for i in info:      print(i,info[i])  #效率更高點  print("---------------")  for k,v in info.items():      print(k,v)  

9.函數

# 1.無參函數  # 定義一個函數  def fun1():      '''testing'''      print('in the fun1')      return 1  # 定義一個過程 實質就是無返回值的函數  def fun2():      '''testing2'''      print('in the fun2')    x=fun1()  y=fun2()  print(x)  print(y)  # 沒有返回值得情況下,python隱式地返回一個None  import time  def logger():      time_format='%Y-%m-%d %X %A %B %p %I'      time_current=time.strftime(time_format)      with open('a.txt','a+')as f:          f.write('time %s end actionn'%time_current)  def test1():      print('in the test1')      logger()      def test2():      print('in the test2')      logger()      return 0    def test3():      print('in the test3')      logger()      return 1,{5:"sda",6:"zad"},[1,2,3]    x=test1()  y=test2()  z=test3()    print(x) # None  print(y) # 0  print(z) # (1, {5: 'sda', 6: 'zad'}, [1, 2, 3])      '''  總結:      返回值數=0:返回None      返回值數=1:返回object      返回值數>1:返回tuple  '''  # 2.有參函數  # 默認參數特點:調用函數的時候,默認參數非必須傳遞  # 用途:1.默認安裝值    def test(x,y):      print(x)      print(y)    test(1,2)     # 位置參數調用 與形參意義對應  test(y=1,x=2) # 關鍵字調用,與形參順序無關  test(3,y=2) # 如果既有關鍵字調用又有位置參數,前面一個一定是位置參數,一句話:關鍵參數一定不能寫在位置參數前面  '''  比如加入一個參數z  '''  def test1(x,y,z):      print(x)      print(y)      print(z)  # 關鍵參數一定不能放在位置參數前面  test1(3,4,z=6)  test1(3,z=6,y=4)  # 默認參數,  def test(x,y,z=2):      print(x)      print(y)      print(z)    test(1,2)  # 用*args傳遞多個參數,轉換成元組的方式 *表示一個功能代號,表示接受的參數不固定,args可以隨意起名  def test(*args):      print(args)  test(1,3,4,5,5,6)  test(*[1,3,4,5,5,6]) # args=tuple([1,2,3,4,5])  def test(x,*args):      print(x)      print(args)  test(1,2,3,4,5,6,7) # 1 (2,3,4,5,6,7)  # 字典傳值 **kwagrs:把N個關鍵字參數,轉換成字典的方式  def test(**kwargs):      print(kwargs)      print(kwargs['name'],kwargs['age'],kwargs['id'],kwargs['sex'])    test(name='alex',age=8,id=10,sex='M') # {'name': 'alex', 'age': 8, 'id': 10, 'sex': 'M'}  test(**{'name':'alex','age':8,'id':10,'sex':'M'})  def test(name,**kwargs):      print(name)      print(kwargs)  test('alex',age=18,sex='M') # 字典 {'age': 18, 'sex': 'M'}    # 默認參數得放在參數組前面  def test(name,age=18,**kwargs):      print(name)      print(age)      print(kwargs)    test('alex',sex='M',hobby='tesla',age=3)  test('alex',3,sex='M',hobby='tesla')  test('alex') # 後面的**kwargs不賦值輸出為空字典  def test(name,age=18,*args,**kwargs):      print(name)      print(age)      print(args)      print(kwargs)  test('alex',age=34,sex='M',hobby='tesla') # alex 34 () {'sex': 'M', 'hobby': 'tesla'}  

10.高階函數

# 高階函數 變數可以指向函數,函數的參數能接受變數,那麼一個函數就可以接受另一個函數作為參數,這個函數就叫做高階函數  def f(x):      return x  def add(x,y,f):      return f(x)+f(y)  res=add(1,2,f)  print(res)  # 3