python總結


以前學python的時候一直在網上找資料,看別人博客上的內容,學的東西感覺好亂,直到看了一本書:python編程從入門到精通,雖然基礎知識是我一天看完的,但是還是感覺豁然開朗,如果對於初學者,可以看看這本書,邊看,邊做上邊的練習題,感覺真的很棒!!由於記憶力不好,還是想把看到的知識總結一下,以備以后,查看,,,

1,字符串:

name="ada lovelace"

  • 首字母大寫 name.title()
  • 全部轉化為大寫 name.upper()
  • 全部轉化為小寫 name.lower()
  • 合並字符串 "hello" + name

name=" ada lovelace "

  • 刪除結尾空白:name.rstrip()
  • 刪除開頭空白:name.lstrip()
  • 刪除開頭和結尾空白:name.strip()

str():

age=23

  • message="happy"+age+"rd birthday!" #有錯誤
  • message="happy"+str(age)+"rd birthday!" #正確形式

2.列表

color=['red','yellow','blue',black]

  • 訪問列表元素:color[0]  #下標從 0開始,不是從1開始
  • 修改列表中的元素:color[1]="green"
  • 在列表中添加元素:color.append("white")
  • 在列表中插入元素:color.insert("orange")
  • 從列表中刪除元素:del color[0]
  •   color.pop() #刪除最后尾部的列表中的元素
  •   color.pop(1) #刪除指定位置上的元素
  •   color.remove("red")

列表排序:

  •   使用sort()方法對列表進行永久性排序:color.sort(recerse=True)
  •   使用sorted()方法對列表進行臨時排序:
  •     print(color)
  •         print(sorted(color))
  •     print(color)
  • 倒序打印列表:print(color.reverse())
  • 確定列表的長度:len(color)
  • 循環遍歷整個列表:
  •   for c in color:
  •     print(c)

數值列表 

  •   range()函數
  •     for value in rang(1,4): #從1開始到4結束
  •       print(value)
  •   創建數值列表:
  •     number=list(range(1,11,2))
  •   統計數值列表中的最大值:max(number)
  •   統計數值列表中的最小值:min(number)
  •   統計數值列表中的值的和:sum(number)
  •   數值列表的demo:
  •     squares=[value**2 for value in range(1,11)]
  •     print(squares)

使用列表中的一部分--切片

  •   print(color[0:3]) #從索引位置0開始到索引位置3結束  
  •   print(color[-3:]) #從索引位置倒數第三個到最后
  • 遍歷切片:
  •    for c in color[:3]:
  •     print(c)

復制列表:  

  •   color1=color[:]#此時color和color1兩個不是同一個列表,只是列表中的元素相同
  •   color1=color#此時color和color1兩個是同一個列表

3 元組:

  •  元組和列表的區別在於:列表可以改變列表元素,而元組不可以
  •  在外形上的區別是:元組是用小括號標識,列表是用中括號標識 

定義元組:

  dimensions=(200,50)

  print(dimensions[0])

遍歷元組中的所有值:

  for dimension in dimensions:

    print(dimension)

修改元組變量:  

  dimensions=(200,50)

  for dimension in dimensions:

    print(dimension)

  dimensions=(200,55)

  for dimension in dimensions:

    print(dimension)

4.字典

  • 字典是一系列的鍵值對:alient_0={"color":"red","points":"5"}
  • 訪問字典中的值:alient_0["color"]
  • 添加鍵值對:alient_0["x_posisiotn"]=25
  • 修改字典中的值:alient_0["color"]="yellow"
  • 刪除鍵值對:del alient_0["color"]
  • 由類似對象組成的字典:
  •    alient_0={
  •     "color":"red",
  •     "points":"5"
  •    }
  • 遍歷字典中所有的鍵值對:for key,value in alient_0.items():
  • 遍歷字典中的所有的鍵:for name in alient_0.keys(): 或 for name in alient_0:
  • 按順尋遍歷字典中的所有的鍵:for name in sorted(alient_0.keys()):
  • 遍歷字典中的所有值,用set集合來去重:for name in set(alient_0.vlaues()):

字典和字典,字典和列表,列表和列表,可以嵌套使用。。。

5函數

  • 當列表作為函數的參數時,為了不改變列表的值,可以使傳遞的參數是列表的副本:function_name(list_name[:])
  • 傳遞任意數量的參數:def make_pizza(*toppings)
  • 結合使用位置實參和任意數量實參:def make_pizza(size,*toppings)
  • 使用任意數量的關鍵字實參:def make_pizza(first,last,*toppings)

