Monday, June 15, 2015

Subtraction in Python - Python Numbers - Python Tutorial

Subtraction in PythonSubtraction in Python


In the previous tutorial, we covered addition which was a very simple tutorial. In this tutorial, we will look at subtraction in Python which is another very simple subject. Subtraction works as expect in Python as simple as it was in grade school.

To perform subtraction, in Python we use the minus(-) symbol. In this tutorial, we will be doing all our code in the Python Interpreter. To follow along open your Python interpreter and try some of the examples below.


Integer Subtraction In Python


The following are just basic examples of subtracting Python integers.


#Integer Subtraction in Python

>>> 8 - 4
4
>>> 345 - 67
278

Float Subtraction in Python


The following are just basic examples of subtracting Python floats or floating point numbers.


#Float Subtraction in Python

#simple float subtraction
>>> 6.7 -98
-91.3
>>> 67.43 - 98.76
-31.33

#fixing float accuracy
>>> 8.8 - 1.5
7.300000000000001

#default round function no numbers after the decimal
>>> round(8.8 - 1.5)
7

#fix for one number after the decimal
>>> round(8.8 - 1.5, 1)
7.3

Now that you have seen how easy subtraction in Python you can now simply add and subtract numbers using your Python code.  If you have any questions about subtraction in Python leave a comment below and we will do our best to help you out.



Sunday, June 14, 2015

Addition Program in Python - Python Tutorial

Addition Program in PythonAddition Program in Python


In this tutorial, we are about build a very simple addition program in Python. We will show how to build a simple program that will add two integer numbers that a user gives us via the terminal or command prompt and then we will return the sum of those two numbers to the user. The program will be accessible to download at the end of the tutorial. Just try to follow along the more you practice writing programs in Python the more you will learn.


Building the Addition Python Program


We will be using sublime text as our text editor to build this program. We will be writing our code using Python 3 syntax.  We will run the code via our terminal or command prompt.


Step 1 - Open Text Editor


Open your text editor so we can write the code for our program.


Step 2 - Save your program


Save your program to your desktop as addition.py


Step 3 - Write Welcome Message For Our Program


Here we will use a simple print statement to welcome our users to our program.


#Write Welcome Message For Our Program

print("Welcome to our addition program")

Step 4 - Get Users First Number


In this step, we will get the users first number using input() and then convert the number to an integer using int() and assign a variable to the object that holds the users first number.


#Get Users First Number

print("Welcome to our addition program")
firstnum = int(input("Give us your first number. "))

Step 5 – Get Users Second Number


In this step, we do the same for the previous step above but we give this user input a different variable.


#Get Users Second Number

print("Welcome to our addition program")
firstnum = int(input("Give us your first number. "))
secondnum = int(input("Give us your second number. "))

Step 6 – Perform The Equation


In this step, we will add the users two numbers together and then assign the sum a variable.


#Perform The Equation

print("Welcome to our addition program")
firstnum = int(input("Give us your first number. "))
secondnum = int(input("Give us your second number. "))
thesum = firstnum + secondnum

Step 7 – Return The Sum To The User


We will return the sum of the user. We will print a string to the user and format the string using a format() method to add our sum into the string.


#Return The Sum To The User

print("Welcome to our addition program")
firstnum = int(input("Give us your first number. "))
secondnum = int(input("Give us your second number. "))
thesum = firstnum + secondnum
print("Your sum is ".format(thesum))

Step 8 – Run The Program


Open your terminal or command prompt and change into your desktop. To run the program, simply type python3 addition.py and press return or enter. The program will ask you to input a number then press return. The program will again prompt you to add your second number again input your number then press return. Now the program will return your sum to you. This is a very simple program in Python.


If you have any questions about Addition Program in Python please leave a comment below and we will help you out.


Get Source Code From Git

 



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.



Saturday, June 13, 2015

Python Decimal Module - Python Numbers - Python Tutorial

Python Decimal ModulePython Decimal Module


In the previous two Python tutorials, we looked at issues that arise when working collaboratively with floating point numbers in the Python programming language. When working with floating point numbers we have seen that Python sometimes returns a value that we are not suspecting. This is doesn’t happen often but when we get a number that is a few ten thousandths off this can be concerning especially if you are working with numbers that need to have precise returns like a accounting program or a program that controls trajectory of a spacecraft. It would be concerning if we could not get the correct amount of money or if our spacecraft was off course by a tad bit we would probably miss the earth on the return and fly right into the sun.

