主要是記錄一些和C++里不一樣的以及我不知道的
變量的定義
message=”hello, world!”
字符串
- 單引號(hào),雙引號(hào)都可以翘贮,這樣就可以自由得在字符串中包含雙引號(hào)單引號(hào)啦
-
message.title()
會(huì)返回Hello, World!
(原字符串并不改變)
全部大寫(xiě)/小寫(xiě).upper/lower()
- 用
+
拼接 -
\t
制表符幻赚,\n
換行 - 返回刪除字符串末尾/開(kāi)頭/開(kāi)頭與末尾的多余空白后的字符串:
.rstrip()/.lstrip()/.strip()
(常用于在存儲(chǔ)用戶輸入前對(duì)其進(jìn)行清理) - 像matlab一樣終端可以當(dāng)計(jì)算器用禀忆,按回車輸出結(jié)果
- 2^3要寫(xiě)成
2**3
- 轉(zhuǎn)為字符串
str(23)
- 判斷一個(gè)字符串是否是另一個(gè)字符串的子串可以直接
if a in b:
列表
- 在列表中添加元素
xxs.append(x)
- 插入元素
xxs.insert(0, x)
- 刪除元素
del xxs[0]
- 刪除的同時(shí)獲取
x=xxs.pop(0) #不寫(xiě)參數(shù)的時(shí)候就是默認(rèn)刪去最后一個(gè)元素
- 根據(jù)值刪除
xxs.remove(x)
注:如果x有重復(fù)的remove只刪去第一個(gè),可以配合循環(huán)來(lái)使用
永久性排序 -
xxs.sort()
xxs.sort(reverse=True)
- 臨時(shí)性排序
sorted(xxs)
sorted(xxs, reverse=True)
- 反轉(zhuǎn)
xxs.reverse()
- 長(zhǎng)度
len(xxs)
- 創(chuàng)建數(shù)值列表
digits=list(range(2, 11, 2))
->[2, 4, 6, 8, 10]
min(digits)/max/sum
- 列表解析將for循環(huán)和創(chuàng)建新元素的代碼合成一行落恼,并自動(dòng)附加新元素
squares=[value**2 for value in range(1, 11)]
- 切片
digits[0:3]==digits[:3]
digits[-3:]
- 復(fù)制列表
digits2=digits[:]
digits2=digits
(這樣不行箩退,這樣只是讓digits2關(guān)聯(lián)到包含在digits中的列表) - 根據(jù)一個(gè)字符串創(chuàng)建單詞列表
string.split()
元組
不可變列表
dimensions=(200, 50)
雖然元組內(nèi)的元素不可以修改但可以給存儲(chǔ)元組的變量重新賦值
條件判斷
if a>b and a>c:
if a>b or a<c:
if x in xxs:
if x not in xxs:
if-elif-elif(-else)
- 確定列表是否為空
if xxs:
字典(無(wú)序)
alien_0={‘color’: ‘good’, ‘points’: 5}
print(alien[‘color’])
- 添加鍵值對(duì)
alien_0[‘x_position’]=0
- 創(chuàng)建空字典
alien_0={}
- 修改字典中的值
alien_0[‘color’]=’yellow’
- 刪除鍵值對(duì)
del alien_0[‘points’]
- 遍歷所有鍵值對(duì)
for k, v in user_0.items():
- 遍歷所有鍵
for k in user_0.keys():
/for k in user_0:
.keys()
方法返回一個(gè)列表
if k1 not in user_0.keys():
- 按順序遍歷字典中的所有鍵
for k in sorted(user_0.keys()):
- 遍歷所有值
for v in user_0.values():
返回所有值組成的列表 - 剔除重復(fù)元素
for v in set(user_0.values())
- 字典可以作為列表的元素
列表也可以作為字典的值
字典也可以作為字典的值 - 記錄了鍵值對(duì)順序的字典
from collections import OrderedDict
my_dict=OrderedDict()
輸入
message=input(‘please input your name:’)
注意返回的是字符串,可以用int()轉(zhuǎn)為數(shù)字
注意python2中是raw_input(如果用input的話用戶輸入會(huì)被視為python代碼并被執(zhí)行)
while循環(huán)
while n<5:
也可以用break佳谦, continue
函數(shù)
def 函數(shù)名(參數(shù)):
“””文檔字符串”””
python會(huì)用這個(gè)生成程序中函數(shù)的文檔
傳遞實(shí)參的多種方式
human(‘a(chǎn)lice”, 18)
human(name=’alice’, age=18)
也可以在編寫(xiě)函數(shù)的時(shí)候給形參指定默認(rèn)值
注意在形參列表中必須先列出沒(méi)有默認(rèn)值的形參注意在函數(shù)中對(duì)傳過(guò)去的參數(shù)進(jìn)行修改的話參數(shù)本身是會(huì)被改變的戴涝,這跟c++不一樣
(所有類型的參數(shù)還是只有列表?)禁止函數(shù)修改列表
function_name(list_name[:])
切片表示法創(chuàng)建副本還挺耗時(shí)的非必要的時(shí)候盡量不用傳遞任意數(shù)量的實(shí)參
預(yù)先不知道要接收多少個(gè)實(shí)參的情況钻蔑,python允許函數(shù)從調(diào)用語(yǔ)句中收集任意數(shù)量的實(shí)參
def make_pizza(*toppings):
print(toppings)
make_pizza(‘pepperoni’)
make_pizza(‘mushrooms’, ‘green pepper’, ‘extra chess’)
*
讓python創(chuàng)建一個(gè)空元組啥刻,并將收到的所有值都封裝到這個(gè)元組中
注意這種類型的形參應(yīng)該放在最后
def make_pizza(size, *toppings):
- 接收任意數(shù)量的實(shí)參,且預(yù)先不知道傳遞給函數(shù)的是代表什么的信息
傳遞任意數(shù)量的鍵值對(duì)
def build_profile(first, last, **user_info):
build_profile(‘a(chǎn)lbert’, ‘einstein’, location=’princeton’, filed=’physics’)
**
讓python創(chuàng)建一個(gè)空字典
- 將函數(shù)存儲(chǔ)在模塊中
模塊是名為.py
的文件
比如pizza.py
同一個(gè)文件夾下
import pizza
pizza.make_pizza()
導(dǎo)入特定函數(shù)
from module_name import function_name1, function_name2
調(diào)用時(shí)直接function_name()
指定別名
from pizza import make_pizza as mp
mp()
模塊也可以指定別名
導(dǎo)入模塊中所有函數(shù)咪笑,這樣也是直接用函數(shù)名來(lái)調(diào)用的(使用非自己編寫(xiě)的大型模塊使最好別這樣可帽,容易重名)
from module_name import *
類
class Dog():
“””模擬小狗”””
def _init_(self, 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!”)
每當(dāng)根據(jù)Dog類來(lái)創(chuàng)建新實(shí)例時(shí),都會(huì)自動(dòng)運(yùn)行_init_()
_init_
的形參中self
必不可少且位于最前面創(chuàng)建實(shí)例時(shí)自動(dòng)傳入窗怒,它是指向?qū)嵗旧淼囊?br>
以self
為前綴的變量可以被類的所有方法使用
python2中映跟,class ClassName(object)
,這樣類的行為就會(huì)比較像python3了
創(chuàng)建實(shí)例
my_dog=Dog(‘willie’, 6)
繼承
Class ElectricDog(Dog):
def _init_(self, name, age, power):
“””初始化父類屬性”””
super()._init_(name, age)
self.power=power
- python2中的繼承
Class Dog(object):
Class ElectricDog(Dog):
def _init_(self, name, age, power):
super(ElectricDog, self)._init_(name, age)
重寫(xiě)父類的方法
直接同名函數(shù)覆蓋就行類也可以保存在模塊中dog.py使用方法和上面的把函數(shù)存在模塊里一樣
from dog import Dog
文件
- 讀取整個(gè)文件
pi_digits.txt與使用它的.py文件在同一個(gè)目錄下
with open(‘pi_digits.txt’) as file_object:
contents=file_object.read()
print(content)
關(guān)鍵字with
會(huì)在不需要訪問(wèn)文件后將其關(guān)閉(如果使用close()
來(lái)關(guān)閉的話扬虚,可能會(huì)出現(xiàn)程序在執(zhí)行close語(yǔ)句前出了bug文件關(guān)不了的情況)
read()
到達(dá)文件末尾時(shí)返回一個(gè)空字符串努隙,會(huì)在原文件末尾多一個(gè)空行(要?jiǎng)h除空行可使用rstrip()
)
- 文件路徑
不在同一個(gè)目錄下的時(shí)候要提供路徑
1.相對(duì)于當(dāng)前運(yùn)行的程序所在目錄
比如程序在python_work中,文件在python_work的子文件text_files中
Linux/OS X
open(‘text_files/filename.txt’)
Win
open(‘text_files\filename.txt’)
2.絕對(duì)路徑
Linux/OS X
file_path=’/home/ehmatthes/other_files/text_files/filename.txt’
open(file_path)
Win
file_path=r’C:\Users\ehmatthes\other_files\text_files\filename.txt’
(因?yàn)閈在python中是轉(zhuǎn)義標(biāo)記所以要加上r使其變成原始字符串)
open(file_path)
- 逐行讀取
以每次一行的方式檢查文件可對(duì)文件對(duì)象使用for循環(huán)
with open(filepath) as file_object:
for line in file_object:
print(line)
不過(guò)這樣每行后面都會(huì)多一個(gè)空行
- 創(chuàng)建一個(gè)包含文件各行內(nèi)容的列表
(使用with關(guān)鍵字的時(shí)候文件對(duì)象file_object只在with代碼塊中可用)
with open(filepath) as file_object:
lines=file_object.readlines()
- 寫(xiě)入文件
with open(‘filename.txt’, ‘w’) as file_object:
file_object.write(“I love programming”)
‘w’
寫(xiě)入模式辜昵,若文件不存在會(huì)自動(dòng)創(chuàng)建荸镊,若存在會(huì)將原文件清空再返回
‘r’
讀取模式,默認(rèn)
‘a(chǎn)’
附加模式路鹰,若文件不存在會(huì)自動(dòng)創(chuàng)建贷洲,若存在會(huì)在原文件的末尾開(kāi)始寫(xiě)
‘r+’
讀寫(xiě)模式
只能將字符串寫(xiě)入文本文件,其它數(shù)據(jù)格式要用str進(jìn)行轉(zhuǎn)換
異常
python使用被稱為異常的特殊對(duì)象來(lái)管理程序執(zhí)行期間發(fā)生的錯(cuò)誤
發(fā)生錯(cuò)誤時(shí)會(huì)創(chuàng)建一個(gè)異常對(duì)象晋柱,如果有處理該異常的代碼程序(try-except)就可以繼續(xù)執(zhí)行否則就會(huì)停止并顯示一個(gè)traceback
try:
print(5/0)
except ZeroDivisionError:
print(“You can’t divide by zero”)
這樣遇到ZeroDivisionError的時(shí)候就會(huì)打印這句話而不是出現(xiàn)traceback
然后程序會(huì)繼續(xù)執(zhí)行
try:
answer=int(first_num)/int(second_num)
except ZeroDivisionError:
print(“You can’t divide by zero”)
else:
print(answer)
FileNotFoundError
ValueError
也可以在except中使用pass
使用json模塊來(lái)存儲(chǔ)數(shù)據(jù)(不局限于字符串优构,各種數(shù)據(jù)結(jié)構(gòu)都可以)
import json
numbers=[2, 3, 5, 7, 11, 13]
filepath=’number.json’
with open(filepath, ‘w’) as f_obj:
json.dump(numbers, f_obj)
讀取數(shù)據(jù)
with open(filepath) as f_obj:
numbers=json.load(f_obj)
示例:
import json
filepath=’username.json’
try:
with open(filepath) as f_obj:
username=json.load(f_obj)
except FileNotFoundError:
username=input(“What is your name?”)
with open(filepath, ‘w’) as f_obj:
json.dump(username, f_obj)
else:
print(“Welcome back, “+username)
使用Python模塊unittest中的工具來(lái)測(cè)試代碼
自動(dòng)執(zhí)行,并使用斷言來(lái)判斷執(zhí)行得是否正確
單元測(cè)試用于核實(shí)函數(shù)的某個(gè)方面沒(méi)有問(wèn)題
測(cè)試用例是一組單元測(cè)試雁竞,核實(shí)函數(shù)在各種情形下都沒(méi)問(wèn)題
全覆蓋式測(cè)試用例
- 測(cè)試函數(shù)
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
“””測(cè)試name_function.py(創(chuàng)建了一個(gè)測(cè)試用例)”””
def test_first_last_name(self):
“””能正確處理像Janis Joplin這樣的名字嗎(創(chuàng)建一個(gè)單元測(cè)試用于測(cè)試某一方面)”””
formatted_name=get_formatted_name(‘janis’, ‘joplin’)
self.assertEqual(formatted_name, ‘Janis Joplin’)
def test_first_last_middle_name(self):
“””測(cè)試另一種情況”””
formatted_name=get_formatted_name (‘wolfgang’, ‘mozart’, ‘a(chǎn)madeus’)
self.assertEqual(formatted_name, ‘Wolfgang Amadeus Mozart’)
unittest.main()
運(yùn)行這個(gè)文件時(shí)钦椭,所有test_開(kāi)頭的方法都會(huì)被自動(dòng)運(yùn)行
用斷言方法來(lái)核實(shí)結(jié)果是否與期望的結(jié)果一致
assertEqual(a, b)
assertNotEqual(a, b)
assertTrue(x)
assertFalse(x)
assertIn(item, list)
assertNotIn(item, list)
- 測(cè)試類
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 response in self.responses:
print(‘- ‘+response)
test_survey.py
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def test_store_single_response(self):
question=”What language did you first learn to speak?”
my_survey=AnonymousSurvey(question)
my_survey.store_response(‘English’)
self.assertIn(‘English’, my_survey.responses)
unittest.main()
不用在每個(gè)方法中都創(chuàng)建實(shí)例拧额,可以使用unittest.TestCase類中的setUp方法,只需創(chuàng)建實(shí)例一次并在每個(gè)測(cè)試方法中使用
setUp方法在test_方法之前調(diào)用
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
question=”What language did you first learn to speak?”
self.my_survey=AnonymousSurvey(question)
self.responses=[‘English’, ‘Spanish’, ‘Mandarin’]
def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()