Sunday, June 14, 2015

Addition in Python - Python Numbers - Python Tutorial

Addition in PythonAddition in Python


We are getting back into the basics in this Python tutorial. In the first three tutorials in this chapter, on Python numbers we focussed on floating point numbers and decimal numbers. Our plan was to start out very basic with addition but we had some questions about the accuracy of floating point numbers which made us push back this tutorial on addition in Python.


Addition in Python is very simple and you should not  have any issues with addition in Python. To add numbers we use the plus(+) symbol to add the numbers together. The plus symbol is regarded as an arithmetic operator in the Python programming language.


Example of Addition in Python


In these examples, we will be using our Python interpreter. The interpreter is a very useful tool when it comes to working with math and numbers.


Adding Integers 


#Adding Integers in Python

>>> 2 + 2
4
>>> 33 + 22
55
>>> 67 + 32
99
>>> 55 + 22
77
>>> 19 + 8978
8997

#adding positive integer to negative integer
>>> 340000 + -40000
300000

Adding Floats


We will run into some issues adding floats, but we have learned in our previous tutorials how to fix these issues. When going through this these examples use the skills that you have learned in the previous Python tutorials and fix these numbers.


#Adding Floats

#Fix this one
>>> 5.6 + 87.3
92.89999999999999

#If you add an integer and a float together we will get a float back
>>> 76.5 + 65
141.5

#fix this one as well
>>> 678.34 + 34.21
712.5500000000001

#adding a positive float to a negative float

>>> 75.3232 + -2.3
73.0232

############################
Answers to above problems below
############################
>>> round(5.6 + 87.3, 1)
92.9
>>> round(678.34 + 34.21, 2)
712.55

This is a very short tutorial and the reason is that addition in Python is so simple that we really did not have much more to show you. Just remember with addition and floats you can run into some weird returns so either use the built-in function round() or the decimal module.


Build An Addition Program

 


If you have any questions please leave a comment below.



No comments:

Post a Comment