Python的数值类型和操作符

本网站用的阿里云ECS,推荐大家用。自己搞个学习研究也不错

<

div id=”content”>整形和基本的操作符

很简单的一个程序来解释这个类型的相关内容:

i = 6 # declare integer
i, j = 6, 7 # declare two integers on one line: i becomes 6 and j becomes 7
print(i,j)
j = 6 + 7 * 92 / (5-3) # basic calculations
print(j)
i += 2 # increase i with 2
print(i)
i -= 1 # decrease i with 1
print(i)
i *= 2 # multiply i with 2
print(i)
i /= 2 # divide i with 2
print(i)
i = i * j / 5 # calculate variables together

输出会是这样的:

Hello World
(6, 7)
328
8
7
14
7

当然了,Python也支持模运算,而且支持在函数中使用运算符,或者一次定义多个变量,代码奉上:

__author__=”Alex”
__date__ =”$2011-2-17 10:39:27$”

if __name__ == “__main__”:
    print “Hello”;

i = 6 # declare integer
print(i)
j = i % 3 # j becomes 0
print(j)
k = i % 4 # k becomes 2
print(k)
l = 7
print ( l+5*7 ) # prints 42
k, e, f = 7, 4, 6 # k becomes 7, e becomes 4, f becomes 6
print(k,e,f)
b = c = -3 # b and c become -3
print(b,c)

运行结果:

Hello
6
0
2
42
(7, 4, 6)
(-3, -3)

浮点型的数据及其操作:

浮点型的数据一样可以使用和整形一样的操作符,而定义一个浮点型的参数,只用在后面加上小数点就可以了:

__author__=”Alex”
__date__ =”$2011-2-17 10:39:27$”

if __name__ == “__main__”:
    print “Hello”;

i = 6 # declare integer
f = 5.0 # declare float

i2 = 6/5 # i2 becomes 2
print(i2)
f2 = 6.0/5 # f2 becomes 1.2
print(f2)
f3 = i/f # f3 becomes 1.2
print(f3)

显示结果:

Hello
1
1.2
1.2

Math运算

在Python中你如果要使用更高级的运算,例如sin cos 等,Python提供了一个Math函数,这个函数返回的都是浮点型,这个地方需要像Java和C#一样引用外部的类,C#的include,Java的import,Show代码:

__author__=”Alex”
__date__ =”$2011-2-17 10:39:27$”

if __name__ == “__main__”:
    print “Hello”;

import math

a = math.sin(90) # sine
print(a)
a = math.cos(0) #cosine
print(a)
a = math.tan(0) #cosine
print(a)
a = math.sqrt(4) # square r

未经允许不得转载:演道网 » Python的数值类型和操作符

赞 (0)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册