Monday, March 23, 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 Tutorial: Operator Precedence in Python - Python Numbers

Operator Precedence in Python - Python Numbers - Python Tutorial

Operator Precedence in PythonOperator Precedence in Python


In this Python tutorial, we are going to look at operator precedence in Python. We will be focusing on the operators we have already learned like **, *, /, //, %, + and -. It is important to understand what operator will run first.


Operator Precedence


The list below will show which operator has more precedence over the operators.  So the first operator in the list will run before the second operator below.


  1. ** – Exponent

  2. *, /, %, // – Multiplication, true division, modulo, floor division.  In this case if these operators where in the same equation then the equation would run left to right.

  3. +, – Addition and Subtraction are the last operators to run.

Operator Precedence Examples


Let’s look at some examples and figure out which operator will run in the equation. The order in which the operators run could have some serious effects on your results.


Exponent and Multiplication


Exponent will always run before the multiplication equation. Take a look at the example.


#Exponent and Multiplication

#Exponent Runs First

>>> 2 ** 2 * 2
8

#If multiplication ran first this answer would be 16
>>> 2 * 2 ** 2
8

Exponent and Division


Exponent will always run before a division equation. Take a look at this example.


#Exponent and Division

#exponent runs first
>>> 4 / 2 ** 6
0.0625

#2 ** 6 is 64
>>> 4 / 64
0.0625

Multiplication and Division


In this scenario Python will run the equation from left to right since multiplication and division have the precedence. Take a look at the example below.


#Multiplication and Division

#In this case division is ran first then multiplied by 3
>>> 5 / 4 * 3
3.75

#In this case 3 is multiplied by 4 then divided by 5
>>> 3 * 4 / 5
2.4

Multiplication and Addition


Multiplication will run before an addition equation since multiplication has more precedence over addition. Here is an example.


#Multiplication and Addition

>>> 2 + 4 * 4
18

Addition and Subtraction


In this scenario the equation will run left to right since addition and subtraction are on the same level.


#Addition and Subtraction

>>> 2 + 3 - 5 + 8 - 4 + 2 - 9
-3

Conclusion


In this Python tutorial, we took a look at Operator Precedence in Python it is important to remember which operator will run first because you can end up with different values if you are not paying attention when setting up your equations. In the next Python tutorial, we will look at a way to manually change the order.



Sunday, March 22, 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. Python Parenthese Flow

  12. Python Comparisons

  13. Python Fractions

  14. Python Decimals

  15. Python Sets

  16. Python Booleans

  17. Python Math Module

 


 



User Select Temperature Conversion Python Program – Part 2 - Python Tutorial

User Select Temperature Conversion Python ProgramUser Select Temperature Conversion Python Program – Part 2


In this Python tutorial, we will improve our program we built-in the previous tutorial called user select temperature conversion Python program. This is a great opportunity to see how to work through your program to address issues and limit the amount of time troubleshooting your program after release. Recall that it is always important to trouble shoot your programs over and over before you release it. If you release a program that contains issues in the world, then you will spend more time handling support than you would working on your next project.


Functions and Methods In This Python Tutorial


  • print()

  • input()

  • if statement

  • .lower()

  • .strip()

  • .format()

  • float()

  • round()

  • slice [0]

Issues with our Program


We saw some issues in our first Python program that would have made our program less desirable to our users.  First issue we saw was that the user would have to capitalize celsius or fahrenheit and prior experience, I know users are unlikely to use the shift key when they want a quick answer. Second issue we saw was if the user inputs the wrong command in the code would still run and then return an error which is not good practice if the program fails then the user should know why right away. Issue three if the user spelled fahrenheit or celsius wrong the program would fail that is not the right idea users would be turned off and never use our program. Let’s look at the issues and work through them and fix them


Code From Version 1.0 Of Our Program


#Code From Version 1.0 Of Our Program

print('Welcome To Our Temp Conversion Program')
temp = input("What temp would you like to convert to? Type Celsius or Fahrenheit. ")
userstemp = float(input("What is your temp to be converted. "))

if temp == 'Celsius':
cel = round((userstemp - 32) * 5 / 9, 1)
print("Your temp in Celsius is ".format(cel))
elif temp == 'Fahrenheit':
fah = round(userstemp * 9 / 5 + 32, 1)
print("Your temp in Fahrenheit is ".format(fah))
else:
print("Whoops Something went wrong")

Fixing The Issues in Version 1.0


We need to fix this program so it runs flawlessly when we release the program to our clients. Our goal is to make the program more user friendly and reliable.


Issue 1


Issue 1 –  The program runs even if the user gives us the wrong command


If the user gives us the wrong command in our second line of code then line third line will still run and then kick back an error.  This is not good practice if the user does something wrong they should be alerted right away.


