Python学习第二章数值与运算符

上一篇 / 下一篇  2015-05-07 15:55:21

1、Python提供了三种类型的可用数值:整型(用于表示整数,无论是负数还是正数)、浮点型、虚数
        确定数值的分类:特殊函数type
        对不同的数值使用type
 >>> type("1")
<class 'str'>
>>> type(1)
<class 'int'>
>>> type(2000)
<class 'int'>
>>> type(999999999)
<class 'int'>
>>> type(1.0)
<class 'float'>
>>> type(-10)
<class 'int'>
2、创建虚数
虚数尾部都有一个字母j
>>> 12j
12j
可以将虚数和非虚数结合起来,创建一个复数
>>> 12j+1
(1+12j)
>>> 12j+1.01
(1.01+12j)
>>> type(12j+1)
<class 'complex'>
3、保存文件 save as  打开文件 open,单击run
4、在字符串中包含不同的数字
     >>> "Including an integer works with %%d like this:%d" %10
          'Including an integer works with %d like this:10'
     >>> "An integer converted to a float with %%f:%f"%5
             'An integer converted to a float with %f:5.000000'
     >>> "An normal float with %%f:%f"%1.2345
            'An normal float with %f:1.234500'
     >>> "A really large number with %%E:%E"%6.789E10
            'A really large number with %E:6.789000E+10'
      >>> "Controlling the number of decimal places shown:%.02f"%25.101010101
             'Controlling the number of decimal places shown:25.10'
5、在字符串中将%符号转义
   如果想在程序中打印字符串%d,可以在python字符串中打印两个%符号
  >>> print("The %%behaves differently when combine with other letters,like this:%%d,%%s,%%f,%d" %10)
            The %behaves differently when combine with other letters,like this:%d,%s,%f,10
6、基本算术
  >>> 5+300
305
>>> 399+3020+1+3456
6876
>>> 300-59994+20
-59674
>>> 4023-22.46
4000.54
>>> 2*4
8
>>> 44/11
4.0
>>> 5.0/2.5
2.0
>>> 324/101
3.207920792079208
当运算超过python的容纳能力时,将会返回inf(无穷大)
 >>> 2e304*3923817273929
inf
>>> 2e34*3923817273929
7.847634547858e+46

7、取余运算(%)
>>> 5/3
1.6666666666666667
>>> 5%3
2
对比以上两种方式,第二种就是取余

8、>>> print("%f"%(4023 - 22.4))
4000.600000

9、%f格式说明符
>>> print("%f"%(5/3))
1.666667
>>> print("%.2f"%(5/3))
1.67
>>> print("%f"%(415*20.2))
8383.000000
>>> print("%0.f"%(415*20.2))
8383

10、使用数值
使用数学运算
>>> (24*8)
192
>>> (24*(8+3))
264
>>> (24*(8+3+7.0))
432.0
>>> (24*(8+3+7.0+9))/19
34.10526315789474
>>> (24*(8+3+7.0+9))%19
2.0

11、数值格式
>>> print("$%0.02f" % 30.0)
$30.00
>>> print("$%0.03f" % 30.00163)
$30.002
>>> print("$%.03f" % 30.1777)
$30.178
>>> print("$%.03f" % 30.1111)
$30.111

12、字符串与字符串相加,字符串不能与数值相加
正确的:>>> "This is a string"+str(4)
'This is a string4'
错误的:>>> "This is a string"+4
 
13、将数字格式化为八进制和十六进制
>>> print('Octal uses the letter "o" lowercase.%d %o'%(10,10))
Octal uses the letter "o" lowercase.10 12
将数值10提供给字符串时,八进制仅仅有8个数值(0-7),因此0-10用八进制表示依次是0、1、2、3、4、5、6、7、10、11、12

>>> print('Hex uses the letter "x" or "X".%d %x %X'%(10,10,10))
Hex uses the letter "x" or "X".10 a A
十六进制使用0-15的数字,但是因为9之后就没有数字了,所以十六进制用**f,使用格式说明符%x,表示是小写的;%X就是大写的,因此十进制的0-19用十六进制就是0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,10,11,12,13


TAG:

 

评分:0

我来说两句

Open Toolbar