Implementing the Quadratic Formula

Introduction

We have been working with input/output and decision making.  We’re now ready to tackle a problem that we first discussed last week, the Quadratic Formula.

quadraticformula

Our program will accept values of a, b, and c (the coefficients of a quadratic equation) and use the quadratic formula to find the solutions. Below is pseudocode that will implement our plan for the quadratic formula program.  Your job is to translate it to Python and get it working.

import math module # We need math for the sqrt function

Ask user to enter the value of a
Ask user to enter the value of b
Ask user to enter the value of c

if discriminant is > 0:
    Tell the user that there are two solutions.
    x1 = first solution # use a + sign
    x2 = second solution # use a - sign
    Show the two solutions

elif discriminant is = 0:
    Tell the user that there is one solution.
    x1 = first solution # use a + sign
    Show the solution.

else:
    Tell the user that there is no solution.

Done.

The output of your program should look something like this:

This program will use the quadratic formula to find the solutions
to a quadratic equation of the form ax^2 + bx + c = 0.

Please enter the value of coefficitent a: 1
Please enter the value of coefficitent b: 9
Please enter the value of coefficitent c: 20

There are two solutions:
x = -4.0 and x = -5.0.
Done.

Be sure to save the file AS yourname-quadraticforumla.py. You can email the file to me when it is completed.

When You Finish

If you have time, let’s do something that you might consider fun.  Let’s check out some games that are written in Python.  First, please check out the Tic Tac Toe game found at this link:

http://code.activestate.com/recipes/578563-tic-tac-toe-console-game/

Copy the code in the long  gray box and paste it into a Python file.  Save it AS yourname-tictactoe.py and then play a few games.  The developer claims the game cannot be beat.  Can you beat it?

If losing to the computer is too frustrating, check out the Tetris game discussed at the website below.  I believe that our installation of Python will be able to run this program.

Website: http://code.google.com/p/tetris-tk/

Download the file to your H: drive: tetris_tk.py

When you download the file, be sure to put it in a familiar place so you will be able to open the file in Idle.  Get it running and enjoy the game.  Then, take a moment to look over the code.  Look for statements that look familiar.  Eventually, we will come to understand most of the code used for the game, but it may take some time.