Python編程 從入門到實(shí)踐 #筆記#

變量

命名規(guī)則
只能包含字母、數(shù)字、下劃線
不能包含空格,不能以數(shù)字開頭
不能為關(guān)鍵字或函數(shù)名
字符串
用單引號(hào)、雙引號(hào)、三引號(hào)包裹 name = "ECLIPSE"
name.title()
name.upper()
name.lower()
name.rstrip()
name.lstrip()
name.strip()

數(shù)字

x = 1
message = "bla" + str(x) + "bla"

列表

bicycles = ['1th', '2th', '3th']
bicycles[-1]

bicycles.append('4th')
bicycles.insert(0, '5th')

del bicycles[0]
poped_bicycle = bicycles.pop()
poped_bicycle = bicycles.pop(0)

a = '2th'
bicycles.remove(a)

bicycles.sort()
bicycles.sort(reverse=True)
sorted(bicycles)
sorted(bicycles, reverse=True)

bicycles.reverse()

len(bicylces)

操作列表
for bicycle in bicycels:
print(bicycle)

不會(huì)打印出數(shù)字5
for v in range(1,5):
print(v)

even_numbers = list(range(2, 21, 2))

squares = []
for v in range(1,10):
squares.append(v**2)
print(squares)

max()
min()
sum()

squares = [v**2 for v in range(1,10)]
print(squares)

players = ['1th', '2th', '3th', '4th', '5th']
print(players[0:3])
print(players[:3])
print(players[1:])
print(players[-3:])

上面的那一種并沒有創(chuàng)建兩個(gè)數(shù)組
new_players = players
new_playerss = players[:]

元組

不可被修改的列表

if

if... elif... else

and
or

if '1th' in bicycles:
print('yes')
if '1th' not in bicylces:
print('no')

if bicycles:
if not bicycles:

字典

aliens = {}
aliens['1th'] = 1
del aliens['1th']

for k, v in aliens():
for k in aliens.keys():
for k in sorted(aliens.keys()):
for v in aliens.values():

用戶輸入
message = input('tell me something:')
print(message)

age = int(input('tell me your age:'))
print(age+1)

循環(huán)while
break
continue

pets = ['1th', '2th', '3th', '4th', '5th']
while pets

url = 'www.baidu.com'
while url:
print('urlis: %s' %url)
url = url[:-1]

函數(shù)

形參數(shù)
實(shí)參數(shù)
位置實(shí)參
關(guān)鍵字實(shí)參
默認(rèn)值
等效的函數(shù)調(diào)用

讓實(shí)參變成可選的

    def get_formated_name(firstName, lastName, middleName=''):
        if middleName:
            fullName = firstName + ' ' + middleName + ' ' + lastName
        else:
            fullName = firstName + ' ' + lastName
        return fullName.title()

function_name(list_name)
function_name(list_name[:])

允許收集任意數(shù)量的實(shí)參,并把其作為一個(gè)元組傳入函數(shù)
def make_pizza(*toppings):

python先匹配位置實(shí)參和關(guān)鍵字實(shí)參,再將余下的實(shí)參收集到一個(gè)形參中
def make_pizza(size, weight=15, *toppings):

使用任意數(shù)量的關(guān)鍵字實(shí)參
def build_profile(first, last, **user_info):

import module_name
from module_name import function_name
from module_name import function_name as f_nick_name
import module_name as m_nick_name
from module_name import *

類名稱首字母大寫
class Dog();
def init():

屬性
方法

給屬性指定一個(gè)默認(rèn)的值
def init(self):
fixed_num = 0
修改屬性的值:
通過句點(diǎn)法直接訪問并修改屬性的值
通過方法修改屬性的值

父類and子類
子類繼承另父類時(shí),自動(dòng)獲得父類所有屬性and方法
同時(shí)也可以定義自己的屬性and方法

class Car():
    def __init__(self, make, model, year):
        ...
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)

子類中和父類相同的方法(重寫父類的方法)

可以將一個(gè)實(shí)例用作屬性

from car import Car
from car import Car, ElectricCar
import car
from car import *   不推薦使用
from collections import OrderedDict
languages = OderedDict()    // 有順序的字典

文件

相對(duì)文件路徑
絕對(duì)文件路徑

file_path = 'text_file/filename.txt'    // Linux and Mac
file_path = 'text_file\filename.txt'    // Windows
with open(file_path) as file_object:
    contents = file_object.read()

    for line in file_object:
        print(line.strip())

    lines = file_object.readlines()

讀取文本文件時(shí),python將其中的所有文本都讀為字符串

'r' 讀取模式
'w' 寫入模式
'a' 附加模式
'r+' 讀取和寫入文件模式
python只能將字符串寫入文本文件

file_object.write('...') // 不會(huì)在文末添加換行符

異常

try:
    answer = ...
except ZeroDivisionError:
    print('erroe')
else:
    print(answer)
title = 'alice is wonderland'
title.split()
def count_words(fileName):
    --snip--
fileNames = ['1th', '2th', '3th']
for fileName in fileNames:
    count_words(fileName)

pass

count()

import json
json.dump(numbers, file_object)
numbers = json.load(file_object)

重構(gòu)

unittest測(cè)試

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容