In this tutorial, we are going to look at the Python decimal module which needs to import into your program for the functions to work. Decimals are basically floating point numbers but, they have fixed number of decimal points.  We can think of them as fixed-precision floating point numbers. We can also control how Python rounds the numbers unlike with the round() function where we saw if can round in the wrong direction.  With the decimal module, we will be capable of more precise numbers with a little bit more work.


Importing The Decimal Module


We have seen how to import a few modules in previous tutorials, in this tutorial we are going to follow the same steps. To make the decimal module to work we first need to import the module and we do this by entering the following “import decimal” with no quotes.  Once we have imported the Python decimal module we will be able to access the functions included in the module.


Importing The Decimal Module Example


#import the whole module. We will use this method in this tutorial

>>> import decimal

#import a specific function in the module
>>> from decimal import Decimal

In this Python decimal module, tutorial we will just use import decimal. This will make it easier to focus on the decimal module over importing specific functions.


Working With Python Decimal Module


First we need to look at an example where we would need to use the decimal module. Let’s look at the example we have been using over and over in our last two tutorials.


Why We Need Decimal Module Example


#below you will find two examples why we would need to use the decimal module

#answer should be 16.3
>>> 7.6 + 8.7
16.299999999999997

Ways To Fix This Using the Decimal Module


Method 1


In this example, we set a global precision on our decimal module and we may be limited in using this method. Take a look at how it works.


#first example

#issue
>>> 7.6 + 8.7
16.299999999999997

#import Decimal Module
>>> import decimal

#set the precision globally this tells decimal module we want 3 numbers returned.
>>> decimal.getcontext().prec = 3

#Now add the two numbers together using the decimal module
>>> decimal.Decimal(7.6) + decimal.Decimal(8.7)
Decimal('16.3')

In the above example, we take our problem floating point number and we use the decimal module to return the correct number. Let’s take a closer look at the process we use above.


Import Decimal Module


First we import the Python decimal module.  This needs to be done so we can use the functions the module contains.


Code: import decimal


Set Global Precision


When we set global precision the program to only show three numbers with our code.  Global means that our program will only show three numbers throughout our program or until we change it. This method may not be the best if you are working with numerous different numbers.


Code: decimal.getcontext().prec = 3


The Equation


Here we perform a simple addition equation.  We do have some words in front of our floats.  The first word decimal says go to the module decimal and then the second word Decimal says get the Decimal function which is inside the decimal module.


Code: decimal.Decimal(7.6) + decimal.Decimal(8.7)


Method 2


In this example, we will set the precision for our numbers temporarily so we will look at global with temporary precision adjustment.


#Temporary Precision

#import decimal module
>>> import decimal

#set global
>>> decimal.getcontext().prec = 3

#our equation for this example but we want the dollar and cents in this equation. We only get 3 numbers which are the dollars
>>> decimal.Decimal(78.96) + decimal.Decimal(90.99)
Decimal('170')

#temporary fix setting our precision for one equation
>>> with decimal.localcontext() as ctx:
... ctx.prec = 5
... decimal.Decimal(78.96) + decimal.Decimal(90.99)
...
Decimal('169.95')

#see only temporary
>>> decimal.Decimal(78.96) + decimal.Decimal(90.99)
Decimal('170')

Import Decimal Module


Is the same as above example


code: import decimal


Set Global Precision


Is the same as above example


Code: decimal.getcontext().prec = 3


The Equation


Here we have an equation and in this equation we want to find out how much a client owes you. This equation does not show cents and rounds up so your client is paying you more than is actually owed to you. This may not be the best choice when running a business


codedecimal.Decimal(78.96) + decimal.Decimal(90.99)


The Temporary Precision Solution


What in the world is that funky looking code. We are nowhere near learning about exceptions in Python but I thought I would share this one to show you the possibilities in Python and the decimal module. Let’s take a closer look “With” is an exception statement in Python. So, what I did here was say “with” the “decimal module” look inside the decimal module and get the “localcontext()” function and set this function “as” a variable called “cxt” so we can call it in the statement. The next line you must indent in your Python interpreter(I use two spaces) we set the precision using “cxt” variable like this cxt.precision = 5. After, we define the precision we can run our equation like before. Then in Python interpreter press return twice.


This also may not be the best solution for your program seems like a lot of code to do something simple.


Method 3


