在苏铭和蓝莓带领下,最近开始学习 Python,下面是走过的坑,吐槽正式开始

Python 在代码书写上要求极高,所有很多时候代码复制过来报错。。还有代码区分空格和 Tab

Python 中,对象赋值本质上是对象的引用

不要把 Python 代码写成 C/C++ 的风格!同样 SageMath 的代码也不要迁就 Python

安装

Python 官网慢的我想吐,几次都没有下下来,最后是在一次中午时分用手机流量定位了下载的地方,然后直接在电脑上手动输入长达 30 字符的网址(带文件名)直接下载,然后网速“飞快”,终于下下来了 26M 的 windows 64 位 Python3.8.2。然后就是用 pip 安装各种包,然后安装的时候真的是一头包,各种报错,各种而且奇慢无比,我吐了。后来终于找到解决方案:引用豆瓣源(其他源也行)。例子如下:

pip install numpy -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

pip install wxPython -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

安装好一些必要的包之后就可以跑程序了。

pip freeze/list 查看所有安装了的包

PyPi :Python Package Index 查看所有发布的包的索引。

简单的终端 Python 程序示例

1
2
3
4
5
6
7
8
9
10
11
12
# score.py
tmp = input('苏铭的Python分数:')
if tmp.isdigit():
score = int(tmp)
if score > 100:
print('我信了你的鬼话')
elif score >=60:
print('可以呀苏铭')
else:
print('菜的呀苏铭')
else:
print('你输入的是什么鬼哦')

简单的 GUI Python 程序示例

1
2
3
4
5
6
7
8
9
10
11
12
13
# hello.py
import wx #需要安装wxPython包,见上面pip安装
class Frame1(wx.Frame):
def __init__(self, superior):
wx.Frame.__init__(self, parent= superior, title = 'Example',pos = (400,200),size=(350,500))
panel = wx.Panel(self)
text1 = wx.TextCtrl(panel,value = 'Hello',pos = (250,300))

if __name__ == '__main__':
app = wx.App()
frame = Frame1(None)
frame.Show(True)
app.MainLoop()

IDE 选择(sublime 大法好, VSCode 无敌)

当时我是大 sublime 啊, 百度 sublime+ Python 就可以获得完整教程 配置 和 代码补全 配置,安装 packageControl 网速慢的话可以早上 7 点起来尝试。(缺点是每次要先 Ctrl+S 保存再 F5 编译,然后下次编译上次的编译窗口不能自己关,我也不知道怎么搞解决这两个问题,可惜!)

再也不用担心tab不是tab了! view ---> Indentation ---> Convert Indentation to tabs

多行注释:ctrl + shift + /

一定要配置代码补全!!!, 特别是在用各种包的时候

入门教程

  1. 下载好 Python 后有自带文档
  2. Python 菜鸟教程
  3. 百度一下,你就知道。不行可以选择 必应
  4. 网易公开课,我选择的是南京大学的 Python 玩转数据,用手机 app 才能看,建议观看 1-25 集和 43-50 集。 1.5 倍速。
  5. 爬虫(下面示例)
  6. Pygame 库的使用(PY 游戏,那也才刺激了吧 0.0)
  7. 100 天学会 Python
  8. 人脸识别

基本语法掌握了之后就要掌握类了,Python 的类挺有趣的,哈哈.类中写得变量是类的属性,而每个对象的属性要加 self. 的,然后方法里面的变量是方法内部临时变量。

素数筛

1
2
3
4
5
6
7
8
9
10
11
12
13
def initprime(n):
isp = [x%2==1 for x in range(n+1)]
isp[1] = False;isp[2]= True
p = [2]
for i in range(3,n+1,2):
if isp[i]: p.append(i)
for j in p:
if(i*j<=n): isp[i*j] = False
else: break
if i%j == 0: break
return isp,p

print(initprime(100008)[-1][-1])

爬虫示例

总结爬虫方法:

  1. 观察想要想要爬虫的网站中特定数据的网址,用 F12(适用于 Chorme, Edge 等)打开代码检查。找到数据对应的意义和名称
  2. 设计流程图和代码框架
  3. Coding

本来就不会写,学习了 leetcode 上的代码后,制作了青春(阉割)版的爬取 lol 所有壁纸到当前文件夹的 lolIamge 文件夹中,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os
import urllib.request as urlrequest

def getimage(heroID):
heroId = str(heroID)
url = 'https://game.gtimg.cn/images/lol/act/img/skin/big' + heroId
heroDir = r'lolImage\\' + heroId
if not os.path.exists(heroDir): os.mkdir(heroDir)
for i in range(100):
heroEnd = '0' + str(i//10) + str(i%10) + '.jpg'
try:
image = urlrequest.urlopen(url + heroEnd).read()
except: break
imageName = heroDir + r'\\' + heroEnd
with open(imageName, 'wb') as f: f.write(image)

if not os.path.exists('lolImage'): os.mkdir('lolImage')
for i in range(1,1000): getimage(i)

Python 处理字符串的 split 函数强的不行,给爬虫提供了特别便利的条件

机器学习示例

1
2
3
4
5
6
7
# hello ML.py
from sklearn import tree # https://sklearn.apachecn.org/
features = [[140,1], [130,1],[150,0],[170,0]]
lAbels = [0,0,1,1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(features,lAbels)
print(clf.predict([[160,0]]))

有需求再去这里学习吧:B 站视频对应笔记

有趣的 Python 特征

  • 内联表达式:[i**2 for i in range(10)]
  • exec 函数 执行 Python 代码(一般用于文件读取)
  • 元组(tuple)可以做加法和乘法来改变它的值!但是本质上元组的值并没有改变,只是新开了一段连续的内存,然后用刚刚那个指针指向了这段内存!!!所以元组是不可变的这句话没毛病
  • 一个元素构成的元组要写成(a,)形式,是因为否则到处都是元组 0.0(因为我们在处理优先级的时候经常加()
  • 上述说明了为什么内联表达式不支持用 tuple,用的是 list(列表)
  • 生成器可以用 list and tuple,搞完生成器就空了
  • map(func,data) 一次算一堆的值。
  • Python 中没有++,-- 这类自增自减运算

打包成可执行文件(.exe)

最简单的方法: pip 安装 pyinstaller (借助豆瓣源,见安装段落),然后执行

pyinstaller -F example.py -w

其中 -F 表示单个文件, -w 表示关闭命令行窗口

问题是,一个几 kb 的 Python 程序,打包就 10M+ 。。。这谁顶得住啊,解决方案

反解析和防止被反解析

datetime 包学习(哈哈哈)

1
2
3
4
import datetime
now = datetime.datetime.now()
day = now - datetime.datetime(2019,10,20)
print('喜欢茶茶子妹妹的第'+str(day.days)+'天')

代码规范

每个包都有各自的代码规范,使用的时候注意一点可以省很多麻烦。个人比较喜欢的代码规范方式:

  1. 逗号后面加空格 ,
  2. 类的手写字母大写,例如:class MyHoney():
  3. 函数或者类的方法全小写
  4. 变量或者类中属性首单词字母小写,后面单词首部大写,例如 myName
  5. 常量全大写
  6. 个人不是很喜欢用下划线,不过也是一个不错的选择
  7. 函数,类中方法,模块隔行显示
  8. 用 tab 缩进,用空格对齐 (强烈抵制用 4 个空格代替 tab!!!)
  9. 多用语法糖

Python 之禅(Zen of Python)

在 Python 命令行中输入 import this 就会出现:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one— and preferably only one —obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

就不翻译了,最喜欢的一句:

Now is better than never although new is often better that right now