How to do calculation with Python integers

Calculate with integer

The following code shows how to do simple calculation with operators.


a = 3           # name created
b = 4
print b / (2 + a)      # print rounds off digits

The code above generates the following result.

% is the remainder operator which gives us the remainder after dividing.


print 107 % 4

The code above generates the following result.

The following code prints the rounds. Integer division returns the floor:


print (50-5*6)/4# w w  w  .  j a va 2 s.c  om

print 7/3
print 7/-3
num = 1 / 3.0
print num               # print rounds

The code above generates the following result.

To get the power we use the power calculation operator **.


print 2L ** 200
print 2 ** 200

The code above generates the following result.

The 2L tells the Python that it is a long integer value.

Use () in calculation


a = 3           # name created
b = 4
print b / (2.0 + a)   # same as (4 / (2.0 + 3))

The code above generates the following result.

A value as a condition

Zero value is treated as false.


money = 0# from w  ww  .  ja v a  2 s  .c om

if money:
    print "Not zero"
else:
    print "zero"

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary