【Python】像计算机科学家一样思考Python

mac2026-03-12  4

目录

(一)程序之道

(二)变量、表达式和语句

(三)函数

例: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模块

 

自定义模块

 

 

最新回复(0)