Tuesday, March 31, 2015

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.



User Select Temperature Conversion Python Program - Python Program Tutorial - Python Tutorial

User Select Temperature Conversion Python ProgramUser Select Temperature Conversion Python Program


In this Python tutorial, we are going to show you how to improve our previous two Python programs that we built by adding a feature where the user can select their conversion. We will build a user select temperature conversion Python program. This program will actually combine our previous two programs into one program and make the program more user friendly.


Functions, Methods and Control Statements Used In This Python Tutorial


  • print()

  • input()

  • float()

  • If Statement

  • round()

  • .format()

Python Program Build


Step 1 – Open Text Editor and Save Project


We first have to open our text editor and save the project as usertemp.py.


Step 2 – Welcome Statement


We use a print() statement in this case to return the text ‘Welcome To Our Temp Conversion Program’.


#Welcome Statement

print('Welcome To Our Temp Conversion Program')

Step 3 - Users Conversion Selection


This steps we ask the user which type of temperature conversion they would like to perform. The user will be able to select their type by typing Celsius or Fahrenheit into the command line. We first create a variable called ‘temp’ and assign this variable to the user’s input.  To get the user’s input we use input() and tell them to enter one of two commands.


#Users Conversion Selection

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

Step 4 – User’s Temperature Input


This step we ask the user for their temperature and assign their input to the variable ‘userstemp’.  Create a variable called ‘userstemp’ and assign it to the users input().


#User's Temperature Input

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. "))

Step 5 – Flow Statement “IF Statement”


In this step, we introduce an if statement which will help us return the proper conversion to the user. I know we have not been covered if statements yet which we will cover in full in our Python tutorials shortly. It is good to see some advanced features of the Python programming language as we move along.

First thing we need to do is create the if statement. On the first line of the if statement, we say if the user’s input is equal to celsius then run the code below which is our code from our previous tutorial celsius conversion. If it is not equal to celsius then move on to the next if statement(elif).


#Flow Statement "IF Statement"

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))

Step 6 – Flow Statement “elif Statement”


In this step, we need to create a elif statement which is part of the if statement. If the previous statement is not true, then the program will skip the code below and move on to our elif statement. For the elif statement we want to see if the user entered ‘Fahrenheit’ if the user entered ‘Fahrenheit’ then our block of code contained in the elif statement will run. This code is similar to our previous Python tutorial where we converted celsius to fahrenheit.


#Flow Statement "elif Statement"

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))

Step 7 – Flow Statement “else”


In the final step of our program we have an else statement.  If the user enters anything other than ‘Celsius’ or ‘Fahrenheit’ the code will run the else statement.  This happen if the user misspells ‘Celsius’ or enters a word we did not request.  The else statement contains a simple print() statement.


#Flow Statement 'else'

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")

Step 8 – Run The Program


Open your terminal or command prompt. cd into your desktop and type ‘python3 usertemp.py’ this will run your Python program. Try it out to make sure it works if it does that is great if you run into problems check your code with ours. If it does work, then your goal is to break the program. When you break your program, you should take notes how the failures in your code and this is how we know where our code needs to improve.


#Run The Program

Thomass-MBP:desktop Tommy$ python3 userstemp.py
Welcome To Our Temp Conversion Program
What temp would you like to convert to? Type Celsius or Fahrenheit. Fahrenheit
What is your temp to be converted. 26.5
Your temp in Fahrenheit is 79.7

Awesome we created a program that will take a user’s command indicating which type of conversion and then we also will take the temperature that needs to be converted.  If you played around with the program you probably noticed there are some issues we could have if we released this program to the public.


Issues with our program


  1. User must type the proper word with proper capitalization if not we will get an error.

  2. If the user does not enter the conversion properly the program will still ask for the users temperature which will not indicate to the user that they entered the wrong command.

In the next tutorial we will make some changes to the code to we can make it more user friendly and more reliable.


If you have any questions about this Python tutorial building a User Select Temperature Conversion Python program please leave a comment below we are here to help you learn Python.


Source Code

 


 



Monday, March 30, 2015

Exponents In Python - Python Numbers - Python Tutorial