This is our final example in this tutorial. If you are looking for more precise decimal numbers then quantize may be our best option. We use quantize to return the exact amount of decimal numbers.


#using quantize in decimal module

#import decimal
>>> import decimal

#assign a variable an equation
>>> a = decimal.Decimal(78.96 * 89.65)

#Then use quantize to set exact decimal position
>>> a.quantize(decimal.Decimal('0.00'))
Decimal('7078.76')

Import Decimal Module


Same as before


code: import decimal


A Variable assigned To An Equation


Here we allocate a variable to an equation. We use a variable to cut down on the amount of code we need to type, but we could have done it all on one line. This is just simpler.  So with equation, we want to know the monetized amount so we want two numbers after the decimal point.


Quantize The Decimal


Here we use a method to round the number to a certain set of numbers after the decimal. We use a method called quantize to achieve this. We set how we want the method to return the value with ‘0.00’ it must be in a string format. If we want more numbers after the decimal for example we want four we could do ‘0.0000’ to make this happen.


Last Example


We also looked at another problem using the built-in function round().  round(2.675, 2) this function does not round as we expect so is there a way to fix this?  Of course there is. 


#Last Example Fixing Rounding Issues

#This should round up to 2.68
>>> round(2.675, 2)
2.67

#Lets take a look at what this number actually represents
>>> b = decimal.Decimal(2.675)
>>> b
Decimal('2.67499999999999982236431605997495353221893310546875')

#as you can see it rounds down because of the 4 instead of the five

#the fix
b.quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)
Decimal('2.68')

In this example we once again use the quantize module but this time we use rounding to tell Python to round the number up.  We can use the following rounding commands ROUND_CEILING, ROUND_UP, ROUND_HALF_UP, ROUND_FLOOR, ROUND_DOWN, ROUND_05UP, ROUND_HALF_EVEN.


In Conclusion


We have taken a brief look at the Python decimal module. This is not a full tutorial on this module and we do have one planned for the future.  That tutorial will need to be broken down into several mini tutorials do the shear size of the Python decimal module. If you want to read more about the Python decimal module visit https://docs.python.org/3.4/library/decimal.html#module-decimal If you have any questions about today’s tutorial, please leave a comment below.



Garbage Collection - Python Tutorial



Garbage collection is the way Python manages memory in a program.  This method is automatic or we have an option to control the garbage collection through a module called garbage collection(gc).

Check out our tutorial on garbage collection at Garbage Collection


View video tutorial on Youtube at https://youtu.be/hg01TTzi6Xk


Tutorial on garbage collection module coming soon!



Friday, June 12, 2015

round() Built-in Function In Python - Python Numbers - Python Tutorial

round() built-in function in Pythonround() Built-in Function In Python


In our previous Python tutorial, we looked at some weird numbers you can get when you doing math with floating point numbers in Python. We also explained that this is not some bug that it has to do with the underlying c language and how it handles floating point numbers. C language converts floating point numbers to fractions and when those fractions are called by Python they again are converted to float and the conversion between a float and fraction are not always accurate.

We also discussed that one of the ways around this minor issue is using a built-in function in Python called round(). Round() will round the floating point number to a certain number to the right of the decimal which we can control in the syntax. To get started with round() let’s look at the syntax for the round() built-in function in Python.


round() Syntax


round(First Argument, Second Argument)


First Argument


This is where we input the float that we want to round.


Second Argument


The second argument is after the comma. This location is where we can declare how many numbers after the decimal we want to use. If we give no second argument then the argument defaults to zero.


round() Examples


#Round Examples

#From the previous tutorial
>>> 7.6 + 8.7
16.299999999999997

#How to fix the above example
>>> round(7.6 + 8.7, 1)
16.3

#Another example
>>> a = 0.1 + 0.2
>>> a
0.30000000000000004
>>> round(a,1)
0.3

#How about more numbers after the decimal
>>> b = 9.5434 * 983245.8943
>>> b
9383508.86766262
>>> round(b, 4)
9383508.8677

Well that is pretty easy use and fix the occasional inaccuracy in Python numbers. Well the round() built-in function in Python does have its own issues.  Take a look at this example.


Round() Issues


#Round() Issues

#This doesn't make sense
>>> round(2.675, 2)
2.67

#Now you are probably even more confused
>>> round(8.875, 2)
8.88

