python基础

178 阅读2分钟

在绝大多数的Linux和Unix的系统安装中,Python的解释器就已经存在了 终端输入

$ python

运行这个命令会启动交互式Python解释器,输出如下

如果我们需要最新版的Python,我们可以到python.org下载 现在我们尝试一下交互式接合器,输入

print "hello"

可以看到输出结果为 hello

>>> 3+4

输出结果是 7

>>> 232332323+3294934

输出结果是 235627257

>>> 3*32
96
>>> 1/2
0
>>> 1.0/2
0.5
>>> 1/2.0
0.5

那我们如何让1除2的时候不做处理呢,执行

>>> from __future__ import division

输入 1/2;此时输出为0.5 然后我们可以使用双斜杠//来实现整除操作.

>>> 10/3
3.3333333333333335
>>> 10%3
1
>>> 10//3
3
>>> 2**3
8
>>> -3**2
-9
>>> (-3)**2
9
>>> 
>>> 190492940249024+23409834098209482094829
23409834288702422343853L

普通整数最大值为2147483647,所以当大于它的时候后面添加了L表示长整型

>>> x=3
>>> x*43
129

第一句为赋值操作,Python中变量名可以包括字母,数字和下划线。变量名不能以数字开头。

用户输入

>>> x = input("x: ")
x: 30
>>> y = input("y: ")
y: 40
>>> x*y
1200

函数

pow(x,y): xy次方

>>> 2**3
8
>>> pow(2,3)
8

abs(x):x的绝对值

>>> abs(-100)
100

round(x):x四舍五入

>>> round(2/3)
1.0
>>> round(1/3)
0.0

float(x):将x转化为浮点型 math.ceil(x):x的上入整数 repr(object):返回字符串形式 str(object):转化为字符串

模块

python中用import来导入模块

>>> import math
>>> math.floor(23.84)
23.0
>>> int(math.floor(23.43))
23

另外两种写法如下 ,from math import floor申明floor方法来自math模块

>>> from math import floor
>>> floor(34.43)
34.0

利用变量test来引入floor函数

>>> test = math.floor
>>> test(32.33)
32.0

sqrt(x):计算x的平方根

>>> from math import sqrt
>>> sqrt(32)
5.656854249492381

sqrt函数中参数为负数时,平方根为虚数

>>> from math import sqrt
>>> sqrt(-3)

执行结果为

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

python中有另一个cmath(complex math 复数)模块,可以实现

>>> import cmath
>>> cmath.sqrt(-3)
1.7320508075688772j

1.7320508075688772j为计算结果,j代表为复数

>>> 3j*4j
(-12+0j)
>>> (3j-34)*(4j-43)
(1450-265j)