块缩进
python的块缩进等同于四个空格键,支持Tab和空格键。
赋值
# string
my_text = 'And now for something completely different'
# int
x = 17
# float
pi = 3.1415926535897932
变量名
变量的名称可以任意长。
字母和数字都可以包含,但不能以数字开头。
使用大写字母是合法的,但是变量名只使用小写字母是惯例。
下划线字符“_”可以出现在名称中。它通常用于包含多个单词的名字中,例如“your_name”或“airspeed_of_unladen_swallow”。
以下是python中的关键字符,有着特殊含义:
| Keyword | Description |
| :------- | :----------------------------------------------------------- |
| and | A logical operator |
| as | To create an alias |
| assert | For debugging |
| break | To break out of a loop |
| class | To define a class |
| continue | To continue to the next iteration of a loop |
| def | To define a function |
| del | To delete an object |
| elif | Used in conditional statements, same as else if |
| else | Used in conditional statements |
| except | Used with exceptions, what to do when an exception occurs |
| False | Boolean value, result of comparison operations |
| finally | Used with exceptions, a block of code that will be executed no matter if there is an exception or not |
| for | To create a for loop |
| from | To import specific parts of a module |
| global | To declare a global variable |
| if | To make a conditional statement |
| import | To import a module |
| in | To check if a value is present in a list, tuple, etc. |
| is | To test if two variables are equal |
| lambda | To create an anonymous function |
| None | Represents a null value |
| nonlocal | To declare a non-local variable |
| not | A logical operator |
| or | A logical operator |
| pass | A null statement, a statement that will do nothing |
| raise | To raise an exception |
| return | To exit a function and return a value |
| True | Boolean value, result of comparison operations |
| try | To make a try...except statement |
| while | To create a while loop |
| with | Used to simplify exception handling |
| yield | To end a function, returns a generator |
多重赋值
python允许你同时给多个向量赋值。
a = b = c = 1
你也可以给多个向量赋多个值。
a, b, c = 1, 2, "john"
增量赋值
| 运算符 | 描述 | 实例 |
| :----- | :---------------| :------------------------------------ |
| = | 简单的赋值运算符 | c = a + b 将 a + b 的运算结果赋值为 c |
| += | 加法赋值运算符 | c += a 等效于 c = c + a |
| -= | 减法赋值运算符 | c -= a 等效于 c = c - a |
| *= | 乘法赋值运算符 | c *= a 等效于 c = c * a |
| /= | 除法赋值运算符 | c /= a 等效于 c = c / a |
| %= | 取模赋值运算符 | c %= a 等效于 c = c % a |
| **= | 幂赋值运算符 | c **= a 等效于 c = c ** a |
| //= | 取整除赋值运算符 | c //= a 等效于 c = c // a |
条件语句
if语句用来做判断,并选择要执行的语句分支。基本格式如下:
```python
if CONDITION1:
code_block(1)
elif CONDITION2:
code_block(2)
elif CONDITION3:
...
...
else:
code_block_else
```
其中elif是可选的,可以有任意多个,else是可选的,表示全都不满足条件时该执行的分支。
循环语句
迭代
迭代有两个基本的方法:iter()和 next()。
a_string = 'abcde'
a_string_iter = iter(a_string)
next(a_string_iter)
' a '
for循环语句
for i in 'xiaofang':
print(i)
x
i
a
o
f
a
n
g
L = ["aa", "bb", "cc"]
for i in L:
for j in i:
print(j)
a
a
b
b
c
c
L = ["aa", "bb", "cc"]
for i in L:
for j in i:
print(j)
aa
bb
cc
range()语句
for i in range(5):
print(i)
0
1
2
3
4
for i in range(1,5):
print(i)
1
2
3
4
for i in range(1, 5, 2):
print(i)
1
3
for i in range(1, 5, 3):
print(i)
1
4
while条件语句
x = 0
print(x)
while(x<5):
x += 1
print(x)
0
1
2
3
4
5
break语句
break语句能让你跳出当前循环
i = 1
total = 0
while True:
total += i
i += 1
if total > 20:
break
print(i)
print(total)
7
21
continue语句
' continue '允许您跳过循环中的其余代码,并跳转到下一次迭代。这对于使用' if '语句跳过由某些条件定义的特定迭代非常有用
# Let's sum all integers less than 20, but skipping multiples of 3
total = 0
for i in range(20):
if i % 3 == 0:
print(i)
continue
total += i
print('\n')
print(total)
0
3
6
9
12
15
18
127
total = 0
for i in range(20):
if i % 3 == 0:
print(i)
total += i
print('\n')
print(total)
0
3
6
9
12
15
18
190
函数
声明函数
#define function name
def func(args1,args2):
###the pass statement does nothing, which can come in handy
##when you are working on something and want to implement some part of your code later
pass
##to implement
用return返回函数的值
## f(x)=width*row
def calculate_area(width,row):
area = width*row
return area
width = 5
row = 3
print(calculate_area(width,row))
15
如果ruturn的是none,函数就不会输出值了
def loop():
##range(10), means 0,1,2,3,...,9
for i in range(10):
print(i)
if i ==3:
return
loop()
列表
列表可以组合变量
myList = [0,1,2,2.0,"name"]
print("myList[0]:",myList[0])
print("myList[1]:",myList[1])
print("myList[3]:",myList[3])
print("myList[-1]:",myList[-1])
print("myList[-2]:",myList[-2])
myList[0]: 0
myList[1]: 1
myList[3]: 2.0
myList[-1]: name
myList[-2]: 2.0
列表可以被切片
myList = [1,2.0,"hello"]
print("myList[0:2]:",myList[0:2])
print("myList*2:",myList*2)
myList2 = [2,"yes"]
print("myList+myList2:",myList+myList2)
myList[0:2]: [1, 2.0]
myList*2: [1, 2.0, 'hello', 1, 2.0, 'hello']
myList+myList2: [1, 2.0, 'hello', 2, 'yes']
复制列表
myList = [0,1.0,"hello"]
myList = myList
print(myList)
print(myList2)
myList = [0,1.0,"hello"]
myList2 = myList
myList2[0] = "yes"
print(myList)
print(myList2)
['yes', 1.0, 'hello']
['yes', 1.0, 'hello']
将两个列表存储在不同的地址
myList = [0,1.0,"hello"]
##myList = list(myList)
##myList2 = myList[:]
myList2 = myList.copy()
myList2[0] = "yes"
print("myList:",myList)
print("myList2:",myList2)
myList: [0, 1.0, 'hello']
myList2: ['yes', 1.0, 'hello']
我们也可以这样定义:
myList2=myList[:]
myList=list(myList[:])
tuples
tuples不能被修改
myTuple = (1,2,3)
myTuple[0] = 2
Dictionaries
d = {}
d[1] = 2
d["a"] = 3
print("d:",d)
c = {1:2, "a":3}
print("c:",c)
print("c[1]:",c[1])
d: {1: 2, 'a': 3}
c: {1: 2, 'a': 3}
c[1]: 2
objects
在python中,所有的东西都是objects
class LinearLayer
object LinearLayer1,LinearLayer2.……
##define class
class Linear():
pass
##instantiate object
layer1 = Linear()
print(layer1)
<__main__.Linear object at 0x0000025C3077CF10>
## define class
class Linear():
## It refers to the object (instance) itself
def __init__(self,n_input):
self.n_input = n_input
layer1 = Linear(100)
layer2 = Linear(1000)
print("layer1:",layer1.n_input)
print("layer2:",layer2.n_input)
layer1: 100
layer2: 1000
除了定义输入,还可以定义输出
## define class
class Linear():
### It refers to the object (instance) itself
def __init__(self,n_input,n_output):
self.n_input = n_input
self.n_output = n_output
def compute_n_params(self):
num_params = self.n_input * self.n_output
return num_params
layer1 = Linear(10,100)
print(layer1.compute_n_params())
1000
numpy基础
可以对n维数组进行各种各样的操作
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
[[1 2 3]
[4 5 6]]
array
array是可以被修改的
可以做broadcasting
还可以做很多运算
Brainpy 介绍
对数组运算器进行了整合
拥有专用的运算器
数值积分器
模型结构
面向对象
brianpy的编程基础
即时编译的介绍
可以理解为动态编译,可以大大提升程序运行速度和运行效率。
运行一个神经模型
数组的用法
for loop语句的使用
while loop语句的使用