<kbd id="5sdj3"></kbd>
<th id="5sdj3"></th>

  • <dd id="5sdj3"><form id="5sdj3"></form></dd>
    <td id="5sdj3"><form id="5sdj3"><big id="5sdj3"></big></form></td><del id="5sdj3"></del>

  • <dd id="5sdj3"></dd>
    <dfn id="5sdj3"></dfn>
  • <th id="5sdj3"></th>
    <tfoot id="5sdj3"><menuitem id="5sdj3"></menuitem></tfoot>

  • <td id="5sdj3"><form id="5sdj3"><menu id="5sdj3"></menu></form></td>
  • <kbd id="5sdj3"><form id="5sdj3"></form></kbd>

    【學(xué)習(xí)筆記】Python基礎(chǔ)知識點

    共 30119字,需瀏覽 61分鐘

     ·

    2021-04-06 11:28


    大家好,歡迎來到 Crossin的編程教室 !
    今天給大家分享份python基礎(chǔ)知識點的學(xué)習(xí)筆記,供各位參考,查漏補缺。
    想要從零學(xué)習(xí)Python的同學(xué),可以從我們的微信教程學(xué)起。更新版地址:
    python666.cn

    一、Day10.print1.輸入輸出2.格式輸入輸出3.輸入密碼不可見4.驗證,python縮進(jìn)5.指向---修改字符串6.注釋`''' '''`內(nèi)涵7.模塊初始sys與os8.三元運算9.python3特性10.bytes與str轉(zhuǎn)化11.循環(huán)12.練習(xí)---三級菜單二、Day21.編碼變換2.文件3.全局變量4.list操作5.Tuple操作6.Set操作7.字符串操作8.字典9.函數(shù)10.高階函數(shù)

    一、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()就會報錯(雖然輸入為數(shù)字,但是print(type(age))為str型),因為python如果不強(qiáng)制類型轉(zhuǎn)化,就會默認(rèn)字符型
    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()就會報錯(雖然輸入為數(shù)字,但是print(type(age))為str型),因為python如果不強(qiáng)制類型轉(zhuǎn)化,就會默認(rèn)字符型
    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()就會報錯(雖然輸入為數(shù)字,但是print(type(age))為str型),因為python如果不強(qiáng)制類型轉(zhuǎn)化,就會默認(rèn)字符型
    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縮進(jìn)

    _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的內(nèi)存地址,name指向改了,但是name2不變
    print("My name is", name,name2) # PaoChe Ge Alex Li
    print("您好,我來了")

    6.注釋`''' '''`內(nèi)涵

    # 第一種情況就是注釋
    '''print("這是一行注釋")'''
    #第二種情況就是打印多行字符串
    str='''這是第一行內(nèi)容
    這是第二行內(nèi)容'''

    print(str)
    # 3.單套雙,雙套單都可以
    str1="i'am a student"
    print(str1)

    7.模塊初始sys與os

    import sys
    # 打印環(huán)境變量
    print(sys.path)

    print(sys.argv)
    print(sys.argv[2])

    # 進(jìn)度條
    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()執(zhí)行后直接輸出到終端,然后結(jié)束,最后cmd_res保存的是os.system()執(zhí)行后的狀態(tài)碼
    print("--->",cmd_res) # ---> 0

    cmd_res1=os.popen("dir")
    print("--->",cmd_res1) # 得到的是內(nèi)存對象值 ---> <os._wrap_close object at 0x00000000029187B8>
    cmd_res1=os.popen("dir").read()
    print("--->",cmd_res1) # 讀取數(shù)據(jù)必須再后面加個read()

    os.mkdir("new_dir3"# 創(chuàng)建一個目錄
    os.removedirs("new_dir"# 刪除一個目錄

    8.三元運算

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

    9.python3特性

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

    10.bytes與str轉(zhuǎn)化

    msg="我愛北京天安門"

    print(msg)
    print(msg.encode(encoding="utf-8")) # str轉(zhuǎn)bytes,編碼
    print(msg.encode(encoding="utf-8").decode(encoding="utf-8")) # bytes轉(zhuǎn)str,解碼

    11.循環(huán)

    print("第一種循環(huán)")
    count = 0
    while True:
        print("count:",count)
        count+=1
        if(count==10):
            break
    print("第二種循環(huán)")
    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.練習(xí)---三級菜單

    data={
        '北京':{
            "昌平":{
                "沙河":["oldboys",'test'],
                "天通苑":["鏈家地產(chǎn)","我愛我家"]
            },
            "朝陽":{
                "望京":["oldboys",'默陌陌'],
                "國貿(mào)":["CICC","HP"],
                "東直門":["Advent","飛信"]
            },
            "海淀":{}
        },
        '山東':{
            "德州":{},
            "青島":{},
            "濟(jì)南":{}
        },
        '廣東':{
            "德州":{},
            "青島":{},
            "濟(jì)南":{}
        },
    }
    exit_flag = False
    while not exit_flag:
        for i in data:
            print(i)
        choice=input("選擇進(jìn)入1>>:")
        if choice in data:
            while not exit_flag:
                for i2 in data[choice]:
                    print("\t",i2)
                choice2=input("選擇進(jìn)入2>>:")
                if choice2 in data[choice]:
                    while not exit_flag:
                        for i3 in data[choice][choice2]:
                            print("\t\t", i3)
                        choice3 = input("選擇進(jìn)入3>>:")
                        if choice3 in data[choice][choice2]:
                            for i4 in data[choice][choice2][choice3]:
                                print(i4)
                            choice4=input("最后一層,按b返回>>:")
                            if choice4=='b':
                                pass # pass可以理解為占位符,表示什么都不做,返回循環(huán)起始位置,以后可以在此處添加內(nèi)容
                            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互相轉(zhuǎn)化需要通過Unicode作為中介
    s="我愛北京天安門"  # 默認(rèn)編碼為Unicode
    print(s.encode("gbk")) # Unicode可直接轉(zhuǎn)化為gbk
    print(s.encode("utf-8")) # Unicode可直接轉(zhuǎn)化為utf-8
    print(s.encode("utf-8").decode("utf-8").encode("gb2312")) # 此時s.encode("utf-8")即轉(zhuǎn)為utf-8了,然后轉(zhuǎn)為gb2312,則需要先告訴Unicode你原先的編碼是什么,即s.encode("utf-8").decode("utf-8"),再對其進(jìn)行編碼為gb2312,即最終為s.encode("utf-8").decode("utf-8").encode("gb2312")

    2.文件

    f=open('ly.txt','r',encoding='utf-8'# 文件句柄 'w'為創(chuàng)建文件,之前的數(shù)據(jù)就沒了
    data=f.read()
    print(data)
    f.close()

    f=open('test','a',encoding='utf-8'# 文件句柄 'a'為追加文件 append
    f.write("\n阿斯達(dá)所,\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()) # 刷新緩沖區(qū)
    # 進(jìn)度條
    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()


    # 實現(xiàn)簡單的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語句---為了避免打開文件后忘記關(guān)閉,可以通過管理上下文
    with open('ly.txt','r',encoding='utf-8'as f:
        for line in f:
            print(line.strip())
    # python2.7后,with又支持同時對多個文件的上下文進(jìn)行管理,即:
    with open('ly.txt','r',encoding='utf-8'as f1,open('ly2.txt','r',encoding='utf-8'):
        pass

    3.全局變量

    names=["Alex","Jack","Rain"]

    # 除了整數(shù)和字符串在函數(shù)內(nèi)不能改,列表,字典這些可以改
    def change_name():
        names[0]="金角大王"
        print("inside func",names
              )

    change_name()
    print(names)

    # 當(dāng)全局變量與局部變量同名時,在定義局部變量的子程序內(nèi),局部變量起作用,在其它地方全局變量起作用。

    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() # 默認(rèn)刪除最后一個
    print(names)
    names.pop(1#刪除第二個元素
    print(names)
    print(names.index("Xu")) # 1
    print(names[names.index("Xu")]) #打印出找出的元素值3
    # 6.統(tǒng)計
    names.append("zhang"#再加一個用于學(xué)習(xí)統(tǒng)計"zhang"的個數(shù)
    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在列表嵌套應(yīng)用
    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區(qū)別就是淺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.列表循環(huán)
    for i in names:
        print(i)
    print(names[0:-1:2]) # 步長為2進(jìn)行切片
    # 0與-1都可以省略掉
    print(names[::2]) # 步長為2進(jìn)行切片

    # 淺拷貝三種方式
    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操作

    # 元組相當(dāng)于只讀列表,只有兩個方法一個是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 \033[31;1m%s\033[0m"%(p_item,salary))
                    else:
                        print("\033[41;1m你的余額只剩[%s]啦,還買個毛線\033[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  集合關(guān)系測試
    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互相都沒有的元素放在一塊,其實就是去掉重復(fù)元素
    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")) # 統(tǒng)計字母個數(shù)
    print(name.count("a")) # 統(tǒng)計字母個數(shù)
    print(name.center(50,"-")) #總共打印50個字符,并把nam放在中間,不夠的用-補上
    print(name.endswith("ex")) # 判斷字符串以什么結(jié)尾
    name="alex \tname is alex"
    print(name.expandtabs(tabsize=30)) # 將name中\(zhòng)t轉(zhuǎn)為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()包含所有字母及數(shù)字,如果不是這兩個,則為False
    print('ab123'.isalpha()) # False  isalpha()包含純英文字符
    print('1A'.isdecimal()) # 是否是十進(jìn)制 False
    print('1A'.isdigit()) # 是否是整數(shù) False
    print('_'.isidentifier()) #判斷是否是合法的標(biāo)識符,實質(zhì)是否為合法變量名 True
    print('aasd'.islower()) # 判斷是否是小寫 True
    print(''.isspace()) # 是否是空格 False
    print('My name is'.istitle()) # 字符串首字母大寫為title,否則不是
    print('+'.join(['1','2','3'])) # 對一列表中所有元素進(jìn)行join操作
    print(name.ljust(50,'*')) # 左對齊字符串,多余位用*補全
    print(name.rjust(50,'-')) # 右對齊字符串,多余位用*-補全
    print('\n Alex'.lstrip()) # 去掉左邊的空格/回車
    print('\nAlex\n'.rstrip()) # 去掉右邊的空格/回車
    print('\nAlex\n'.strip()) # 去掉左邊和右邊的空格/回車
    print('Alex')

    p=str.maketrans("abcdef","123456")
    print("alex li".translate(p))  #把alex li換成上一行對應(yīng)的值

    print("alex li".replace('l','L',1)) # 替換 1表示替換幾個l,從左到右計算替換個數(shù)
    print("alex li".rfind('l')) # 找到的最右邊的下標(biāo)返回
    print("alex li".split('l')) # 默認(rèn)將字符串按照空格分隔成列表,也可以在()中填寫相應(yīng)的分隔符,比如以字符l分隔,print("alex li".split(‘l’)),而且分隔符在列表中不會出現(xiàn)
    print("1+2+3+4".split('+')) # ['1', '2', '3', '4']
    print("1+2\n+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)
    '''
    # 隨機(jī)刪除
    info.popitem()
    print(info)
    '''

    # 4.多級字典嵌套及操作
    av_catalog = {
        "歐美":{
            "www.youporn.com": ["很多免費的,世界最大的","質(zhì)量一般"],
            "www.pornhub.com": ["很多免費的,也很大","質(zhì)量比yourporn高點"],
            "letmedothistoyou.com": ["多是自拍,高質(zhì)量圖片很多","資源不多,更新慢"],
            "x-art.com":["質(zhì)量很高,真的很高","全部收費,屌比請繞過"]
        },
        "日韓":{
            "tokyo-hot":["質(zhì)量怎樣不清楚,個人已經(jīng)不喜歡日韓范了","聽說是收費的"]
        },
        "大陸":{
            "1024":["全部免費,真好,好人一生平安","服務(wù)器在國外,慢"]
        }
    }
    b={
        'stu1101':"Alex",
        1:3,
        2:5
    }
    info.update(b) #將兩個字典合并,存在key,則更新value,不存在key,則合并
    print(info)
    print(info.items()) #把一個字典轉(zhuǎn)成列表
    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]="可以在國內(nèi)做鏡像" # 二級字典替換
    av_catalog.setdefault("taiwan",{"www.baidu.com":[1,2]}) # 如果不重名,即創(chuàng)建一個新的值,如果重名,將找到的值返回
    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.函數(shù)

    # 1.無參函數(shù)
    # 定義一個函數(shù)
    def fun1():
        '''testing'''
        print('in the fun1')
        return 1
    # 定義一個過程 實質(zhì)就是無返回值的函數(shù)
    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 action\n'%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])


    '''
    總結(jié):
        返回值數(shù)=0:返回None
        返回值數(shù)=1:返回object
        返回值數(shù)>1:返回tuple
    '''

    # 2.有參函數(shù)
    # 默認(rèn)參數(shù)特點:調(diào)用函數(shù)的時候,默認(rèn)參數(shù)非必須傳遞
    # 用途:1.默認(rèn)安裝值

    def test(x,y):
        print(x)
        print(y)

    test(1,2)     # 位置參數(shù)調(diào)用 與形參意義對應(yīng)
    test(y=1,x=2# 關(guān)鍵字調(diào)用,與形參順序無關(guān)
    test(3,y=2# 如果既有關(guān)鍵字調(diào)用又有位置參數(shù),前面一個一定是位置參數(shù),一句話:關(guān)鍵參數(shù)一定不能寫在位置參數(shù)前面
    '''
    比如加入一個參數(shù)z
    '''

    def test1(x,y,z):
        print(x)
        print(y)
        print(z)
    # 關(guān)鍵參數(shù)一定不能放在位置參數(shù)前面
    test1(3,4,z=6)
    test1(3,z=6,y=4)
    # 默認(rèn)參數(shù),
    def test(x,y,z=2):
        print(x)
        print(y)
        print(z)

    test(1,2)
    # 用*args傳遞多個參數(shù),轉(zhuǎn)換成元組的方式 *表示一個功能代號,表示接受的參數(shù)不固定,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個關(guān)鍵字參數(shù),轉(zhuǎ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'}

    # 默認(rèn)參數(shù)得放在參數(shù)組前面
    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.高階函數(shù)

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

    以上是對Python基礎(chǔ)知識點的一個總結(jié)筆記,需要的小伙伴可以收藏下來慢慢對照,檢驗自己的學(xué)習(xí)情況。
    想要從零學(xué)習(xí)Python的同學(xué),可以從我們的微信教程學(xué)起。更新版地址:

    python666.cn


    如果文章對你有幫助,歡迎轉(zhuǎn)發(fā)/點贊/收藏~

    作者:lightcity

    來源:光城


    _往期文章推薦_

    Python列表核心知識點匯總




    如需了解付費精品課程教學(xué)答疑服務(wù)
    請在Crossin的編程教室內(nèi)回復(fù): 666

    瀏覽 54
    點贊
    評論
    收藏
    分享

    手機(jī)掃一掃分享

    分享
    舉報
    評論
    圖片
    表情
    推薦
    點贊
    評論
    收藏
    分享

    手機(jī)掃一掃分享

    分享
    舉報

    <kbd id="5sdj3"></kbd>
    <th id="5sdj3"></th>

  • <dd id="5sdj3"><form id="5sdj3"></form></dd>
    <td id="5sdj3"><form id="5sdj3"><big id="5sdj3"></big></form></td><del id="5sdj3"></del>

  • <dd id="5sdj3"></dd>
    <dfn id="5sdj3"></dfn>
  • <th id="5sdj3"></th>
    <tfoot id="5sdj3"><menuitem id="5sdj3"></menuitem></tfoot>

  • <td id="5sdj3"><form id="5sdj3"><menu id="5sdj3"></menu></form></td>
  • <kbd id="5sdj3"><form id="5sdj3"></form></kbd>
    在线看黄色视频网站 | 男女拍拍视频免费 | 免费一区二区三区无码 | 五月天操逼网站 | 天天干天天插天天 |