160 likes | 267 Views
Chapter 4 Numbers. Bernard Chen 2007. Python Build-in types. Numbers 3.1415 Strings “Hello World” Lists [1,2,3,4] Dictionaries {‘test’: ‘yum’} Files input=open(‘file.txt’, ‘r’). Numbers.
E N D
Chapter 4 Numbers Bernard Chen 2007
Python Build-in types • Numbers 3.1415 • Strings “Hello World” • Lists [1,2,3,4] • Dictionaries {‘test’: ‘yum’} • Files input=open(‘file.txt’, ‘r’)
Numbers Many different types, we only provide 3 here for now: • Integer • Floating-point • Long integer
Number in Action • Perhaps the best way to understand numerical objects is to see them in action. >>> a=3 #Name Created >>> b=4
Number in Action >>> a+1, a-1 # (3+1), (3-1) (4,2) >>> b*3, b/2 (12,2)
Number in Action >>> a%2, b**2 #remainder, power (1,16) >>> 2+4.0, 2.0**b #mix type (6.0,16.0) >>> c*2 #error
Number in Action >>> b / 2 + a >>> b/(2.0+a) >>> b/(2+a)
Number in Action >>> b / (2.0 + a) #auto echo output 0.80000000000004 >>> print b/(2.0+a) #print rounds off 0.8 digits
Number in Action >>> 1 / 2.0 0.5 >>> 1/2 0
Long Integers >>> 2L ** 200 >>> 2 ** 200
Other Numeric Tools >>> import math >>> math.pi >>> math.e >>> int(2.567), round(2.567), round(2.567,2)
Other Numeric Tools >>> abs(-42), 2**4, pow(2,4) (42, 16, 16) >>>int(2.567), round(2.567), round(2.4) (2, 3.0, 2.0) >>> round(2.567, 2) 2.569999999999998
Dynamic Typing >>> a = 3 • Create an object to represent the value of 3 • Create the variable a, if it does not yet exist • Link the variable a to the new object 3
Share Reference >>> a=3 >>> b=a
Share Reference >>>a=3 >>>b=a >>>a=5