ALGEBRA  QUIZZES  AND  ILLUSTRATIVE  COMPUTER  CODE     

Python-1

Click (below) and watch a Python program solve this equation:

$$\begin{equation} 3x+6=24 \end{equation}$$

Here's the code

Python code Comments
   
 1   right_side = 24 # Creates a variable named 'right_side' and initializes it with the value of the right side of the equation (24).
 2   left_side = 0 # Creates a variable named 'left_side' and initializes it with the value 0.
 3   for x in range(1, 30): # The for keyword starts a loop that runs from x=1 to x=30. Python keywords are printed in bold type.
 4       left_side = 3*x+6 # Computes the left side of the equation (3x+6) using the current value of x, and updates the value of 'left_side'.
 5       if left_side == right_side: # The if block uses == to check if both sides are equal yet. If yes, proceed to the next line. Otherwise, continue.
 6          print "Answer: ", x # If left_side = right_side (the if statement was true), that means we found the answer and we'll print it out here.
 7          break # Breaks out of the enclosing for loop. (Without this statement, the loop would continue running up to 30.)
   

Try it yourself. It's easy!

Python is a popular programming language that can be used to solve math problems and so much more1. Python is also taught at top universities as a first programming language. Python is free to download2 and install on your own computer (recommended), and there are several ways to learn3 Python on your own.

In this example, we are going to enter and run the above computer program (Python code) in Philip Guo's excellent visualizer, Online Python Tutor. Once you get the hang of it, you'll be able to create and visualize your own programs! So let's get started.

The algorithm we'll be using is called exhaustive search. Here's how it works: One-by-one, we'll plug a series of different values into x and check to see if that particular value makes both sides of the equation equal. If it does, then that value of x is a solution to the equation (it makes both sides equal), and we'll print the answer.

Notice that exhaustive search just checks all possible solutions within our specified range of 1-30 (line 3 above); it doesn't use any tricks to reduce the number of guesses needed. But since computers can make millions of guesses per second, exhaustive search is actually a pretty good algorithm for many applications. In future examples, we'll look at other algorithms that do use tricks to cut down on the number of guesses and the time it takes. Reducing processing time is especially important in programs that crunch big data sets, such as weather forecasting, problems in science and engineering, and heck, even some areas of biology. (Actually, computing is used almost everywhere today, so having some knowledge of it is bound to come in handy. And did you know that software developers are among the most in-demand and highly-paid people today?)

So let's take a look at the code:

Lines 1 and 2 create two variables named right_side and left_side. These variables contain the values of the righthand side of the equation and the lefthand side. (Later on line 5 we will use the comparison operator (==) to check if these two quantites are equal or not.)

Line 3 has a for loop which is the perfect control flow structure for looping over a range of numbers. Control flow structures guide how the program flows from one statement to another; the flow can branch one way or another depending on comparisons.

  • In a for loop, you have to specify two things: a variable name, and a range.
  • We picked 'x' for the variable name because x is the variable we used in the equation we are trying to solve (at the top of the page).
  • The range we specified is (1, 30). We picked 1-30 because we think the answer is contained somewhere in that range. The range tells the for loop what numbers to plug into x. For each number in the range, the for loop executes all the indented lines of code nested below itself (lines 4-7). For example, it first makes x=1, then executes all the indented statements below until it hits the if statement on line 5. From there it either continues to line 6 if the if condition is true, or it goes back to line 3 and assigns x the next value (2) if the if condition is false, where it repeats the loop.
Line 4 is where it solves the lefthand side of the equation using the current value of x.

Line 5 is where it checks to see if the lefthand side equals the righthand side.

Now going back to line 3, the for loop will repeat the above steps until one of the following events occurs:

  • It either finds the answer (line 5 is true), prints it out (line 6), then exits (line 7). (The double-equal sign == tests whether it's true that the left side equals the right side. If it is true, line 6 is executed next. If not, control goes back up to the for and the value of x is incremented by 1.)
  • Or, it can't find the answer (line 5 is never true) and has exhausted all the numbers in its range and exits the loop (but not by reaching line 7). It would then begin executing a statement on line 8. (If it's never true, it's because the answer is not contained in the range we specified. For example, if we had specified the range to be (1, 5), it will never find the answer, because the answer is 6--outside the range. Or, if the answer was actually 6.5, it still wouldn't find it because our range is the integers) between 1-30.)
We're almost ready to enter the code into the Online Python tutor, but first a word about paying close attention to detail:

Computers do exactly what they're told. If you're code is correct, you'll get a correct answer. If your code is wrong, however, you'll either an error message3 and your program won't run, or you'll get the wrong answer. To avoid syntax errors that can prevent your program from running, study each line of code carefully. In the Online Python Tutor simulator, you'll see a red X next to lines that contain syntax errors. For example, if you forget a colon (:), that is a syntax error and your program won't run. Or, if you don't indent when you should, that's also an error and your program won't run. Logical errors (bugs) can be harder to detect. There will be no red X and your program will run, but your answer will be wrong. One common error is using the assignment operator (=) when you should be using the equality operator (==), which is used to test for a true or false condition. Another common error is not using parenthesis properly when grouping your terms. Example: the solution to 3x+6=24 is different than the solution to 3(x+6)=24.

Ok, let's copy the program to the Online Python Tutor and run it:

  • Write the Python program down on a separate sheet of paper exactly as it appears above on lines 1-7, including indentations.
  • Open a new browser tab and copy-and-paste this web address: http://www.pythontutor.com/visualize.html#mode=edit
    (Then press Enter to actually go there.) You can switch back to this page as needed.
  • Click inside the box and start typing your program line-by-line. When you indent, use 4 spaces. (If it indents automatically, don't indent again. Python is one of the only programming languages that requires you to indent, which is good programming practice. But remember to be consistent in the number of spaces used.) Press Enter at the end of each line. Notice that on line 3 (after you typed-in while x < 30), the next line indents automatically. (If you copied-and-pasted from the example instead of typing it in, the indentation might be wrong, causing an error.)
  • After you've entered the last line and pressed the Enter key, click the Visualize Execution button. If there were no mistakes, your code will move into a box to the left and a red arrow will point to the first line. (If that didn't happen, start debugging!)
  • Click the Forward> button and watch your variables change in the blue box to the right as the arrow traces out the execution of your program. Your final answer will appear in the Program output box $tempAns.
  • Congratulations! You've just written your first Python program. :-)


Footnotes


1 Besides being used by YouTube!, Google, and Dropbox, Python is widely used in the sciences and engineering, and in the business world. Python is also used to build websites, create games, and code hobby projects using the Raspberry Pi. (Here are some example Raspberry Pi projects: PC World, Instructables. The Raspberry Pi runs on various flavors of Linux and comes pre-installed with Python, Scratch, and much more.)

2 You can download Python to your own computer for free here. Or, you can install Anaconda from here and get Python, Sympy, plus 195 other packages for science, engineering, and data analysis, for free. Ask for help if you need it.

3 There are several ways to learn Python on your own: (1) The official tutorial for Python version 2.7 is here, and the official tutorial for Python version 3.x is here. The difference between versions is explained here. (2) Some Python books are here. (3) Some online Python courses: codeacademy, coursera, edx, udacity.

4 If you make an error, the Traceback error message provides pretty good clues as to what went wrong.