Sunday, May 3, 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.


 



Saturday, May 2, 2015

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.



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.


 



Friday, May 1, 2015

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

 


 



Python Garbage Collection - Python Variables - Python Tutorial

 


Python Garbage CollectionPython Garbage Collection


One of the nicest things about the Python programming language is the Python garbage collection feature which will monitor and free up memory automatically. If we had to manage memory in Python programs we would devote more time allocating memory in our programs then we would be writing the program. In this Python tutorial, we will have a close look at how Python manages memory with its garbage collection algorithm.


What is Garbage Collection?


Garbage collection is a process whereby a program runs some code to clean up unused memory. In previous Python tutorials, we have discussed that the blocks of memory in Python are designated as objects. When these objects are not required anymore than the garbage collection system jumps in and removes those objects to clear up memory for more objects. This is all automatic so we are not required to initiate the garbage collection system to free up memory.


How Does The Garbage Collection Work?


When an object is no longer used then the garbage collection algorithm will remove the object. This is where the reference counter becomes involved. If the object is referenced then the reference counter increments up by one and when the reference to that object is removed then the counter increments down.  When the objects reference counter is at zero(No References To The Object) then that object will be deleted. The reference counter method is great but there are cases where this method of removing objects doesn’t always work.


Reference Cycles


Sometimes the objects reference counter never goes to zero and there is a lack of physical reference to an object. This happens when an object reference itself and this is referred to as a reference cycle. In this case, Python relies on a schedule for garbage collection to run. Each time a reference is added or removed the system will count the occurrence and when the number of occurrences reaches a set number then the garbage collection will run and remove reference cycles.


#Example of a Reference Cycle

>>> a = []
>>> a.append(a)
>>> a
[[...]]

In the above example, the variable “a” is assigned to an empty list then we append “a” to itself. Now we have an object referencing itself and in this case the list objects reference counter would never go to zero.


When Will Garbage Collection Run?


Garbage collection runs when the number of references added and deleted hit a certain number. We can find this number by importing the garbage collection module which gives us the ability to control the garbage collection. Let’s take a look at when will the garbage collection runs.


#When Will Garbage Collection Run?

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

We see 700 that means deallocation must reach 700 then the garbage collector will run and remove reference cycles. If an object is not removed in the first run it is forwarded to the second run. The second run will run when first run has run 10 times. If an object survives it will be moved to the third run which is the definitive run and this where the object will stay till it is removed. The third run will run when the second run has run ten times.


Now we have covered the Python Garbage Collection we understand how Python automatically handles memory.  There is a module called garbage collection which we briefly discussed in this tutorial. We will examine the garbage collection module in full in its own tutorial. If you have any questions please let us know by leaving a comment below.


Updated


March 11, 2015 – Changed the explanation of garbage collection run times



Thursday, April 30, 2015

keyword.iskeyword() - Python Tutorial

keyword.iskeyword()


The is keyword.iskeyword() command is used with the keyword module to check if a word is a keyword within the Python Programming Language. We must import the module for this command to work . If a word is a keyword we will get a boolean as True and if a word is not a keyword in Python then we will get a boolean False.


keyword.iskeyword() Syntax


keyword.iskeyword(‘word’)


Note that the word needs to be in a string format.


keyword.iskeyword() Example


#keyword.iskeyword() Example

#import keyword module
>>> import keyword

#check if a word is a keyword with a True return
>>> keyword.iskeyword('def')
True

#check if a word is a keyword with a False return
>>> keyword.iskeyword('dog')
False

#remove keyword module
>>> del keyword

 


 



keyword.kwlist - Python Tutorial

keyword.kwlist


keyword.kwlist will display a list of Python keywords when the keyword module has been imported. If you ever need to know the list of reserved words in the Python Programming Language we can import the keyword module and call keyword.kwlist to display a list of keywords.


keyword.kwlist Example


#keyword.kwlist

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

#remove keyword module
>>> del keyword

If you have any questions about the keyword module or the keyword.kwlist command leave a message below we will help you out.