Basic knowledge
conditionals
mark= 56
if mark>= 69.5:
print("distribution")
elif mark>= 59.5:
print("merit")
elif mark>= 50.0:
print("pass")
else:
print("Fail")
pass
Loops
numbers= [1,2,3,4,5,6]
for i in numbers:
print(i)
1
2
3
4
5
6
number_plus_one= []
number_plus_one= []
for i in numbers:
number_plus_one.append(i+1)
print("current number is: "+ str(i))
current number is: 1
current number is: 2
current number is: 3
current number is: 4
current number is: 5
current number is: 6
number_plus_one
[2, 3, 4, 5, 6, 7]
for i in range(1, 8, 2):
print(i)
1
3
5
7
count= 0
while count< 5:
print(count)
count+= 1
0
1
2
3
4
count= 0
while True:
print(count)
count+= 1
if count>= 5:
break
0
1
2
3
4
Functions
def my_func():
print("Hello from my func")
my_func()
Hello from my func
def my_func2(greeting, planet):
print(greeting+ ' '+ planet+ '!')
my_func2('Hello', 'World')
Hello World!
def add(a, b):
return a+ b
result= add(1, 2)
print(result)
3
result
3
Python packages, and the numpy
package
import numpy as np
np.identity(5)
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
from numpy import identity
identity(5)
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
from matplotlib import pyplot as plt
plt.plot([1,2,3],[1,4,1],'or')
[<matplotlib.lines.Line2D at 0x208b1c47780>]
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/291c9bdec165095c3c0fc7bf1b9a3b1d.png)
Numpy arrays
import numpy as np
arr= np.array([1.2, 3.14, -6.45])
arr
array([ 1.2 , 3.14, -6.45])
2* [23,42]
[23, 42, 23, 42]
2* arr
array([ 2.4 , 6.28, -12.9 ])
arr+ 1
array([ 2.2 , 4.14, -5.45])
arr* -1
array([-1.2 , -3.14, 6.45])
arr** 2
array([ 1.44 , 9.8596, 41.6025])
arr1= arr
arr2= np.array([1, 2, 3])
print([1, 2 ,3]+ [3, 4, 5])
arr1+ arr2
[1, 2, 3, 3, 4, 5]
array([ 2.2 , 5.14, -3.45])
arr1* arr2
array([ 1.2 , 6.28, -19.35])
np.sin(1)
0.8414709848078965
np.sin(arr1)
array([ 0.93203909, 0.00159265, -0.16604211])
arr1[0]
1.2
arr[: 2]
array([1.2 , 3.14])
Numpy arrays pt 2
import numpy as np
a= np.array([[1, 2, 3],[4, 5, 6]])
a
array([[1, 2, 3],
[4, 5, 6]])
a.shape
(2, 3)
nrows, ncols= a.shape
print(nrows, ncols)
2 3
a.shape= 6
a
array([1, 2, 3, 4, 5, 6])
a.shape= [3, 2]
a
array([[1, 2],
[3, 4],
[5, 6]])
a.shape= [2, 3]
a
array([[1, 2, 3],
[4, 5, 6]])
np.zeros(5)
array([0., 0., 0., 0., 0.])
np.zeros([3, 4])
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
np