Well now that we confused you a bit this comes back to the previous tutorial where the underlying c language and how it converts floats to fractions and back again. Not every float can be displayed properly. In this tutorial, we saw where round() could help and we also saw where round() could hurt a bit.We will look at the decimal module in the next tutorial and see how that can help us work together with floats.

In this tutorial, we saw how the round() built-in function could help us in most situations but there are times when round() built-in function in Python may not be the best choice. We will look at our other option in the next tutorial. If you have any questions about round() leave a comment below and we will help you.


 



Why are floating point calculations so inaccurate? - Python Numbers - Python Tutorial

Why are floating point calculations so inaccurateWhy are floating point calculations so inaccurate?


This may be deeper than you are ready to go at this point in learning Python but it is important to understand that floating point numbers may not be returned as you expect with performing calculations in Python. To kick off this tutorial let’s take a look at an example of this weird problem you may come across in Python.


Example of Floating Point Calculations


#Example of Floating Point Calculations

>>> 7.6 + 8.7
16.299999999999997

7.6 + 8.7 should equal 16.3 correct?  Why does Python have this bug?  It is not a bug actually. This is related to the underlying c language which Python is built on. This issue can seen in a lot of computer programming languages not just in Python.


Why Does This Happen?


This happens when the c language attempts to represent floating point numbers. C language uses binary numbers to account for floating point numbers but these numbers sometimes return numbers with a small round off error. Floating point numbers are actually handled as fractions then converted to floating point numbers when displayed. The conversion from a fraction to a floating point number is not so accurate as you may like.


How Can I Make My Floating Point Numbers More Accurate?


We have two options.  We could use round() which is a built-in function or we could use the decimal module. We will cover the built-in round() function in the next tutorial and then the following tutorial we will cover the decimal module. We will see how to work around this issue within Python.


In conclusion


We saw how floating point numbers are represented in Python and that it is not an issue with Python but an issue with how the underlying c language represents floating point numbers. We now know that floating point numbers are broken down into fractions and then returned to us as floating point numbers where fractions are not as accurate as floating point numbers. This will give us a slight rounding issue with our floating point numbers.  There are ways to be more exact by either using a built-in function called round or by using a module called decimal. Now that you understand that Why are floating point calculations so inaccurate in Python we can safely say we are moving in the right direction to learn programming.



Thursday, June 11, 2015

gc.get_threshold() - Python Tutorial


gc.get_threshold()


gc.get_threshold() is a function that we can use when we import the garbage collection module. This function will return when the garbage collection algorithm will run to clean up the memory. The number that is returned to us is the threshold when the algorithm is ran.  


gc.get_threshold() Example


#gc.get_threshold()

>>> import gc
>>> gc.get_threshold()
(700, 10, 10)

 


gc.get_threshold(threshold0, threshold1, threshold2)


You will see three numbers returned to us and these numbers are set at three different runs of the garbage collection. First one is ran when the allocations minus the deallocations exceed the number displayed.Default for threshold0 is 700. If the object survives the first run it is relocated into the second run. The second number returned to us is when the second garbage collection will run this is threshold1 of garbage collection this number is based on the number runs that threshold0 does. The succeeding generation default is 10 so in this case threshold0 run must run ten times before the threshold1 of garbage collection is ran. If an object survives the subsequent run it is now moved into the third and final run and the object will stay here until it is removed. Threshold2 will run based off threshold1 runs.  The default is 10 threshold1 runs. So, when the threshold1 runs ten times the final generation will run.


 



Python Numbers - Chapter 4 - Python Tutorial

Python NumbersPython Numbers


Welcome to Python Numbers in chapter 4 of our Python Tutorials we are going to focus on numbers, math that we can perform in Python, operators used for numbers, a couple math modules and booleans.  Like the previous chapter, we will go deep into the Python numbers and focus on each and every aspect of Python numbers.


Python Numbers Tutorials


Below you will find a list of the scheduled Python numbers tutorials. These tutorials are not set in stone and can change as we move along.


  1. Why are floating point calculations so inaccurate?

  2. Round() Built-in Function

  3. Python Decimal Module

  4. Python Addition

  5. Python Subtraction

  6. Python Multiplication

  7. Python Division

  8. Python Modulo

  9. Python Exponentiation

  10. Python Mixed Operators Flow

  11. Manually Adjust The Operator Precedence

  12. Convert Number Types in Python

  13. Booleans In Python

  14. Python Comparison Operators

  15. Python Sets

  16. Python Booleans

  17. Python Math Module