Exponents in PythonExponents In Python


In this Python Tutorial, we are going to look at exponents in Python. We first need to realise what an exponent is. An exponent is the power to which a number is raised. For example 2 * 2 * 2 is equivalent to 8. With an exponent, we can cut down on writing the whole equation out and use **(exponent in Python) by using this operator we are doing the equation in shorthand. Example of exponent 2 ** 3 is equal to 8.  Less typing the same outcome.


Examples Exponents In Python


We will perform all these examples in our Python interpreter. Make sure you follow a long and do some of your own. The best way to learn Python is by practicing.


#Examples of Exponents In Python

>>> 2 ** 4
16

>>> 78 ** 97
3413315720704337419097101027000771686980504078677575730926905758203118108388932801027381449501146100963728165489443041132814728861531870470672271776414594578193877674244432184882495488

>>> 5 ** 5
3125

>>> 4 ** 2
16

>>> 9 ** 7
4782969

>>> 7.5 ** 4
3164.0625

As you can see there is not much to exponents in Python. Since exponents are pretty simple to work with there is not much to this Python tutorial. Just remember that exponents are available to you and the syntax and you will be all ready to go.



Modulo Operator to Get Remainder In Python - Python Numbers - Python Tutorial

Modulo Operator to Get Remainder In PythonModulo Operator to Get Remainder In Python


In this Python tutorial we are going to focus on Modulo Operator to Get Remainder In Python.  We could use modulo to get remainder after division is performed.  This can be a little confusing at times so make sure you check work closely to make sure your program is performing as expected.


How Modulo Operator Works


To implement the modulo operator we need to use the percent sign(%) in our equations. When use the percent sign in an equation we will get the remainder after division is performed. Sometimes this will return a number that does not make much sense so we will look at that as well.


Modulo Examples


In this tutorial all the examples will be carried out in the Python interpreter. We suggest you open your Python interpreter and follow a long. Practicing modulos will help you figure out how it actually works.


#Modulo Examples

#No remainder when you divide 8 by 2
>>> 8 % 2
0

#10 divided by 3 is 9 with 1 left over
>>> 10 % 3
1

#12.5 divided by 5 is 2.5
>>> 12.5 % 5
2.5


Now the Confusing Modulo Equations


This may or may not be confusing to you, but I remember when I first learned how to use modulo this was a bit confusing to me a times until I figured out what was going on.


#Now the Confusing Modulo Equations

#What is going on here?
#When you use modulo here where numbers go in evenly it will return the exact number of the modulo number
>>> 25 % 50
25


#This is also the proper remainder
>>> 30 % 70
30

In the above example what is going on? Well we can not divide a smaller number by a larger number.  Think of this way if you have a job to go out and get 70 beers and not to return till you got these 70 beers going to a store with only 30 is not going to cut it so when you leave that store the store still has 30 beers. This is the best way I can explain it.

In this tutorial, we looked at Modulo Operator to Get Remainder In Python which is a useful tool to find the remaining numbers. If you have any questions please leave a comment below.



Sunday, March 29, 2015

Fahrenheit To Celsius Conversion Program in Python - Python Tutorial

Fahrenheit To Celsius Conversion Program in PythonFahrenheit To Celsius Conversion Program


In this tutorial, we are going to build a simple Fahrenheit to Celsius Conversion Program in Python. This program is similar to our previous program with some slight changes to perform fahrenheit to celsius conversion.


Functions and Methods Used 


  • printt()

  • float()

  • input()

  • round()

  • .format()

Step 1 – Open Text Editor and Save Program


In the first step, we need to open your preferred text editor we use Sublime Text and save your program to your desktop as ftoc.py.


Step 2 – Write a welcome to our users


In this step, we are going to write a simple welcome statement to our users using a print statement.


#Write a welcome to our users

print("Welcome to Fahrenheit to Celsius Program")

Step 3 – User’s Input


First we need to create a variable in this step we created a variable called “fah” for fahrenheit.  Then we need to convert the user’s input to a floating point number using float().  Then we prompt the user for a number using the input() function.


#User's Input