函數和模塊:模塊為擴展名為.py的文件,函數位於模塊中

  • 導入整個模塊:import pizza
  •        pizza.make_pizza(12,"apple")
  • 倒入特定的函數:from pizza import make_pizza
  • 使用as給函數指定別名:from module_name import function_namr as fn
  • 使用as給模塊指定別名:import module_name as mn
  • 導入模塊中的所有函數:from pizza import *
"""8-3 T恤 : 編寫一個名為make_shirt() 的函數, 它接受一個尺碼以及要印到T恤上的字樣。 這個函數應打印一個句子, 概要地說明T恤的尺碼和字樣。
使用位置實參調用這個函數來制作一件T恤; 再使用關鍵字實參來調用這個函數。
8-4 大號T恤 : 修改函數make_shirt() , 使其在默認情況下制作一件印有字樣“I love Python”的大號T恤。 調用這個函數來制作如下T恤: 一件印有默認字樣的大號T
恤、 一件印有默認字樣的中號T恤和一件印有其他字樣的T恤( 尺碼無關緊要) 。
8-5 城市 : 編寫一個名為describe_city() 的函數, 它接受一座城市的名字以及該城市所屬的國家。 這個函數應打印一個簡單的句子, 如Reykjavik is in
Iceland 。 給用於存儲國家的形參指定默認值。 為三座不同的城市調用這個函數, 且其中至少有一座城市不屬於默認國家。
"""
def make_shirt(size,words):
    print("大小是:"+ size+" 字樣是:"+words)

def make_shirt1(size,word="I love Python"):
    print("大小是:"+ size+" 字樣是:"+word)

def describe_city(city,country="China"):
    print(city + "is in "+country)


make_shirt("大號","apple")

make_shirt1("大號")
make_shirt1("中號")
make_shirt1("小號","是你")

describe_city("Reykjavik","Iceland")
describe_city("baoding")
describe_city("shenyang")

"""8-1 消息 : 編寫一個名為display_message() 的函數, 它打印一個句子, 指出你在本章學的是什么。 調用這個函數, 確認顯示的消息正確無誤。
8-2 喜歡的圖書 : 編寫一個名為favorite_book() 的函數, 其中包含一個名為title 的形參。 這個函數打印一條消息, 如One of my favorite books is
Alice in Wonderland 。 調用這個函數, 並將一本圖書的名稱作為實參傳遞給它。"""


"""8-6 城市名 : 編寫一個名為city_country() 的函數, 它接受城市的名稱及其所屬的國家。 這個函數應返回一個格式類似於下面這樣的字符串:
"Santiago, Chile"
至少使用三個城市-國家對調用這個函數, 並打印它返回的值。
8-7 專輯 : 編寫一個名為make_album() 的函數, 它創建一個描述音樂專輯的字典。 這個函數應接受歌手的名字和專輯名, 並返回一個包含這兩項信息的字典。 使
用這個函數創建三個表示不同專輯的字典, 並打印每個返回的值, 以核實字典正確地存儲了專輯的信息。
給函數make_album() 添加一個可選形參, 以便能夠存儲專輯包含的歌曲數。 如果調用這個函數時指定了歌曲數, 就將這個值添加到表示專輯的字典中。 調用這個
函數, 並至少在一次調用中指定專輯包含的歌曲數。
8-8 用戶的專輯 : 在為完成練習8-7編寫的程序中, 編寫一個while 循環, 讓用戶輸入一個專輯的歌手和名稱。 獲取這些信息后, 使用它們來調用函
數make_album() , 並將創建的字典打印出來。 在這個while 循環中, 務必要提供退出途徑。"""

def city_country(city,country="China"):
    print(city + ", "+country)

def make_album(singer,zhuanji,num=""):
    person={"歌手":singer,"專輯":zhuanji}
    if num:
        person["數量"]=num
    return person




city_country("shanghai")
city_country("newyue","USA")
a=make_album('jimi', 'hendrix', num=27)
print(a)
b=make_album('jimi', 'hendrix')
print(b)

print("---------------")

while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")
    singer = input("歌手: ")
    if singer == 'q':
        break
    zhuanji = input("專輯: ")
    if zhuanji == 'q':
        break
    person=make_album(singer,zhuanji)
    print(person)

