Monday, May 11, 2015

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.



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.



Sunday, May 10, 2015

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

 


 



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.



Saturday, May 9, 2015

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.



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.


 



Friday, May 8, 2015

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.