print("Welcome to Fahrenheit to Celsius Program")
fah = float(input("Please give us a temperature in Fahrenheit. "))

Step 4 – The Conversion


In this step, we have to create a variable to point to the value we get from our conversion. We create a variable called “cel” for celsius. We will need to round this equation so we put the equation in the round() function with one number after the decimal. Then we have to put the first part of the equation in parentheses so this part is performed before any other part of the equation (fah – 32). Then we need in order to finish off the equation by multiplying by 5 and then divide by 9.


#The Equation

print("Welcome to Fahrenheit to Celsius Program")
fah = float(input("Please give us a temperature in Fahrenheit. "))
cel = round((fah - 32) * 5 / 9, 1)

Step 5 – Return the conversion to the user


We return to the conversion to the user using a print() statement which we .format() to include our variable “cel” which will be replaced by the value of our conversion.


#Return Conversion To User

print("Welcome to Fahrenheit to Celsius Program")
fah = float(input("Please give us a temperature in Fahrenheit. "))
cel = round((fah - 32) * 5 / 9, 1)
print("The temperature in Celsius is ".format(cel))

Step 6 – Run the Program


To run the program open your terminal or command prompt.  Cd into your desktop directory and enter python3 ftoc.py


#Run The Program

Thomass-MBP:desktop Tommy$ python3 ftoc.py
Welcome to Fahrenheit to Celsius Program
Please give us a temperature in Fahrenheit. 78
The temperature in Celsius is 25.6

In this Python Programming Tutorial, we created a Fahrenheit to Celsius Conversion Program in Python. If you have any questions please leave a comment below and we will help you out.


 



Division In Python - Python Numbers - Python Tutorial

Division in PythonDivision In Python


We have seen division way back in one of our earlier tutorials.  In Python 3, there are two different types of division we can do first one being true division and the second being floor division. Understanding what value you need to return to you is key when working with division in Python.


What Is True Division In Python


True division is represented by a single backslash(/) and we get our results as a floating point number which will return the remainder in the position after the decimal.


True Division Examples


#True Division Examples

>>> 3 /7
0.42857142857142855

>>> 8 / 9
0.8888888888888888

>>> 90 / 3
30.0

>>> 8 / 5
1.6

>>> 45890 / 78
588.3333333333334

>>> 89 / 12
7.416666666666667

>>> 90.0 / 3
30.0

Floating Point Accuracy


We have talked about the floating point accuracy a lot in our previous tutorials. When using division in Python we see a lot of numbers returned inaccurate do the fraction and floating point conversion.  To fix these issues, we need to use the built-in function round() or the decimal module that is available to us. We will not cover them in this tutorial so if you have not seen those tutorial I suggest your visit the round() tutorial or decimal module tutorial.


What is Floor Division


