您的位置:首页 > 编程语言 > Python开发

python学习(一)变量和数据类型

2016-01-01 16:38 639 查看
数据类型

print 45678+0x12fd2             #整形
print "Learn Python in imooc."      #字符串
print 100<99                #布尔型


123456
Learn Python in imooc.
False


输出

#input code
print "hello,python"
print "hello,","python"


hello,python
hello, python


注释

#hello




字符串

普通字符串

s = 'Python was started in 1989 by "Guido".\nPython is free and easy to learn.'
print s


Python was started in 1989 by "Guido".
Python is free and easy to learn.


2.raw字符串与多行字符串(相当于原样输出)

print r'''"To be, or not to be": that is the question.
Whether it's nobler in the mind to suffer.'''


"To be, or not to be": that is the question.
Whether it's nobler in the mind to suffer.


整数和浮点数

和数学运算不同的地方是,Python的整数运算结果仍然是整数,浮点数运算结果仍然是浮点数

1 + 2    # ==> 整数


1.0+ 2.0    # ==> 浮点数 3.0


整形数和浮点数混合运算的结果就变成浮点

1 + 2.0    # ==> 浮点数 3.0


要区分整数运算和浮点数运算呢?这是因为整数运算的结果永远是精确的,而浮点数运算的结果不一定精确,因为计算机内存再大,也无法精确表示出无限循环小数,比如 0.1 换成二进制表示就是无限循环小数。

那整数的除法运算遇到除不尽的时候,结果难道不是浮点数吗?

`11 / 4 # ==> 2

初学者惊讶的是,Python的整数除法,即使除不尽,结果仍然是整数,余数直接被扔掉。不过,Python提供了一个求余的运算 % 可以计算余数

11 % 4    # ==> 3


我们要计算 11 / 4 的精确结果,按照“整数和浮点数混合运算的结果是浮点数”的法则,把两个数中的一个变成浮点数再运算就没问题了:

11.0 / 4    # ==> 2.75


布尔类型

与运算:只有两个布尔值都为 True 时,计算结果才为 True。

True and True   # ==> True
True and False   # ==> False
False and True   # ==> False
False and False   # ==> False


或运算:只要有一个布尔值为 True,计算结果就是 True。

True or True   # ==> True
True or False   # ==> True
False or True   # ==> True
False or False   # ==> False


非运算:把True变为False,或者把False变为True:

not True   # ==> False
not False   # ==> True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息