让我们尝试一些简单的Python命令。比如:Python 数学计算 启动解释器然后等待主提示符>>>
解释器的行为就像是一个计算器:你可以输入一个表达式,来进行试验。表达式的语法很简单:符+, - ,*,/就像工作在大多数其他语言(比如C或Pascal),括号可以用于分组。例如:
>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3
等号('=')是用来指定一个变量值。
>>> width = 30
>>> height = 5*9
>>> width * height
1350
值可以同时赋值给多个变量:
x = y = z = 0 # Zero x, y and z
输出x,y,z的结果,都是0 并且大家可以通过id(x),id(y),id(z)看下结果。
必须将变量“定义”(分配值)才可以使用,如果没有定义则会发生错误:
>>> # try to access an undefined variable
... n
Traceback (most recent call last):
File "", line 1, in
NameError: name 'n' is not defined
完全支持浮点数,运营商与混合型操作数转换为整数浮点运算:
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
还支持复数,复数的虚数被写入,或者可以创建与真实,复杂(IMAG)功能。
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
复数总是表示为两个浮点数,实部和虚部。从这些部位提取复数z,使用z.real和z.imag。
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
不转换功能,浮点和整数,对复数起作用 - 有没有一个正确的方式来转换一个复数为实数。使用ABS(z)的幅度(浮动)或z.real得到它的实部。
>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
>>>
这个只是简单的介绍了下python数学的入门知识点,如果你想学习更多python科学计算的,可以学习numpy模块