How It Works
The Pythagorean distance formula is derived from the Pythagorean theorem, which I’ll have more to say about in Chapter 6. By applying this theorem, you can see that the distance between two points is equivalent to the hypotenuse of a right triangle, in which the vertical distance (v_dist) and horizontal distance (h_dist) are the two other sides.
The square of the hypotenuse is equal to the sums of the squares of the other sides. Therefore, the hypotenuse itself is equal to the square root of this sum. (See the figure.)
Remember that the exponentiation operator in Python is **. Therefore, the following
amount ** 2
means to produce the square of amount (multiply itself by itself), whereas this next expression
b ** 0.5
is equivalent to taking the square root of b. Therefore, the distance formula is
dist = (h_dist ** 2 + v_dist ** 2) ** 0.5
Exercise 3.3.1. As I just mentioned, the syntax x ** 2 translates as x to the second power, in other words, x squared. There is another, slightly more verbose, way of expressing the same operation. Revise Example 3.3 so that it uses this other means of calculating a square. Also, replace h_dist, v_dist, and dist in the program with h, v, and d. Then rerun and make sure everything works. For example, if you input the points 0, 0 and 3, 4, the program should say that the distance between the points is 5.0.
Exercise 3.3.2. Revise Example 3.3 so that it outputs the result and puts a period (.) at the end of the sentence, without any superfluous blank spaces. Use the format-specification-string technique I outlined in the previous section.
Exercise 3.3.3. Write a program that calculates the area of a triangle after prompting for the values of the triangle’s height and width. Use the formula height * width * 0.5. Use the format-specification-string technique to print a period at the end of the output.
Exercise 3.3.4. Write a program that calculates the area of a circle after prompting for the value of the radius. (I’ll leave it to you to look up the formula for area of a circle if you don’t remember it.) Use the format-specification-string technique to print a period at the end of the output. Also, to get the value of pi, place the following statement at the beginning of your program:
from math import pi
With this statement at the beginning of your program, you can use pi to refer to a good approximation of pi.