Friday, April 3, 2015

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.



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.


 


 



Thursday, April 2, 2015

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.



Wednesday, April 1, 2015

allocation - Python Tutorial

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



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.



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.