"""8-9 魔術師 : 創建一個包含魔術師名字的列表, 並將其傳遞給一個名為show_magicians() 的函數, 這個函數打印列表中每個魔術師的名字。
8-10 了不起的魔術師 : 在你為完成練習8-9而編寫的程序中, 編寫一個名為make_great() 的函數, 對魔術師列表進行修改, 在每個魔術師的名字中都加入字樣“the
Great”。 調用函數show_magicians() , 確認魔術師列表確實變了。
8-11 不變的魔術師 : 修改你為完成練習8-10而編寫的程序, 在調用函數make_great() 時, 向它傳遞魔術師列表的副本。 由於不想修改原始列表, 請返回修改后的
列表, 並將其存儲到另一個列表中。 分別使用這兩個列表來調用show_magicians() , 確認一個列表包含的是原來的魔術師名字, 而另一個列表包含的是添加了字
樣“the Great”的魔術師名字。"""

lists = ['iphone case', 'robot pendant', 'dodecahedron']
completed_lists = []

def show_magicians(completed_lists):
    for list in completed_lists:
        print("name is :"+list)

show_magicians(lists)

def make_great(lists,completed_lists):
    while lists:
        temp=lists.pop()
        completed_lists.append("the Great "+temp)


def make_great1(lists,completed_lists):
    while lists:
        temp=lists.pop()
        completed_lists.append("the Great "+temp)

make_great1(lists[:],completed_lists)
show_magicians(lists)
show_magicians(completed_lists)


"""8-12 三明治 : 編寫一個函數, 它接受顧客要在三明治中添加的一系列食材。 這個函數只有一個形參( 它收集函數調用中提供的所有食材) , 並打印一條消息, 對顧客
點的三明治進行概述。 調用這個函數三次, 每次都提供不同數量的實參。
8-13 用戶簡介 : 復制前面的程序user_profile.py, 在其中調用build_profile() 來創建有關你的簡介; 調用這個函數時, 指定你的名和姓, 以及三個描述你的鍵-值
對。
8-14 汽車 : 編寫一個函數, 將一輛汽車的信息存儲在一個字典中。 這個函數總是接受制造商和型號, 還接受任意數量的關鍵字實參。 這樣調用這個函數: 提供必不可
少的信息, 以及兩個名稱—值對, 如顏色和選裝配件。 這個函數必須能夠像下面這樣進行調用:
car = make_car('subaru', 'outback', color='blue', tow_package=True)
打印返回的字典, 確認正確地處理了所有的信息。"""

def make_pizza(*toppings):
    """打印顧客點的所有配料"""
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

def make_car(color, tow_package, **car_info):
    car={}
    car['color']=color
    car['tow_package']=tow_package
    for key,value in car_info.items():
        car[key]=value
    print(car)
make_car('albert', 'einstein',location='princeton',field='physics')

6類

class Dog():
    """一次模擬小狗的簡單嘗試"""
    def __init__(self, name, age):
        """初始化屬性name和age"""
        self.name = name
        self.age = age
    def sit(self):
        """模擬小狗被命令時蹲下"""
        print(self.name.title() + " is now sitting.")
    def roll_over(self):
        """模擬小狗被命令時打滾"""
        print(self.name.title() + " rolled over!")

 

__init__()類似於java中的構造方法,形參self必不可少,還必須放在其他的形參的前邊。為何必須在方法定義中包含形參self 呢? 因為Python調用這個__init__() 方法來創建Dog 實例時, 將自動傳入實參self 。 每個與類相關聯的方法調用都自動傳遞實參self , 它是一個指向實例本身的引用, 讓實例能夠訪問類中的屬性和方法。 我們創建Dog 實例時, Python將調用Dog 類的方法__init__() 。 我們將通過實參向Dog() 傳遞名字和年齡; self 會自動傳遞,因此我們不需要傳遞它。 每當我們根據Dog 類創建實例時, 都只需給最后兩個形參( name age ) 提供值。

調用方法:

my_dog = Dog('willie', 6)
my_dog.sit()
my_dog.roll_over()

繼承

class Car():
    """一次模擬汽車的簡單嘗試"""
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += miles

class ElectricCar(Car):
    """電動汽車的獨特之處"""
    def __init__(self, make, model, year):
        """初始化父類的屬性"""
        super().__init__(make, model, year)
     self.battery_size = 70
   def describe_battery(self):
  
"""打印一條描述電瓶容量的消息"""
  
print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla
= ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name())

 super() 是一個特殊函數,幫助Python將父類和子類關聯起來。這行代碼讓Python調用ElectricCar 的父類的方法__init__() ,讓ElectricCar 實例包含父類的所有屬性。 父類也稱為超類 ( superclass) , 名稱super因此而得名

重寫父類方法:

  可在子類中定義一個這樣的方法, 即它與要重寫的父類方法同名。 這樣,Python將不會考慮這個父類方法, 而只關注你在子類中定義的相應方法。 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM