【Python】像計算機科學家一樣思考Python_筆記(上)

目錄

(一)程序之道

(二)變量、表達式和語句

(三)函數

例:turtle模塊,畫正方形

有返回值的函數

重構

(四)函數接口

文檔字符串

(五)條件和遞歸

pass

嵌套條件

遞歸recursion

鍵盤輸入

(八)字符串序列(sequence)

遍歷字符串

字符串不可變

例:計算字母a在字符串中出現的次數(計數器counter)

(九)例:文字遊戲

(十)列表

列表遍歷

遍歷列表,讀取元素

遍歷列表並更新元素

列表方法(如append、extend、sort)

例:列表元素相加(可直接sum(l) )

例:首字母大寫(倆列表交互)

例:只保留大寫元素

刪除元素(pop、del、remove)

列表和字符串(list、split、join)

對象和值

(十一)字典

可哈希/不可哈希

(十二)元組

內置函數enumerate()

(十二)元組之內置函數zip()

(十三)數據結構的選擇

random()方法

(十四)文件

os模塊

數據庫

pickle模塊

自定義模塊


(一)程序之道

(二)變量、表達式和語句

(三)函數

函數之無返回值函數
函數之嵌套使用
函數之注意事項
函數之函數對象
函數之命名規則.png
模塊.png
定義 調用call 函數.png
調試之runtime error和semantic error
調試之syntax error
解釋器
關鍵字

 

例:turtle模塊,畫正方形

  • 準備工作
import turtle #導入模塊

bob=turtle.Turtle() #使用turtle模塊.Turtle函數
#Turtle函數會創建一個Turtle對象,我們將其賦給變量bob

print(bob)#<turtle.Turtle object at 0x00000240C054DB00>
#即變量bob指向一個類型爲Turtle的對象,這個類型由turtle模塊定義
  • 法一:簡單重複
  • #創建一個Turtle對象,可以調用方法以進行更多操作(方法與函數類似,但語法略有不同)
    #(Turtle函數會創建一個Turtle對象,我們將其賦給變量bob)
    
    bob.fd(100)#讓海龜往前走100個像素
    bob.lt(90)#左轉90度
    
    bob.fd(100)#讓海龜往前走100個像素
    bob.lt(90)#左轉90度
    
    bob.fd(100)#讓海龜往前走100個像素
    bob.lt(90)#左轉90度
    
    bob.fd(100)#讓海龜往前走100個像素
    bob.lt(90)#左轉90度
  • 法二:藉助for循環(loop)
for i in range(4):  #i=0,1,2,3
    bob.fd(100)
    bob.lt(90)
  • 畫正方形:封裝成函數
#完整代碼
import turtle #導入模塊
bob=turtle.Turtle() #使用turtle模塊.Turtle函數
#Turtle函數會創建一個Turtle對象,我們將其賦給變量bob
print(bob)#<turtle.Turtle object at 0x00000240C054DB00>
#即變量bob指向一個類型爲Turtle的對象,這個類型由turtle模塊定義

def square(t):
    for i in range(4):
        t.fd(100)
        t.lt(90)

#square(bob)
bobb=turtle.Turtle()
square(bobb)
  • 畫多邊形
def polygon(t,n,length):
    angle=360/n
    for i in range(n):
        t.fd(length)
        t.lt(angle)

bobb=turtle.Turtle()
polygon(bobb,6,70)
polygon(bobb,n=6,length=70)#可加 關鍵字實參
  • 畫多邊形→近似圓
import math,turtle
bob=turtle.Turtle() #注意有括號!Turtle函數

def polygon(t,n,length):
    angle=360/n
    for i in range(n):
        t.fd(length)
        t.lt(angle)

#用50邊形近似圓
def circle(t,r):
    circumference=2*math.pi*r#周長
    n=50
    length=circumference/n#每條小邊的長度
    polygon(bob,n,length)#調用上面的畫多邊形函數

circle(bob,500)
函數接口
#修改一行
n=int(circumference/3)+1 #線段數量約爲周長的1/3

有返回值的函數

調用一個有返回值的函數會生成一個返回值,我們通常將其賦值給某個變量或作爲表達式的一部分。無返回值的函數,更準確地說,它們的返回值是None。

 

重構

 

(四)函數接口

接口就像是函數和調用者之間的合同,調用者同意提供合適的參數,函數同意完成相應的工作。

 

文檔字符串

 

 

 

(五)條件和遞歸

pass

 

嵌套條件

 

遞歸recursion

調用正在執行的函數本身的過程

#遞歸recursion:自己調用自己的函數
def countdown(n):
    if n<=0:
        print('blastoff')
    else:
        print(n)
        countdown(n-1)

countdown(3) #>>>3 2 1 blastoff

 

鍵盤輸入

text=input('隨便輸:')
num=eval(input('隨便輸數值:'))
print(type(num))#<class 'int'>
print(text)
print(num)

 

(八)字符串序列(sequence)

遍歷字符串

fruit='banana'

#while循環,遍歷字符串
index=0
while index < len(fruit):
    letter=fruit[index]
    print(letter)
    index=index+1

#for循環,遍歷字符串
for letter in fruit:
    print(letter)

字符串不可變

不能直接用過字符串索引修改元素值。只能重新創建呢。列表可變

例:計算字母a在字符串中出現的次數(計數器counter)

word='banana'
count=0
for letter in word:
    if letter =='a':
        count=count+1
print(count) #>>>3

 

(九)例:文字遊戲

  • 讀文本
#1、讀取單詞列表
fin=open('E:\新桌面\Python\截圖\words.txt')
fin.readline()#讀一行
#遍歷讀每行
for line in fin:
    word=line.strip()
    print(word)
  • 遍歷找e,找到就False
fin=open('E:\新桌面\Python\截圖\words.txt')
#遍歷找'e',找到就False
def has_no_e(word):
    for letter in word:
        if letter=='e':
            return False
    return True
  • 函數:判斷是否按字母順序 is_abecedarian()

法一:for循環

word='apple'
#是否按字母順序
def is_abecedarian(word):
    previous=word[0]
    for c in word:
        if c < previous: #字符/串可以比大小,如'c'>'a','bc'>'b'
            return False
        previous=c
    return True

print(is_abecedarian(word)) #注:print輸出才能看到結果(False)

法二:遞歸

word='apple'
#是否按字母順序
def is_abecedarian(word):
    if len(word) <=1:
        return True
    if word[0] > word[1]:
        return False
    return is_abecedarian(word[1:])

print(is_abecedarian(word))

法三:while循環

word='apple'
#是否按字母順序
def is_abecedarian(word):
    i=0
    while i <len(word)-1:
        if word[i+1]<word[i]:
            return False
        i=i+1
    return True

print(is_abecedarian(word))
  • 函數:判斷是否爲迴文 is_palindrome
#判斷是否爲迴文
word='250052'
def is_palindrome(word):
    i=0
    j=len(word)-1

    while i<j:
        if word[i]!=word[j]: #別忘冒號!!!
                return False
        i=i+1
        j=j-1
    return True
print(is_palindrome(word))

 

(十)列表

列表遍歷

遍歷列表,讀取元素

#for循環,遍歷列表(與遍歷字符串類似)
#讀取列表元素
name=['ywp','wtx','baby']
for n in name:
    print(n)
num=[1,2,3,0]

遍歷列表並更新元素

num=[1,2,3,0]
#寫入/更新列表元素,結合下標訪問、內置函數range()和len()
for i in range(len(num)):
    num[i]=num[i]*2
    print(num[i])

列表方法(如append、extend、sort)

#append添加一個新元素到 列表末端
t=['a','b','c']
t.append('d')
print(t) #['a', 'b', 'c', 'd']

#extend添加所有元素到 列表末端
t2=['aa','bb','cc']
t.extend(t2)
print(t) #['a', 'b', 'c', 'd', 'aa', 'bb', 'cc']

#sort 將列表元素從小到大排序
t3=['d','c','a']
t3.sort()
print(t3) #['a', 'c', 'd']
print(t3.sort()) #None
print(l.sort)結果爲None

 

例:列表元素相加(可直接sum(l) )

num=[1,2,3]
def add_all(t):
    total=0
    for x in t:
        total+=x
    return total
print(add_all(num))

print(sum(num))

例:首字母大寫(倆列表交互)

t=['app','pig','fine']
#首字母大寫
def capitalize_all(t):
    res=[]
    for s in t:
        res.append(s.capitalize())
    return res
print(capitalize_all(t))#['App', 'Pig', 'Fine']

例:只保留大寫元素

t=['app','PIG','Fine']
#只保留大寫元素
def only_upper(t):
    res=[]
    for s in t:
        if s.isupper():
            res.append(s)
    return res
print(only_upper(t))#['PIG']

 

刪除元素(pop、del、remove)

#pop
t=['app','PIG','Fine']
tp=t.pop(1)#返回被刪除的元素
print(tp)#PIG
print(t)#查看原列表 ['app', 'Fine']

#del
tt=['app','PIG','Fine']
del tt[1]
print(tt) #['app', 'Fine']
del tt[:1]
print(tt)#['Fine']

#remove(若已知要刪除的值,但不知下標)
ttt=['app','PIG','Fine']
ttt.remove('app')
print(ttt)#['PIG', 'Fine']

列表和字符串(list、split、join)

#list直接將字符串分成單個字符
t='love you'
t=list(t)
print(t)#['l', 'o', 'v', 'e', ' ', 'y', 'o', 'u']

#split按某符號(默認空格)分隔字符串
tt='love you'
ts=tt.split()
print(ts)#['love', 'you']

#join按某符號(默認空格)合併字符串,與split相反
delimiter=' '
#在某個分隔符上調用join方法,並傳入一個列表作爲參數
tj=delimiter.join(ts)
print(tj)#love you

 

對象和值

 

 

(十一)字典

可哈希/不可哈希

 

(十二)元組

內置函數enumerate()

for index,element in enumerate('abc'):
    print(index,element)
'''
0 a
1 b
2 c
'''

(十二)元組之內置函數zip()

a = [1,2,3]
b = ['a','b','c']
zipped = zip(a,b)
print(zipped)#<zip object at 0x000002476F680488>
print(list(zipped))#[(1, 'a'), (2, 'b'), (3, 'c')]

 

(十三)數據結構的選擇

random()方法

import random
for i in range(3):
    x=random.random()
    print(x)
'''
0.5859316143057813
0.7867295553359852
0.07251354296290347
'''

import random
random.randint(5,10)
print(random.randint(5,10))#10
print(random.randint(5,10))#9
print(random.randint(5,10))#5

 

(十四)文件

os模塊

os模塊提供了操作文件和目錄的函數,os.getcwd返回當前目錄的名稱

import os
print(os.getcwd()) #如D:\Anaconda\Lib\site-packages\lda2vec

數據庫

pickle模塊

 

自定義模塊

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章