Floor division is represented by a double backslash(//). Floor division will return with a rounded down floating point number or integer and this return type is based off which type we use in the equation. Which means that we will not get a remainder when we use the floor division operator.


Floor division Example


#Floor division Example

#integers
>>> 89 // 9
9

>>> 124345 // 67
1855

>>> 345 // 8
43

>>> 89 // -6
-15

>>> 787643 // 2345
335

#floats
>>> 689.90 // 987
0.0

>>> 8976.98 // 76
118.0

>>> 865 // 8
108

>>> 78.6768789789 // 2
39.0

>>> 765734.1 // 67.3
11377.0

Conclusion


We have just seen how to perform division in Python. When writing your program, you need to figure out how precisely you would like your numbers. If you need a precise number, then I would use true division if you need a number that was not as precise the floor division may be a better decision.

If you have any questions about our Python tutorial on division in Python leave, a comment below and we will help you out.


 



Saturday, March 28, 2015

Convert Celsius to Fahrenheit Python Program tutorial - Python Tutorial

Convert Celsius to Fahrenheit Python Program tutorialConvert Celsius to Fahrenheit Python Program tutorial


In this Python tutorial, we are going to build a Python program that will convert celsius to fahrenheit. This is another very simple program that takes the users input and converts celsius temperature to a fahrenheit temperature and prints the temperature back to the user.


Functions and Methods Used in This Tutorial


  • print()

  • float()

  • .format()

Build The Python Program


In this program, we will be using Python 3, a text editor of your choice we use Sublime Text and the Python interpreter.


Step 1 – Open Text Editor and Save Program


Open your text editor and save your file to your desktop as ctof.py(Celsius to Fahrenheit). The dot py is a Python extension.


Step 2 – Welcome Message to Users


We want to just add a very simple welcome message to the users.  To this we use the print() function.


#Welcome Message to Users

#Spelled celsius and Fahrenheit wrong sorry!
print("Convert Celcius to Fahreheit")

Step 3 – Retrieve the users input


To retrieve the user’s input we first need to assign a variable to that object the user will create. In this step, we create a variable called “cel” for celsius. We then need in order to convert the number to a floating point number using the float() function in Python. Then we use the input() function to get the users temperature in celsius.  We also prompt the user for the input() function by adding a string “Input temperature in celsius”.


#Retrieve the users input

print("Convert Celcius to Fahreheit")
cel = float(input("Input tempature in celcius. "))

Step 4 – The conversion


In this step, we need to assign a variable to the value of our equation. We create a variable called “fah” and assign the returned value from our conversion. To convert celsius to fahrenheit we first need to input the user’s value by using the variable called “cel” then multiply that number by 9 then divide by 5 and then add 32 to get the temperature in fahrenheit.


#The conversion

print("Convert Celcius to Fahreheit")
cel = float(input("Input tempature in celcius. "))
fah = cel * 9 / 5 + 32

Step 5 – Print conversion to user


In this step, we need to return the conversion to the user. We do this using a print() statement and use .format() method to convert the string.


#Print Conversion To User

print("Convert Celcius to Fahreheit")
cel = float(input("Input tempature in celcius. "))
fah = cel * 9 / 5 + 32
print("The tempature in Fahreheit is ".format(fah))

Step 6 – Save and Run the program


Save your program and we need to run the program.  To run the program we will go into our terminal or command prompt and cd into our desktop and type python3 ctof.py and press return.


#Save and Run the program

Thomass-MBP:desktop Tommy$ python3 ctof.py
Convert Celcius to Fahreheit
Input tempature in celcius. 22
The tempature in Fahreheit is 71.6

Conclusion 


In this Python tutorial, we built a very simple program that will convert celsius to fahrenheit and return the value to the user. If you have any questions please leave a comment below and we will help you out.


 


Source Code

Multiplication In Python - Python Numbers - Python Tutorial

Multiplication in PythonMultiplication In Python


In this Python tutorial, we will be focusing on multiplication in Python. Multiplication is another simple concept in the Python programming language. We use the asterisk(*) to indicate multiplication.


Examples of Multiplication In Python


#Examples of Multiplication In Python

#Integers
>>> 7 * 8
56
>>> 33 * 98
3234
>>> 44 * 7
308
>>> 23 * -4
-92

#floats
>>> 7.8 * 9.5
74.1
>>> 8.65 * 7.34
63.491
>>> 67.23 * 56.8
3818.664

Multiplication is so straightforward in Python that there is not much to it.  I suggest you play around with multiplication if you run in to float that not returning like they should then go ahead and try to fix them using round() or decimal module.


If you have any questions about multiplication in Python leave a question in our Q & A section of our website.



Friday, March 27, 2015

How do I switch into a directory that has a space - Python Tutorial

I am trying to switch into my “Python tutorials” but using cd will not allow me to switch.  Is there a way to do this?  Do I have to change the name?



Less Than or Equal to

Less Than or Equal to <=


The less than or equal to <= comparison operator checks if the object on left is less than or equal to the object on the right and if it is then Python returns True.  If the object on the left is greater than the right then Python will return False.


Less Than or Equal to <= Examples


#Less Than or Equal to <=

>>> 4 <= 5
True
>>> 5 <= 5
True
>>> 6 <= 5
False

If you have any questions about less than or equal to <= leave a comment below so we can assist you.



Greater Than or Equal to >= - Python Tutorial

Greater Than or Equal to >=


The Greater Than or Equal to >= will check if the left side is greater or equal to the right side if it is then Python will return True and if left side is less than the right then Python will return False


Greater Than or Equal to >= Examples


= Examples" >#Great Than or Equal to >= Examples

>>> 7 >= 5
True
>>> 4 >= 5
False

If you have any questions about Greater Than or Equal to >= leave a comment below so we can help you better understand this comparison operator.



Not Equal != - Python Tutorial

not equal !=Not Equal !=


The not equal to symbol will compare the left side to the right side. If the object on the left is not equal to the object on right then Python will return True and if they are equal to each other then Python will return False


Not Equal != Examples


#Not Equal != Examples

>>> 5 != 4
True
>>> 5 != 5
False

If you have any questions about not equal != leave a comment below.



Equal To == - Python Tutorial

Equal To ==Equal To ==


Equal to symbol == compares the object on the left to the object on the right if they are equal to one another than Python will return True and if the left is not equal to the right than Python will return False.


Equal To == Examples


#Equal To == Examples

>>> 5 == 5
True
>>> 5 == 6
False

If you have any questions about equal to == leave a comment below.


 



> - Python Tutorial

>The > simple is used as a comparison operator in Python.  If the object on the left of the > is greater than the object on the right then Python will return True.  If the object on the left of > is less than the object on right then Python will return False.


> Examples


 Examples" ># > Examples

>>> 2 > 1
True
>>> 1 > 2
False

If you have any questions about the Python > leave a comment below.




>

Python Comparison Operators - Python Numbers - Python Tutorial

Python Comparison OperatorsPython Comparison Operators


In the previous Python tutorial, we looked at booleans now we can use some Python comparison operators to get a boolean returned to us.  Python comparison operators are a vital part of programming with Python. We use the comparison operators to compare objects and tell the program to do something when a certain return happens.  We can compare if an object is greater than, less than, equal to, not equal to, greater than and equal to or less than and equal to.


Single Comparison Operators


== Equal Or Not Equal


The == symbols will check if the left side is equal to the right if so Python will return True if not then we get False. Do not make the mistake of using a single equal symbol like =, you will get an error or assign a variable.


#== Equal Or Not Equal

>>> 6 == 6
True
>>> 6 == 7
False

!= Not Equal or Equal


The != symbols will check if the left side is not equal to the right side if so Python will return True but if the left is equal to right then we will get False. This is opposite of the == operator.


#!= Not Equal or Equal

>>> 6 != 8
True
>>> 5 != 5
False

> Left is Greater Than Right


The > symbol will check if the left side is greater than the right.  If the left is greater Python will return True and if left is less Python will return False.


 Left is Greater Than Right" ># > Left is Greater Than Right

>>> 6 > 5
True
>>> 6 > 8
False

< Right is Greater Than Right 


The < symbol will check if the right side is greater than the left.  If the right if greater Python will return True and if the right is less Python will return false.


# < Right is Greater Than Right 

>>> 5 < 6
True
>>> 6 < 5
False

>= Left is Greater Than or Equal to Right


The >= symbols check if the left side is either greater or equal to the right side.  If the left is greater or equal to right then Python returns True if left side is less than right then Python returns False.


= Left is Greater Than or Equal to Right" ># >= Left is Greater Than or Equal to Right

>>> 7 >= 6
True
>>> 6 >= 6
True
>>> 5 >= 6
False

<= Right is Greater Than or Equal To Left


The <= right is greater than or equal to the left. If the right is greater or equal to the left then Python will return True if right side is less than Python will return False.


# <= Right is Greater or Equal To Left

>>> 6 <= 7
True
>>> 6 <= 6
True
>>> 6 <= 5
False

Chained Comparisons


Now that we have learned to use Comparison Operators in Python we can actually compare larger amounts of data using something called chained comparisons.  We will show you a bunch of examples below but they are pretty straight forward if you understand Comparision Operators so we will not explain each one.


#Chained Comparison Operators

>>> 4 < 6 < 8
True
>>> 7 > 4 == 4
True
>>> 9 != 7 != 6
True
>>> 10 > 8 > 6 > 4 > 2 > 0
True

>>> 5 > 2 and 7 < 10
True
>>> 6 == 6 or 7 != 5
True

Conclusion


Comparison operators are very simple to use and are effective in programming.  You will become very familiar to comparison operators as you move on in your Python programming career.  If you have any questions about Python comparison operators let us know via comment below.



Python Tutorial: Python Comparison Operators - Python Numbers #37

Subtraction Program In Python - Python Programs - Python Tutorial

subtraction program in PythonSubtraction Program in Python


In this Python programming, tutorial we are going to create a simple Subtraction Program in Python. In this program, we are going to add the ability to use floats not integers.


Functions and Methods Used in This Program


  • input()

  • float()

  • print()

  • .format()

  • round()

Step 1 – Open Your Text Editor


Open your text editor in this tutorial we use Sublime Text 3


Step 2 – Save your file


Save your file by pressing command + s or control + s.  Name your file subtraction.py and save to your desktop.


Step 3 – Create Welcome Print Statement


We want to welcome our users to our program so we will add a simple print statement doing so.


#Create Welcome Print Statement

print("Welcome to our subtraction program")

Step 4 - Get the users first number


In this step, we will get the users number using input() and then convert that number to a floating point number using float(). Then we will assign the value to a variable called firstnum.


#Get the users first number

print("Welcome to our subtraction program")
firstnum = float(input("What is your first number. "))

Step 5 – Get the users second number


This step is similar to step 4 with the only difference being we are going to assign the value to the user gives to a new variable called secondnum.


#Get the users second number

print("Welcome to our subtraction program")
firstnum = float(input("What is your first number. "))
secondnum = float(input("What is your second number. "))

Step 6 – Get Users Difference


This step we will get the users difference between two numbers and round the number to two numbers after the decimal and save the difference to a variable called thesum.


#Get Users Difference

print("Welcome to our subtraction program")
firstnum = float(input("What is your first number. "))
secondnum = float(input("What is your second number. "))
thesum = round(firstnum - secondnum, 2)

Step 7 – Print The Difference Back to User


This is our final line of code in our little program here.  We want to print the difference back to the user so to do that we use a print() statement and format the string print backs the value within thesum.


#Print The Difference Back to User

print("Welcome to our subtraction program")
firstnum = float(input("What is your first number. "))
secondnum = float(input("What is your second number. "))
thesum = round(firstnum - secondnum, 2)
print("Your difference is ".format(thesum))

Step 8 – Run The Program


Open your terminal or command prompt.  Change into your desktop and run the program by typing python3 subtraction.py


#Run The Program

Thomass-MBP:~ Tommy$ cd desktop
Thomass-MBP:desktop Tommy$ python3 subtraction.py
Welcome to our subtraction program
What is your first number. 4
What is your second number. 5
Your difference is -1.0

Now that you have seen the way to build a simple subtraction program in Python with floating point numbers. Play with the program try to improve it and make your own modifications. If you can break let us know so we can do a tutorial how to improve the subtraction program.  If you have any questions leave a comment below and we will help you.



Thursday, March 26, 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.



Python Tutorial: Booleans in Python - Python Numbers #36

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

 



Booleans In Python - Python Numbers - Python Tutorial

booleans in pythonBooleans In Python


In this Python tutorial, we are going to look at booleans in Python. Booleans are sometimes called truth statements in programming. Booleans are returned only a True or False.  You may be asking why we are covering booleans in the numbers section our Python tutorial. Booleans are indeed part of the integer family. A True boolean is equal to 1 and a False boolean is equal to 0.


Boolean Examples in Python


We will be checking out examples of booleans. Some of the methods, operators or functions may have not been covered yet in our tutorial series.  Just follow along we are going to get to all these very shortly. All these examples will be performed in our Python interpreter.


#boolean Examples in Python

#Boolean Operations
>>> False or True
True
>>> True or False
True
>>> False or False
False
>>> True or True
True
>>> True and False
False
>>> True and True
True
>>> False and False
False
>>> not False
True

#Comparison Operators
>>> 7 < 9
True
>>> 8 > 8
False
>>> 8 != 9
True
>>> 8 == 8
True
>>> 8 <= 9
True


Proof That Booleans are Integers


#Proof That Booleans are Integers

>>> True + False
1
>>> True * False
0
>>> True ** 8
1
>>> type(True)
<class 'bool'>
>>> a = True + False
>>> type(a)
<class 'int'>

We will do a lot of work with Python booleans over the next couple of Python tutorials. If you have any questions about booleans in Python leave, a comment below so we can help you.


 



str() - Python Tutorial

str() built-in function



 


str() Built-in Function


str() is a built-in function in Python that will convert an other type like a integer, float, list, tuple and so on to a string.


Str() Syntax


syntax(argument)


The argument can be a integer, floating point number, list, tuple, dictionary, file, and so on.  The argument will be converted to a string.


str() Built-in Function Examples


#Str() Built-in Function

>>> str(6)
'6'
>>> str(7.6)
'7.6'
>>> str((6,75,9))
'(6, 75, 9)'
>>> str('cat': 'mary', 'dog': 'maggie')
"'cat': 'mary', 'dog': 'maggie'"

If you have any questions about the str() built-in function leave a comment below and we will do our best to assist you.


float() - Python Tutorial

float() built-in function in python



 


Float() Built-in Function In Python


The float() built-in function converts integers and strings to floating point numbers.  This basic function simply just changes the type of object to a floating point number type in Python.


Float() Syntax


float(argument)


The argument can be a integer or string.  You can also include a float but it will do nothing to the floating point number. If you call the float() function on a integer the when be convert to float which it will contain a decimal and a zero.


Float() Examples


#float examples

>>> float(1)
1.0
>>> float("6")
6.0
>>> float("5.6")
5.6

If you have any questions about the float() built-in function leave a comment below and we will assist you.


 



Wednesday, March 25, 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.



int() - Python Tutorial

int() in pythonint() Python Built-in Function


int() is a built-in function that will convert a floating point number or string to an integer type. If a user or our program returns a string or a float we can use the int() function to convert the number to integer. The int() function rounds the float down to the floor check the examples below.


int() Built-in Function Example


#int() Examples

#int() example
>>> int(8.7)
8

#int() example
>>> int(9.876)
9

#int() example
>>> int(5.3)
5

#int() example
>>> int(6)
6

#int() example
>>> int("5677")
5677

#This does not work we can not convert a float string but check next example
>>> int("5.98")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.98'

#The fix to above example
>>> int(float("5.98"))
5

If you have any questions about int() built-in function leave a comment below.


 



Python Tutorial: How To Convert Number Types In Python - Python Numbers #35

How to Convert Number Types in Python - Python Numbers - Python Tutorial

How to Convert Number Types in PythonHow To Convert Number Types in Python


In this Python tutorial, we are going to explore how to convert number types in Python. When coding sometimes we need in order to convert our current integer to a float or our current float to integer. We can also convert strings to either integers or floating point numbers.  Python has a built-in function that will give us the ability to do this.


Int() Built-in Function


The int() built-in function gives the ability to convert either a floating point number to an integer or convert a string to an integer. The int() function will always round down when converting floating point numbers. We also cannot convert floating point number strings to integers but we can do it we will look at that later in this tutorial. Let’s take a closer look at some int() examples.


#int() built-in function

#convert floats to integers
>>> int(4.5)
4
>>> int(1.45643)
1

#convert string integers to integers
>>> int("5")
5
>>> int("9")
9


Float() Built-in Function


The float() built-in function gives us the ability to convert integers to floating point numbers and convert strings to floating point numbers let’s take a closer look at this example.


#float() built-in function

#Convert integer to float
>>> float(6)
6.0

#convert integer to float
>>> float(-78)
-78.0

#convert integer in a string to a floating point number
>>> float("5")
5.0

#convert a floating point number string to a actual floating point number
>>> float("6.7")
6.7

Converting a String Floating Point Number To A Real Integer


#just using int will not work
>>> int("6.7")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '6.7'

#first convert to float then to integer
>>> int(float("6.7"))
6

Checking The Type Of An Object


We can also use the type() built-in function to check the type of an object.


#type()

>>> type(6)
<class 'int'>
>>> type(())
<class 'tuple'>
>>> type(7.6)
<class 'float'>
>>> type("")
<class 'str'>

Conclusion


 


In this Python tutorial, we took a look at How to Convert Number Types in Python. These built-in functions help us with our code so we do not have to build our own function to convert the number types. If you have any questions about this tutorial please leave a comment below.



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.



Python Tutorial: Manually Adjust Operator Precedence - Python Numbers #34

Manually Adjust The Operator Precedence - Python Numbers - Python Tutorial

Manually Adjust the Operator PrecedenceManually Adjust The Operator Precedence


In the previous Python tutorial, we took a look at how Python evaluates equations using the operator precedence. In this Python tutorial, we are going to throw out all the information you learned in the previous tutorial and show you how you can control the operator precedence with parentheses in your equations.


Python will evaluate parentheses first then default to the operator precedence. This gives us the ability to adjust how Python will run an equation and gives us more control over our mathematical equations in our programs.


The Operator Precedence


A little review how the operator precedence is evaluated in Python.


  1. **

  2. *, /, %, //

  3. +, -

In the default operator precedence exponent(**) will always run before any other operator.  Then multiplication(*), true division(/), modulo(%), and floor division(//) will run after the exponent(**).  Then finally addition(+) and subtraction(-) will run.


If an equation contains operators in the precedence like addition(+) and subtraction(-) then the equation will run left to right.


Manually Adjust The Operator Precedence


With Python we have the ability to manually adjust the operator precedence using parentheses which Python will run first then go to the default operator precedence after running the equation in the parentheses. This option gives us more control over our code and helps control flow of our math equations.


Manually Adjust The Operator Precedence Examples


#Manually Adjust The Operator Precedence Examples

#Default Operator Precedence Exponent first
>>> 2 ** 2 + 2
6

#Still runs exponent first
>>> 2 + 2 ** 2
6

#runs addition
>>> (2 + 2) ** 2
16

#runs left to right
>>> 3 * 8 / 2
12.0

#runs division first
>>> 3 * (8 / 2)
12.0

#runs division first
>>> 6 * (7 / 4)
10.5

#test the equation
>>> 7/4
1.75

#test the equation
>>> 1.75 * 6
10.5

#Python runs multiplication first
>>> 6 + 5 - 3 + 4 * 10
48

#Python runs addition and subtraction first
>>> (6 + 5 - 3 +4) * 10
120

Conclusion 


In this tutorial, we learned how to Manually Adjust the Operator Precedence which gives us more control over our code and gives the flexibility to write quality programs. It is important to know that Python will default to its operator precedence after running the parentheses.


If you have any questions leave a comment below and we will do our best to help you out.


 


 



Tuesday, March 24, 2015

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!



round() - Python Tutorial


round() is a build-in function in the Python Programming Language which gives us the ability to round a floating point number to the closest multiple of 10. It is important to understand that round() function takes a floating point number which has been convert from a fraction so sometimes the round() may return some numbers a different than you expect.


round() Syntax


round(floating point number, numbers after the decimal)


Round() only takes floating point numbers which is our first argument and the second argument is how many numbers positions do you want after the decimal point. If you do not provide a second argument python will return a integer type number as the default.


round() Examples


#round() Examples

#round() with no second argument
>>> round(1.7)
2

#round() with an second argument of 1
>>> round(1.76, 1)
1.8

#round() example with an second argument of 4
>>> round(1.56787, 4)
1.5679

Weird Round() Returns


round(0.5) – returns 0 but we would expect this to return 1


round(2.675, 2) - returns 2.67 but in reality it should be 2.68.  Python returns 2.67 because this number is convert to a fraction and then converted back from a fraction and the conversion is not exact the actual return for 2.67 is 2.67499999999999982236431605997495353221893310546875



deallocation - Python Tutorial

Deallocation is the process Python uses to remove reserved memory. This process is done by Python’s memory management process.



allocation - Python Tutorial

Allocation is how Python distributes space for memory in Python programs.  Allocation is part of the Python memory management process.



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.


 



Monday, March 23, 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.