1 字串相關函式

  • .title() # 將字串每個單詞的首字母大寫
  • .upper() #不改變字串變數的值
  • .lower() #不改變字串變數的值
  • f"{var} ,字串" # 將變數和字串格式化
  • .rstrip() # 去除字串尾空格,暫時的,再次訪問還原
  • .lstrip() # 去除字串頭空格
  • .strip() # 去除字串 頭和尾的空格
  • .split() # 以空格 將字串拆分成列表

2 計算符號

  • 3**2  # 9 3的2次方
  • 1_000_0000 # 大數可以使用_分割 不會影響

3 import this #Python之禪

4 列表

特定順序排列元素組成;元素間可無關係(不必同類型);索引從0開始;-1表示最後一個元素;

  • .append() # 列表末尾新增元素
  • .insert(index,var) # 在index處插入一個值,後面依次右移
  • del list[index] # 刪除index索引處元素,後面依次左移
  • .pop() # 刪除列表尾一個元素
  • .pop(index) # 刪除index處元素
  • .remove(var) # 刪除列表中第一齣現的var
  • .sort() # 按照字母表順序,大小排序;永久性;字母數字不可混合排序;
  • sorted(list) # 臨時排序,再次訪問還原
  • .reverse() # 反轉列表順序
  • len(list) # 確定列表長度
  • 遍歷列表
# 依據冒號和縮排

for var in list:

print(var)
  • range 建立數值列表
# 1 2 3 4 ;range(m,n) 最後m到n-1;
  • for value in range(1,5):
print(value)
  • var_list=list(range(1,5))
print(var_list)
  • range(2,11,2)
#從2開始,不斷加2,一直達到或者超過11
  • 列表解析
squares=[value**2 for value in range(1,11)]

print(squares)

# 輸出 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • list[0:3] # 返回索引0 1 2 元素
  • list[:4] # 返回前4個元素
  • list[2:] # 返回第三個到最後一個元素
  • list[-2:] # 返回倒數兩個元素
  • list[:] #複製列表;如果是list2=list1,只是將list2指標指向list1,並沒有真正複製建立一個新list
  • 檢查一個值在不在列表中
var_list=["nihao","nihaoa","nizhendehao"]

"nihao" in var_list

"nibuhao" not in var_list

5 元組

  • 不可變的列表
  • 定義 ,嚴格的說元組是由逗號標識的,定義只包含一個元素的元組,也必須在這個元素後面加上逗號,所以 dimensions=200,50 也是可以的
dimensions=(200,50) #元組使用圓括號

print(dimensions[0])
  • 修改元組變數,雖然不能修改元組的元素,但是可以給儲存元組的變數重新賦值
dimensions[0]=250 # 這個是錯誤的

dimensions=(250,50) # 這個是合法的

6 字典

  • 字典是一系列鍵值對,與鍵相關聯的值可以是數、字串、列表乃至字典等任意一個Python物件。
var_dic={'color':'green','point':5} # 建立字典

print(var_dic['color'])
  • 新增
var_kong_dic={} # 建立一個空的字典

var_kong_dic['nihao']="nihao" # 在字典中新增鍵值對

var_kong_dic['nibuhao']="nibuhao"

print(var_kong_dic)
  • 修改
var_kong_dic['nihao']="How are you?" # 修改值

print(var_kong_dic)
  • 刪除
del var_kong_dic['nibuhao'] #刪除鍵值對

print(var_kong_dic)
  • 獲取
point_value=var_kong_dic.get('point',"No point value assigned")

#直接列印字典不存在鍵值報錯,get不存在時返回第二個引數;沒有指定第二個引數返回None

print(point_value)
  • 遍歷
# 新增幾個值做演示

var_kong_dic['cnihaos']="nihao"#在字典中新增鍵值對

var_kong_dic['anihaoss']="nihao"#在字典中新增鍵值對

for k,v in var_kong_dic.items():

    print("Key:"+k)

    print("Value:"+v)
  • 獲取字典 鍵的 列表 # 同樣的,值 values
print(var_kong_dic.keys())

print(type(var_kong_dic.keys()))
  • 排序遍歷
for name in sorted(var_kong_dic.keys()):

print(name)
  • 刪除重複遍歷
for var_values in set(var_kong_dic.values())

print(var_values)
  • 區別 集合
# 集合 不會以特定的順序儲存元素

var_jihe={'python','java','C#'}

print(var_jihe)

字典 列表
alien_0={'color':'green','points':5} alien_1={'color':'red','points':10} alien_2={'color':'yellow','points':15} aliens=[alien_0,alien_1,alien_2] print(aliens)

7 函式相關

  • input函式

    • 讓程式暫停執行,等待使用者輸入並將使用者輸入賦值給一個變數,其引數是向用戶顯示的提示
message=input("Pleaseinputsomething:")

print(message) # input獲取的都是字串型別
  • 強制型別轉換
age=input("Howoldareyou?\n")

print(type(age))

print(":"+age)

age=int(age) # 強制型別轉化

