Input and Output

Python Input/Output Intro


Let’s talk about some math.  Do you remember the Pythagorean Theorem or the quadratic formula?  How about the distance formula?

Math students often struggle evaluating these formulas, but computers are especially good at it, if they are programmed correctly.

Let’s look at the Pythagorean Theorem.  It states that in a right triangle, with legs a and b and hypotenuse c, a squared plus b squared = c squared.  If we know the two legs, we can find the hypotenuse.  Here is a program that takes the lengths two legs as input from the user and returns the length of the hypotenuse as output.

# Pythagorean Theorem
# This program accepts the measures of the legs of a
# right triangle from the user and computes the hypotenuse.

import math # We need this for sort

print('Hello! Below you will enter the legs of a right triangle')
print('and the length of the hypotenuse will be calculated and displayed.')

a = float(raw_input('Enter the length of leg a: '))

b = float(raw_input('Enter the length of leg b: '))

c = math.sqrt(a**2 + b**2)

print('') # Blank Line
print('The value of the hypotenuse is ' + str(c) +'.')

There are a few new functions used in this program.  First, you notice that we need to import a module called math, so we can take a square root [math.sqrt()].  The print statements display information in the screen.  The text between the ‘ ‘ marks is displayed.

The combination of float and raw_input is used to accept a number value from the user.  (What happens if the user enters a word instead?)  The str function turns numbers into text so we can display them.

Enter (or copy) the program and run it a few times (start by entering 3 for a and 4 for b).  Once you think you have it down, please write the following programs:

  1. Write another program to have the user enter the coordinates of two points in the coordinate plane, (x1, y1) and (x2, y2) and then print the distance between the points by using the distance formula.
  2. Write a program the accepts values for a, b, and c (coefficients of a quadratic equation in standard form) and uses the quadratic formula to find solutions for x. Use the discriminant to determine the number of solutions, and if there are any, print them.