The Fix


We can fix issue 1 by moving the third line of our code which asks the user to input the current temperature into the if statement. We will now use this line twice once in the if statement and once in the elif statement.This ensures our code will only work when the user inputs the correct command.


The Code 


#issue 1 code

print('Welcome To Our Temp Conversion Program')
temp = input("What temp would you like to convert to? Type Celsius or Fahrenheit. ")


if temp == 'Celsius':
userstemp = float(input("What is your temp to be converted. "))
cel = round((userstemp - 32) * 5 / 9, 1)
print("Your temp in Celsius is ".format(cel))
elif temp == 'Fahrenheit':
userstemp = float(input("What is your temp to be converted. "))
fah = round(userstemp * 9 / 5 + 32, 1)
print("Your temp in Fahrenheit is ".format(fah))
else:
print("Whoops Something went wrong")

Tip: Any time you make changes to your program I suggest you run the program so you can locate any issues that may arise from the code changes. If the program does not work then you will know the problem code.


Issue 2


Issue 2 – If the user does not capitalize Celsius or Fahrenheit then the program will fail


When the user types in a command in our current code they must capitalize the first letter.  In my prior experience users do not necessarily do so. This will cause the program to fail and this would not be good for our business. User’s would think we build crappy programs and go to our competition which would not be a good idea.


The Fix


We can easily fix this problem using .lower() string method which will make the users input lowercase which will give us the ability to anticipate the user’s input.  If we use the .lower() string method then we need to change our if and elif statements so that our code has celsius and fahrenheit in lowercase so it matches the users input.


The Code


#issue 2 code

print('Welcome To Our Temp Conversion Program')
temp = input("What temp would you like to convert to? Type Celsius or Fahrenheit. ").lower()

if temp == 'celsius':
userstemp = float(input("What is your temp to be converted. "))
cel = round((userstemp - 32) * 5 / 9, 1)
print("Your temp in Celsius is ".format(cel))
elif temp == 'fahrenheit':
userstemp = float(input("What is your temp to be converted. "))
fah = round(userstemp * 9 / 5 + 32, 1)
print("Your temp in Fahrenheit is ".format(fah))
else:
print("Whoops Something went wrong")

Issue 3


Issue 3 – If the user uses a space in our code then the code will fail


If the user uses a space in front of the command or after the command then our code will fail and once again we will want to avoid this.


The Fix


To ensure that the user does not use a space in front of command or after the command, we need to use a string method called .strip() this will remove the spaces before and after the command.


The Code


#issue 3 code

print('Welcome To Our Temp Conversion Program')
temp = input("What temp would you like to convert to? Type Celsius or Fahrenheit. ").lower().strip()

if temp == 'celsius':
userstemp = float(input("What is your temp to be converted. "))
cel = round((userstemp - 32) * 5 / 9, 1)
print("Your temp in Celsius is ".format(cel))
elif temp == 'fahrenheit':
userstemp = float(input("What is your temp to be converted. "))
fah = round(userstemp * 9 / 5 + 32, 1)
print("Your temp in Fahrenheit is ".format(fah))
else:
print("Whoops Something went wrong")

Issue 4


Issue 4 – If the user spells the command wrong code will fail


If the user misspells celsius or fahrenheit wrong then our code will fail.  We want to think of ways a user could make our code fail and avoid the scenario at all cost.


The Fix


We could use a slice on the user’s input to get just the users first letter. Since the two commands start with different letters, we can avoid spelling mistakes by getting the users first letter and running the code based off that. We indicate a slice with square brackets[ ] and then we put zero in the square brackets which says we want the first letter of the users command.  We will need to change if and elif statements to c and f since we just want the first letter.


The Code


#Issue 4 Code

print('Welcome To Our Temp Conversion Program')
temp = input("What temp would you like to convert to? Type Celsius or Fahrenheit. ").lower().strip()


if temp[0] == 'c':
userstemp = float(input("What is your temp to be converted. "))
cel = round((userstemp - 32) * 5 / 9, 1)
print("Your temp in Celsius is ".format(cel))
elif temp[0] == 'f':
userstemp = float(input("What is your temp to be converted. "))
fah = round(userstemp * 9 / 5 + 32, 1)
print("Your temp in Fahrenheit is ".format(fah))
else:
print("Whoops Something went wrong")

Conclusion


We have now updated our program to version 1.1 which is now more user friendly and less likely to break when our clients use our program. I have a tendency to build programs like this I will first build one so I can get the result I want and then I will work my way through the program fixing issues that may arise. I will concentrate on the users experience, program speed and reliability. If we can fix all the issues in our program before we release the program we will live a happy life.


If you have any questions about User Select Temperature Conversion Python Program leave a comment below and we will do our best to help you out.



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



Saturday, March 21, 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