print(type(age))

print(":"+str(age)) # 輸入字串+數字會報錯,所以還需要再來一次型別轉換
  • 傳遞任意數量的實參

形參中的 * 讓Python建立一個空元組(不可變),並將收到的所有值都封裝在這個元組中、

defmake_pizza(*toppings):

""""列印顧客所點的所有配料"""

print(toppings)

print(type(toppings))

make_pizza('peperoni')

make_pizza('mushrooms','greenpepers','extracheese')
  • 使用任意數量的關鍵字實參

    • 形參中的 ** 讓Python建立一個空字典,將所有名稱值對都放在字典中
defbuild_profile(first,last,**user_info):

"""建立一個字典,其中包含我們知道的有關使用者的一切"""

user_info['first_name']=first

user_info['last_name']=last

returnuser_info

user_profile=build_profile('albert','einstein',location='princeton',field='physics')

print(user_profile)

8 讀取/寫入 檔案

  • 讀取整個檔案
#原檔案中的換行會被讀取,但是列印末尾會多一個空行,因為read() 到達檔案末尾時會返回一個空字串,而將這個空字串顯示出來就是一個空行,如果要去除空行,就在字串末尾加一個  rstrip()

with open("pi.txt") as file_object:

contents=file_object.read()

print(contents)
  • 逐行讀取
#逐行讀取每行末尾都會有一個換行符,所以需要加一個rstrip去除

with open("pi.txt") as file_object:

    for line in file_object:

        print(line.rstrip())
  • 建立一個包含檔案各行內容的列表
with open("pi.txt") as file_object:

    lines=file_object.readlines()

print(type(lines))

print(lines)

print("\n")

for line in lines:

    print(line.rstrip())
  • 寫入空檔案
# 這樣會覆蓋掉原檔案中的內容,開啟檔案時的w引數,a 附加模式(在檔案末尾新增不會覆蓋原內容),r+讀寫模式,省略引數預設r 只讀模式

with open("pi.txt",'w') as file_object:

    file_object.write("I love programming.")

with open("pi.txt",'a') as file_object:

    file_object.write("\nI love programming,too.")
  • json 儲存與讀取
import json

numbers=[2,3,4,5,6,9]

# 儲存

filename='numbers.json'

with open(filename,'w') as f:

    json.dump(numbers,f)

f.close()

# 讀取

file_name2='numbers.json'

#異常處理

try:

    with open(file_name2,'r') as f:

        read_number=json.load(f)

except FileNotFoundError:

    print("The file is not found!")

else:

    print(read_number)

    print(type(read_number))

9 測試

  • 測試函式

    • name_function.py
def get_formatted_name(first,last,middle=''):

    """形參中指定預設值得形參 middle只能放在最後"""

    if middle:

        full_name=f"{first}.{middle}.{last}"

    else:

        full_name=f"{first}.{last}"

    return full_name
  • test_name_function.py
import unittest

# 匯入單元測試

from name_function import get_formatted_name

class NameTestCase(unittest.TestCase):

    """繼承 unittest.TestCase"""

    def test_first_last_name(self):

        """方法名必須test打頭,這樣才能自動執行"""

        formaated_name=get_formatted_name("jone","json")

        self.assertEqual(formaated_name,"jone.json")

        """斷言方法"""

    def test_test_first_last_middle_name(self):

        formatteed_name=get_formatted_name("A","B","C")

        self.assertEqual(formatteed_name,"A.B.C") # 形參順序不對會報錯的

if __name__=='__main__':

    unittest.main()
  • 測試類

    • survey.py
class AnonymousSurvey:

    """建構函式"""

    def __init__(self,question):

        """儲存 問題和 答案的變數"""

        self.question=question

        self.responses=[]

    """顯示調查問卷"""

    def show_question(self):

        print(self.question)

    """儲存單份調查問卷"""

    def store_response(self,new_response):

        self.responses.append(new_response)

    """顯示所有答案"""

    def show_results(self):

        print("Survey Results:")

        for var_response in self.responses:

            print(f"-{var_response}")
  • test_survey.py
  • # 匯入單元測試
    
    import unittest
    
    # 匯入測試的類檔案
    
    from survey import AnonymousSurvey
    
    class TestAnonymousSurvey(unittest.TestCase):
    
        """使用setUp函式 建立一個所有方法都可以使用的類和答案列表"""
    
        def setUp(self):
    
            question="What language did you first learn to speak?"
    
            self.my_survey=AnonymousSurvey(question)
    
            self.responses=['English','Chinese','Janpanese']
    
        def test_store_single_reponse(self):
    
            self.my_survey.store_response(self.responses[0])
    
            self.assertIn(self.responses[0],self.my_survey.responses)
    
        def test_store_three_reponses(self):
    
            for reponse in self.responses:
    
                self.my_survey.store_response(reponse)
    
            for reponse in self.responses:
    
                self.assertIn(reponse, self.my_survey.responses)
    
    if __name__=='__main__':
    
        unittest.main()