注解

此笔记本可在此处下载: 00_Basics.ipynb

代码作者:Ludovic Charleux ludovic.charleux@univ-smb.fr

python基础

变量和简单类型

2 + 2 # Addition of 2 numbers
4
a = 5 # An integer
a
5
type(a) # Get "a"'s class.
int
type(5.) # A floating point number
float
type("Hello") # A string
str
type(True)
bool
type(None)
NoneType

容器

列表

l = [1, 3, "cat"] # A list that contained both ints and strings.
l
[1, 3, 'cat']
l[0] # Python counts from 0 !
1
l[1] = 8
l
[1, 8, 'cat']
l.append("dog")
l
[1, 8, 'cat', 'dog']
len(l)
4

词典

d = {"tomato":"red", "banana": "yellow"} # A dictionnary
d
{'banana': 'yellow', 'tomato': 'red'}
d.keys()
dict_keys(['tomato', 'banana'])
d.values()
dict_values(['red', 'yellow'])
d["tomato"]
'red'
d["salad"] = "green"
d
{'banana': 'yellow', 'salad': 'green', 'tomato': 'red'}

循环

for a in [1, 2, "hello"]:
    print(a) # Leading spaces (indentations) are mandatory to define code blocks
1
2
hello
for i in range(5):
    print(i**2)
0
1
4
9
16
a = 5
if a < 4:
    print("a<4")
else:
    print("a>4")
a>4
a = 0
while a < 5:
    print("hello")
    a += 2
hello
hello
hello

功能

功能 是需要 争论 可能还有:

  • 返回 一些东西,

  • 修改他们的论点。

def myFunction(x, a = 1, b = 0.):
    """
    My Function: Affine equation

    * Params: x, a, b: 3 numbers
    * Returns: y = a*x + b
    """
    return a* x + b
myFunction(1) # a and b have default values
1.0
myFunction(1, 2, 3)
5
myFunction(x = 1, b = 4) # Arguments are defined by keywords
5

Classes

Classes 定义对象,这些对象一旦出现就可以执行许多任务。在一些工作之后,类是构建工作的有效方法。

class Vector3D:
    """
    A very simple 3D vector class.
    """
    def __init__(self, x = 0, y = 0., z = 0.):
        self.x = x
        self.y = y
        self.z = z

    def __repr__(self):
        return "<Vector: ({0:.2e}, {1:.2e}, {2:.2e})>".format(self.x, self.y, self.z)

    def norm(self):
        """
        Returns the norm of the vector.
        """
        return (self.x**2 + self.y**2 + self.z**2)**.5

    def normalize(self):
        """
        Divides the vector by its own norm.
        """
        n = self.norm()
        self.x /= n
        self.y /= n
        self.z /= n

    def cross(self, other):
        """
        Cross product with another vector.
        """
        return Vector3D(x = self.y * other.z - self.z * other.y,
                        y = self.z * other.x - self.x * other.z,
                        z = self.x * other.y - self.y * other.x)
    __mul__ = cross
v = Vector3D(2,2,0)
v
<Vector: (2.00e+00, 2.00e+00, 0.00e+00)>
v.norm()
2.8284271247461903
v.normalize()
v
<Vector: (7.07e-01, 7.07e-01, 0.00e+00)>
v.norm()
0.9999999999999999
u = Vector3D(0,0,1) # Cross product
v.cross(u)
<Vector: (7.07e-01, -7.07e-01, 0.00e+00)>
u * v # operator overcharge
<Vector: (-7.07e-01, 7.07e-01, 0.00e+00)>