骆秀韬 epsilon_luoo@outlook.com
聪明办法学 Python 教学团队
第一行代码
print("hello, world") # f(x)
hello, world
单行注释 使用 #
开头,#
后面的内容不会被当做代码,只能写在一行中
print("Datawhale") # for the learner,和学习者一起成长
Datawhale
# learn python the smart way v2
print("p2s")
# print("prepare to be smart")
p2s
每一个 print()
会默认换行
print("Data")
print("whale")
Data whale
print("Data", end="")
print("whale")
Datawhale
多个内容是以空格分隔
print("Data", "whale") # f(x, y)
Data whale
print("Data", "whale", sep="*")
Data*whale
列表是一种序列,它是可变的
容器的唯一作用就是打包、解包、内容传递。
p2s = ["learn", "python", "the", "smart", "way"] # 从 0 开始计数
print(p2s)
['learn', 'python', 'the', 'smart', 'way']
print(p2s[1], p2s[0], p2s[-1], p2s[-2]) # 索引 index
python learn way smart
print(p2s[0:2]) # 切片
print(p2s[2:]) # 左闭右开区间,起始 0,终止 -1
['learn', 'python'] ['the', 'smart', 'way']
字典是键值对的集合
dw_set = set()
for i in "Datawhale":
dw_set.add(i)
print(dw_set)
{'h', 'a', 'D', 'w', 'l', 't', 'e'}
dw_dict = {"d":"Data", "w":"whale"} # key: value
print(dw_dict["d"], dw_dict["w"], sep="")
Datawhale
字典的更新
dw_dict["w"] = "Whale"
print(dw_dict)
{'d': 'Data', 'w': 'Whale'}
女朋友说,下班回来带一个西瓜。如果看到番茄,就买两个
def 买西瓜(num):
return f"{num}个西瓜"
def 买番茄(num):
return f"{num}个番茄"
看到番茄 = True
# 下班了
西瓜 = 买西瓜(1)
if 看到番茄:
西瓜 = 买西瓜(2)
print(f"带了{西瓜}回家")
带了2个西瓜回家
# 女朋友心想
西瓜 = 买西瓜(1)
if 看到番茄:
番茄 = 买番茄(2)
print(f"带了{西瓜}和{番茄}回家")
带了1个西瓜和2个番茄回家
for row in range(3): # [0, 3)
for col in range(3):
print("🐳", end="")
print()
🐳🐳🐳 🐳🐳🐳 🐳🐳🐳
for string in "learn python the smart way".split():
print(string)
learn python the smart way
print("我,秦始皇,V50,吃肯德基".split(","))
['我', '秦始皇', 'V50', '吃肯德基']
nums = []
for i in range(10):
nums.append(i)
print(nums)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
有什么问题?
nums = [i for i in range(10)]
nums
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
列表推导式
[ 表达式 for 变量 in 序列 (if 条件) ]
nums = [i for i in range(10) if i < 5]
nums
[0, 1, 2, 3, 4]
字典推导式
{ 键(表达式): 值(表达式) for 变量 in 序列 if 条件 }
nums = {i: i**2 for i in range(10) if i > 5}
nums
{6: 36, 7: 49, 8: 64, 9: 81}
A function is a procedure (a sequence of statements) stored under a name that can be used repeatedly by calling the name.
以 Rectified Linear Unit (ReLU) 函数为例,其数学表达式为:
$f(x) = \begin{cases} x, x > 0, \\ 0, x \leqslant 0. \end{cases}$
def ReLU(x): # define
if x > 0:
return x
return 0
print(ReLU(9))
9
relu = lambda x: max(x, 0)
print(relu(-9))
0
import matplotlib.pyplot as plt
%matplotlib inline
X = [x for x in range(-10, 10)]
Y = [relu(x) for x in range(-10, 10)]
plt.plot(X, Y)
[<matplotlib.lines.Line2D at 0x2497f90b3d0>]
from random import choice
import time
from tqdm import tqdm
from IPython.display import display, HTML
class Train:
def __init__(self, name, *goods, naughty=True):
self.name = name
self.goods = goods
self.naughty = naughty
def __getitem__(self, idx):
if self.naughty:
return choice(self.goods)
return self.goods[idx]
def __len__(self):
return len(self.goods)
def info(self):
if self.name == "托马斯小火车":
return f"Hi,我是{self.name},Cinders and ashes!"
return f"Hi,我是{self.name}"
def 发车(self, string):
print(f"{string},上山!") # f-strings
for _ in tqdm(range(30)):
time.sleep(0.1)
display(HTML("<video controls width=1200 src='train.mp4'>train</video>"))
Edward = Train("爱德华", 1, 2.5, 9, 114, 514, naughty=False) # 实例化
Edward.info()
'Hi,我是爱德华'
len(Edward)
hw
a, b = Edward[3], Edward[4] # 打包与解包 ([3], [4]) -> a, b
print(f"hello {b}") # f-string
hello 514
货物 = ["邮件", "大米", "煤矿", "劳斯莱斯"]
托马斯 = Train("托马斯小火车", *货物, naughty=True )
托马斯.info()
'Hi,我是托马斯小火车,Cinders and ashes!'
len(托马斯)
4
托马斯[2]
'邮件'
托马斯.发车("AE86")
AE86,上山!
100%|███████████████████████████████████████████████████████████████████████████████| 30/30 [00:03<00:00, 9.89it/s]