Arithmetic Expressions in Python

Arithmetic expressions in python are very simple and easy.  There are two types of numbers: integers (e.g. 1, -3) and decimal numbers (i.e. 3.45) in python there are two corresponding data types int() and float () respectively.

# Arithmetic expressions - numbers, operators, expressions

print 3, -1, 3.14159, -2.8

# numbers – two types, an integer or a decimal number
# two corresponding data types int() and float()

print type(3), type(3.14159)
print type(3.0)

type() function is used to find the type of data you are working with. The above code will produce the following results:

3 -1 3.14159 -2.8
<type ‘int’> <type ‘float’>
<type ‘float’>

we can convert between data types using int() and float(). Note that int() takes the “whole” part of a decimal number and doesn’t round.

# we can convert between data types using int() and float()
# note that int() takes the "whole" part of a decimal number and doesn't round

print int(3.14159), int(-2.8)
print float(3), float(-1)

From the above code we will get the following results:

3 -2
3.0 -1.0

Python has the ability to maintain 15 digits after the decimal. Python has the following basic arithmetic operators:

# arithmetic operators
+ plus addition
– minus subtraction
* times multiplication
/ divided by division
** power exponentiation

# Division in Python
# If one operand is a decimal (float), the answer is decimal
print 1.0 / 3

0.333333333333

# If both operands are ints, the answer is an int (rounded down)
print 5 / 2

2

# operator precedence - (), **, *, /, +,-
print 1 * 2 + 3 * 4
print 2 + 12

14
14


# always manually group using parentheses when in doubt

print 1 * (2 + 3) * 4
print 1 * 5 * 4

20
20

Arithmetic_expressions

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.