http://www.skillbrew.com
/SkillbrewTalent brewed by the
industry itself
Numbers and Arithmetic Operators
Pavan Verma
@YinYangPavan
Python Programming Essentials
© SkillBrew http://skillbrew.com
Number Types
 int : 20
 long : 1000000000000000L
 float : 3.14
 complex : 1j * 1J
2
© SkillBrew http://skillbrew.com
Arithmetic operations
3
>>> x = 10
>>> y = 15
>>> x + y # add
25
>>> x - y # subtract
-5
>>> x * y # multiply
150
© SkillBrew http://skillbrew.com
Arithmetic operations
4
>>> x = 10
>>> y = 15
>>> x ** y # exponent
1000000000000000L
>>> y/x # division
1
>>> y%x # modulus
5
© SkillBrew http://skillbrew.com
Floating points
5
>>> 3/2
1
>>> 4/2
2
>>> 3.0/2
1.5
>>> 3/2.0
1.5
>>> 3.0/2.0
1.5
By default the division operation
on int will return result also as
int
If any of the (numerator and
denominator) is a floating
point number the output is
also a floating point
number
© SkillBrew http://skillbrew.com
Floating points (2)
6
>>> 2 * 3.12
6.24
>>> 2 * 3.5
7.0
>>> 10 * 1.0
10.0
>>> 2 + 3.0
5.0
>>> 5 - 3.5
1.5
>>> 5 - 3.0
2.0
Multiplying, addition, subtraction,
division with floating point
number results in a floating point
number
Many times you might need to
convert an integer to float, just
multiply it by 1.0
© SkillBrew http://skillbrew.com
Converting int to binary, octal and hexadecimal
>>> bin(3)
'0b11'
>>> oct(3)
'03'
>>> hex(3)
'0x3'
7
© SkillBrew http://skillbrew.com
Bitwise operators
8
>>> 0b0011
3
>>> 0b1010
10
>>> 0b0011 & 0b1010
2
>>> 0b0011 | 0b1010
11
>>> 0b0011 ^ 0b1010
9
Operator Description
& Binary AND
| Binary OR
^ Binary XOR
<< Left Shift operator
>> Right Shift operator
~ One’s complement
© SkillBrew http://skillbrew.com
Bitwise operators (2)
9
>>> 0b0011 << 2
12
>>> 0b1010 >> 2
2
>>> ~0b0011
-4
Operator Description
& Binary AND
| Binary OR
^ Binary XOR
<< Left Shift operator
>> Right Shift operator
~ One’s complement
© SkillBrew http://skillbrew.com
Summary
 Number Types
 Arithmetic operators
 Converting int to binary, octal and hexadecimal
 Bitwise operators
10
© SkillBrew http://skillbrew.com
Resources
 Tutorial on numbers
http://www.tutorialspoint.com/python/python_numbers.htm
 Converting a decimal to binary discussion
http://stackoverflow.com/questions/3528146/convert-
decimal-to-binary-in-python
11
12

Python Programming Essentials - M10 - Numbers and Artihmetic Operators