文章目錄
- 數據
- 變量
- 數據結構
- 循環-判斷-用戶輸入
- 判斷
- 用戶輸入
- 循環
- 函數
- 參數
- 返回值
- 將函數存儲在模塊中
- 文件和異常
- 讀取文件
- 異常
- 操作Json文件
- 類對象
- 創建類
- 使用類
- 類的繼承
- 導入外部類
- 測試
- 測試函數
- 創建測試
Python 是一種廣泛使用的高級編程語言,以其清晰的語法和代碼可讀性而聞名。它由 Guido van Rossum 于 1991 年首次發布,并支持多種編程范式,包括面向對象、命令式、功能性和過程式編程。這里介紹一下python的基本語法。
數據
變量
在定義變量的時候Python和C++不同不需要指定變量的類型,是一種弱類型的語言。不過在定義變量名稱時仍有一些限制,變量名只能由字母數字和下劃線組成,變量名可以由字母或者下劃線開頭但是不能以數字開頭。
Python中用引號括起來的都是字符串,其中的引號既可以是單引號也可以是雙引號,引號都成對存在。為了方便操作字符串,python為字符串變量提供了很多方法供大家使用。
title():將字符串的首字母進行大寫
upper():將字符串的所有字母轉成大寫
lower():將字符串的所有字母轉成小寫
rstrip():暫時剔除字符串末尾的空白
lstrip():暫時剔除字符串頭部的空白
strip():剔除字符串兩端的空白
str():將數字轉成字符串
若想永遠移除字符串變量兩端的空白,需要在修改后再次賦值調用放法如下:
string1 = string1.rstrip()
數據結構
在python中通過括號類型來區分不同的數據類型,[]對應列表,()對應元組,{}對應字典。下面我們分別對這三種數據類型進行簡要介紹。
列表
列表使用[]表示類似于C++中的動態數組vector,下面我們以一個例子對字符串列表進行說明,定義列表bicycles來表示自行車品牌列表:
bicycles = ['feige' , 'giant', 'ongjiu', 'trek']# 元素之間用逗號來進行分割,元素序號從0開始而不是從1開始,打印第0個元素
# 列表中最后一個元素的編號為-1倒數第二個編號為-2,剩下的依次類推
print(bicycles[0])# 修改第0個元素
bicycles[0] = "ofo"# 追加元素 bicycles.append("newBike")# 特定位插入元素bicycles.insert(0,'ducadi')# 定義空列表
motorcycles = []# 末尾彈出元素
bicycles.pop()# 根據列表索引刪除元素
bicycles.pop(index)# 根據值刪除列表中的元素
bicycles.remove('ducadi')# 刪除第0個元素
# 方法remove只能刪除第一個遇到的元素,若是遇到多個則需要循環遍歷進行刪除del bicycles[0]# 對列表進行永久排序
bicycles.sort()# 按照字符表的反方向進行排序
bicycles.sort(reverse = True)# 對列表進行臨時排序
sorted(cars)# 獲取列表長度
lens(bicycles)# 永久翻轉列表的順序
bicycles.reverse() # 遍歷列表
for bicycle in bicycles:print(bicycle)# 列表的一部分稱為列表的切片
# 打印列表的前三個 不包含右邊界
print(bicycles[0,3])
# 打印前四個
bicycles[:4]
# 從第三個到最后
bicycles[2:]
# 最后三個元素
bicycles[-3:]# 遍歷切片
for bicycle in bicycles[:3]:print(bicycle.title())# 復制列表
newBicycles = bicycles[:]# 生成1到4的數字列表
# range函數生成的列表包含左邊界不包含右邊界
range(1,5)# 創建1到5的名為numbers的字符列表
numbers = list(range(1,6))# 創建2到11間隔為2的列表
range(2,11,2)
# 求列表中最大值,最小值,列表的和
max() min() sum()
# 求取1到10數值平方的列表
squares = []
for value in range(1,11)squares = value ** 2squares.append(square)
元組
元組用()表示,和列表相比元組的特性很明顯,列表可以修改而元組不可以修改,雖然不能修改元組的元素,但可以給存儲元組的變量從新賦值。相比于列表,元組是更簡單的數據結構,如果需要存儲一組值在程序的整個生命周期內不變,可以使用元組。其它方法元組的使用方法和列表相同。
字典
python中的字典類似于C++中map存儲的是鍵值對數據。在python中字典數據結構用{}來進行表示。字典是一系列的鍵值對,每個鍵都與一個值相關聯,可以通過鍵來訪問相對應的值,與鍵相對應的值可以是數字、字符串、列表乃至字典,事實上可將任何python對象用作字典中的值。
# 用一個字典來表示球員的姓名和得分
player_1 = {'name' : 'xiaoming', 'point' : 23}# 打印球員姓名和得分
print(player_1['name'])
print(player_1['point'])# 向字典中添加鍵值對
player_1["age"] = 33# 修改鍵值對
player_1["age"] = 30# 刪除鍵值對
del player_1["age"]# 創建一個空字典
player_2 = {}# 遍歷字典
for key, value in player_1.items():do something# 遍歷字典中的所有鍵
for key in player_1.keys():do something# 判斷鍵是否在對應的字典中
if 'name' in player_1.keys()
if 'name' not in player_1.keys()# 可以通過sorted()函數來獲得特定順序排列的鍵列表的副本
favorite_languages = {'jen' : 'python','salar' : 'C++','edward' : 'jave','phil' : 'ruby'
}
for name in sorted(favorite_languages.keys()):print(name.title() + "thanks you")# 遍歷字典中值
for language in favorite_languages.values():print(language.title())# 通過集合set剔除字典值中的重復項目
for language in set(favorite_languages.values()):print(language.title())# 字典嵌套
alien_0 = {'color' : 'green', 'point':45}
alien_1 = {'color' : 'blue', 'point':40}
alien_2 = {'color' : 'yello', 'point':42}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:print(alien)# 在字典中存儲列表
favorite_languages = {'Jenny' : ['ruby', 'java'],'Lily': ['c++', 'python'],'phil': ['perl', 'C']
}
for name, languages in favorite_languages.items():print(name.title() + "favorite languages are:")for language in languages:print(language)# 在字典中存儲字典
users = {'Lily' : {'first' : 'albert','last' : 'einstein','location' : 'princeton'},'mcurie' : {'first' : 'marie','last' : 'curie','location' : 'paris'}
}
for username, uer_info in user.items():print("uername" + uername)fullname = user_info["first"] + user_info["last"]location = user_info["location"]
循環-判斷-用戶輸入
判斷
python中進行判斷的關鍵字同樣是if,判斷條件和C++相同包括: ==、!=、<、<=、>、>=,多個條件同時成立用關鍵字 and 類似于C++中的 &&
if (age >= 21) and (age <= 35):do something# 多個條件只要一個為真即為真用關鍵字or類似于C++中的 ||
# 檢查特定值是否在列表中用in,判斷特定值是否不在列表中用not in
request_toppings = ['mushroom', 'onions', 'pipeline']
if 'mushroom' in reque_t-toppings:do something
if 'mushroom' not in request_toppings:do something# if-else語句
if condition1:do something
else:do something# 使用多個elif代碼塊
if condition1:do something
elif condition2:do something
elif condition3:do something
else:do something
用戶輸入
# 1.獲取字符串輸入
name = input("Please Enter your name")
print("hello" + name + "!")# 2.獲取數值輸入
age = input("How old are you")
age = int(age)# 3.運算符
# + 加法運算 – 減法運算 *乘法運算 /除法運算 ** 乘方運算 %求模運算(余數)
循環
# 用戶選擇何時退出
message = ''
while message != 'quit':message = input("input string")print(message)# 使用標志
active = True
while active:message = input("請輸入字符串:")if message == "quit":active = Falseelse:print(message)# 使用break退出
while True:city = input("enter the name of your city")if city == "quit":break;else:print("my city is" + city.title())# 使用continue繼續循環
current_number = 0
while current_number < 10:current_number += 1if current_number % 2 == 0:continueprint(current_number)# while循環處理列表和字典
# for循環中不應該修改列表否則將導致python難以追蹤其元素,要在遍歷列表同時對其進行修改,可使用while循環# 列表之間移動元素
unconfirmed_users = ['Alice', 'Jack', 'John']
confirmed_users = []
while unconfirmed_users:current_user = unconfirmed_users.pop()confirmed_users.append(current_user)# 刪除包含特定值的所有列表元素
pets = ['cat', 'dog', 'dog', 'goldfish','cat']
while 'cat' in pets:pets.remove('cat')# 使用用戶輸入來填充字典
responses = {}
polling_active = True
while polling_active:name = input("what is your name")response = input("what is your favorite subject?")responses[name] = responserepeat = input("would you like to let another person to response?(yes or no)")if(repeat == 'no'):polling_active = False
print("polling ended")
函數
參數
def greet_user(username):print("hello" + username.title() + "!")# 傳遞實參
def describe_bet(animal_type, pet_name):print("I have a" + animal_type + "named" + pet_name)
dscribe_bet('hamster', 'harry')# 鍵值對參數
describe_bet(animal_type="hamster", pet_name="harry") # 指定函數默認值
def describe_bet(pet_name, animal_type="dog"):do something# 傳遞列表
def greet_users(names):for name in names:msg = "hello" + name.title()print(msg)
usernames = ['Brice', 'Danny', "Lily"]
greet_users(usernames)function_name(listname[:]) # 如果需要禁止函數修改列表,向函數中傳遞列表的副本而不是原件,這樣函數所有的操作修改的都是副本而絲毫不影響原件
# 傳遞任意數量的實參
# 形參名*toppings中的星號讓Python創建一個名為toppings的空元組,并將所有的值都封到了這個元組中
def make_pizza(*toppings):print(toppings)
make_pizza('mushroom', 'greenpeppers', 'cheese')# 結合使用位置實參和任意數量實參
def make_pizza(size, *toppings):print("make a" + str(size) + "inch pizza")for topping in toppings:print("-" + topping)# 使用任意數量的關鍵字實參
def build_profile(first, last, **user_info):profile = {}profile['first_name'] = firstprofile['last_name'] = lastfor key, value in user_info.items():profile[key] = valuereturn profile
user_profile = build_profile('abert', 'einstein', location="priceton",field="physcis")
print(user_profile)
返回值
# 返回簡單值
def get_formatted_name(first_name, last_name):full_name=first_name + '' + last_namereturn full_name.title()# 返回字典
def build_person(first_name, last_name, age=''):person={'first':first_name, 'last':last_name}if(age):person['age'] = agereturn person
musician = build_person("jimi", 'hendrix', age=27)
將函數存儲在模塊中
# 導入整個模塊
imprt module_name
# 調用方法
module_name.function_name()
# 導入特定的函數
from module_name import function_0, function_1, function_2…
# 使用as給函數指定別名
from module_name import function_name as fn
# 使用as給模塊指定別名
import module_name as mn
# 導入模塊所有的函數
from module_name import *
函數編寫規范:
1.給形參指定默認值或調用關鍵字實參,等號兩邊不要有空格
2.代碼行的長度不要超過79個字符
3.模塊包含多個函數,可使用兩個空行將相鄰函數分開
4.文件頭沒有注釋時,所有的import語句都應放在文件開頭
文件和異常
為了提高程序的運行效率,在程序運行的時候,需要從文件中讀取數據,在運行結束之后需要將結果輸出到文件中,這個過程中程序需要進行文件操作。在程序運行的過程中可能由于某些原因導致崩潰,當程序面臨這些崩潰時如何操作,就是程序的異常處理。通過異常處理可以降低突發狀況的危害,提高程序的可用性和穩定性。
讀取文件
# 讀取整個文件
# 1.open傳遞文件的名稱,程序會在程序源文件所在的目錄去查找test.txt文件
# 2.關鍵字with在不需要訪問文件后將其關閉, 你只管打開文件,并在需要時訪問它,Python會在合適的時候自動將其關閉
# 3.read() 到達文件末尾時返回一個空字符串,而將這個空字符串顯示出來就是一個空行。要刪除末尾的空行,可在打印時使用rstrip()路徑
with open("test.txt") as file_object:contents = file_object.read()print(contents)
在open()中即可傳遞文件的相對路徑也可以傳遞文件的絕對路徑,Linux和OS X路徑中使用斜杠( / ), Window系統中路徑使用反斜杠( \ )
另外由于反斜杠在Python中被視為轉義標記,為在Windows中萬無一失,應以原始字符串的方式指定路徑,即在開頭的單引號前加上r逐行讀取,每一行的結尾都有一個看不見的換行符,打印出來會出現空開,通過rstrip()消除空白。
filename = "test.txt"
with open(filename) as file_object:for line in file_object:print(line.rstrip())# 創建一個包含文件各行內容的列表
filename = "test.txt"
with open(filename) as file_object:lines = file_object.readlines()
for line in lines:print(line.rstrip())# 寫入文件
# open中傳遞兩個參數第一個為文件名稱,第二個為文件的打開模式:
# w:寫入模式 r:讀取模式 a:附加模式 r+:讀寫模式
# 寫入模式w模式打開文件時要格外小心,因為如果指定的文件已經存在,python會在返回文件對象前清空該文件
filename = "test.txt"
with open(filename, 'w') as file_object:file_object.write("I Love Python")# 寫入多行
filename = "test.txt"
with open(filename) as file_object:file_object.write("I love python")file_object.write("I love create new things")
異常
# 使用try-except-else代碼塊處理異常
while True:first_number = input("\nFirst number:")if first_number == 'q':breaksecond_number = input("\n Second number:")
try:answer = int(first_number) / int(second_number)
except ZeroDivisionError:print("You can't divide by zero")
else:print(answer)# 處理FileNotFoundError異常
filename = "alice.txt"
try:with open(filename) as f_obj:contents = f_obj.read()
except FileNotFoundError:#異常可使用pass語句表示異常時不做任何處理msg = "Sorry the File" + filename + "does not exist"print(msg)
else:#計算文件中包含多少個單詞words = contents.split()num_words = len(words)print("The file has" + str(num_words) + "words")
操作Json文件
# 寫列表
import json
numbers = [2, 3, 5, 7, 9]
filename = "number.json"
with open(filename, 'w') as f_obj:json.dump(numbers, f_obj)# 讀列表
import json
filename = "number.json"
with open(filename) as f_obj:numbers = json.load(f_obj)
print(numbers)
類對象
面向對象編程是大型軟件開發的基礎,能極大的提高代碼的復用率,提高軟件的開發效率。在面向對象編程中最基礎的就是類的編寫和使用,本文將對Python中類的創建和使用方法進行簡要介紹。
創建類
下面我們以一個dog類為例進行說明,dog的屬性包括姓名和年齡,行為包括坐下和站起。
class Dog():def __init__(self,name,age):self.name = nameself.age = ageself.color = "red"def sit(self):print(self.name.title() + "is now sitting")def stand_up(self):print(self.name.title() + "stands up")def set_dog_color(self,dogcolor):self.color = dogcolor
通過上面的例子可知:
1.類的成員函數的第一個參數都是self類似于C++中的this指針,函數通過self和類關聯起來。
2.方法__init__()[注:開頭和末尾兩個下劃線],是一個特殊的函數,和C++類中的構造函數類似,負責對類的成員變量進行初始化,創建類時Python會自動調用它。
3.在調用函數的成員變量時都是通過self.paramer的方式進行訪問,類似于C++中通過this指針調用成員變量。
4.成員變量的屬性值可以通過__init__()傳入、可以在__init__()中指定默認值、可以通過對象名直接修改,還可以通過成員函數對成員變量進行修改。
5.類名稱的首字母一般都大寫
使用類
下面同樣以Dog類為例說明,類的使用方法:
class Dog():---snip—
my_dog = Dog("Billy",6)
my_dog.sit()
my_dog.stand_up()
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog's age is " + str(my_dog.age))
通過上面的例子可知
1.Python中不像C++中可以給每個變量設置訪問權限,所有變量均可以通過對象名來進行訪問。
2.所有的成員函數(init()除外)都可以通過對象名直接進行訪問。
類的繼承
一個類繼承另一個類時,它將自動獲得另一個類的所有屬性和方法:原有的類稱為父類,而新類稱為子類,子類繼承了其父類所有的屬性和方法,同時還可以定義自己的屬性和方法。
下面我們以汽車和電動汽車為例進行說明其中汽車為父類,電動汽車為子類
class Car():def __init__(self,make,model,year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_describe_name(self):long_name = str(self.yaer) + ' ' + self.make + ' ' + self.modelreturn long_name.title()def update_odometer(self, miles):self.odometer_reading += milesclass ElectricCar(Car):def __init__(self, make, model, year):super().__init(make, model, year)self.battery_size = 70def describe_battery(self):print("battery size is " + str(self.battery_size))def get_describe_name(self):print("This is a electric Car")# 調用
my_tesla = ElectricCar('tesla', 'models', 2016)
print(my_tesla.get_describe_name())
通過上面的例子可以知道:
1.創建子類時,父類必須包含在當前文件中,且位于子類的前面
2.定義子類時必須在括號內指定父類的名稱
3.在方法__init__()內傳遞父類所需要的信息
4.通過super()調用父類的__init__()方法
5.子類可以重寫父類的成員函數
6.類可以通過繼承或者組合的方式進行使用
導入外部類
隨著不斷添加新功能,文件可能變的很長,為了遵循python的總體理念,我們應盡可能讓文件整潔,為此我們可以將類存儲在不同的模塊中,然后在主程序中導入所需的模塊。
假如我們將Car和ElectricCar都定義在了car.py文件中。
# 導入Car類
from car import Car
# 同時導入Car類和ElectricCar類
from car import Car, ElectricCar
# 導入整個模塊
import car
# 導入整個模塊之后,通過模塊名來定義相關的類
import car
my_beetle = car.Car('volkswagen', 'beetle',2017)
# 導入模塊中的所有的類
from module_name import *
# 需要從一個模塊中導入很多類時,最好導入整個模塊
module_name.class_name()
類編碼風格
1.類名應該采用駝峰命名法,即將類名中的每個單詞的首字母進行大寫,而不使用下劃線,實例名稱和模塊名都采用小寫格式,單詞之間加上下劃線。
2.對于每個類,都應緊跟在類定義后面包含一個文檔字符串,這樣的字符串要簡要的描述類的功能,并遵循編寫函數的文檔字符串時采用的格式約定。每個模塊也都應包含一個文檔字符串對其中的類功能進行描述。
3.可以使用空行來進行代碼組織,但不要濫用。在類中,可以使用一個空行來分割方法;而在模塊中可以使用兩個空行來分隔類。
4.需要同時導入標準庫中的模塊和自己編寫的模塊時,先導入標準庫模塊再添加一個空行,然后再導入自己編寫的模塊。
測試
Python標準庫中模塊unitest提供了代碼測試工具。單元測試用于核實函數的某個方面沒有問題;測試用例是一組單元測試,這些單元測試一起核實函數在各種情形下的行為都復合要求。良好的測試用例考慮了函數可能收到的各種輸入,包含針對所有這些情形的測試。全覆蓋測試用例包含一整套單元測試,涵蓋了各種可能的函數使用方法。
測試函數
以下面函數作為被測試的函數
def get_formatted_name(first, last):full_name = first + " " + lastreturn full_name.title()
創建測試
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):def test_first_last_name(self):formatted_name = get_formatted_name('Janis', 'Jplin')self.assertEqual(formatted_name, 'Janis Jplin')
unittest.main()
方法必須以test_開頭,這樣它才會在運行測試腳本時自動運行;
測試中的各種斷言
assertEqual(a,b)
assertNotEqual(a,b)
assertTrue(x)
assertFalse(x)
assertIn(item, list)
assertNotIn(item, list)
創建要測試的類,幫助管理匿名調查
class AnonymousSurvey():def __init__(self, question):self.question = questionself.responses = []def show_question(self):print(self.question)def store_response(self, new_response):self.responses.append(new_response)def show_result(self):print("survey results:")for response in self.responses:print("." + response)
測試AnonymousSurvey()類:
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):def test_store_three_responses(self):question = "what's language did you first learn to speak?"my_survey = AnonymousSurvey(question)responses = ['English', 'Spanish', 'Chinese']for response in responses:my_survey.store_response(response)for response in responses:self.assertIn(response, my_survey.responses)
setup方法
setup()方法類似于測試類的構造函數,Python先運行它,再運行各個以test_開頭的方法,setup方法創建了測試需要的對象和數據。
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):def __init__(self):question = "what's your mother tongue?"self.my_survey = AnonymousSurvey(question)self.responses = ["English", "Spanish", "Chinese"]def test_store_three_responses(self):--snip—