Sunday, May 8, 2016

Middle School Python

This past week my son was working on calculating the percent increase or decrease between a beginning and an ending value. He had written out the formula a bunch of times:

percent = (ending - beginning) / beginning * 100

Then he dutifully plugged in the values and if he didn't make any careless mistakes, he'd get the answer. I saw so much repetition that I offered to help him automate the process.

The above formula is perfect for putting straight into Python. Then all we need from the user is the beginning value and the ending value. Sounds like the parameters of a function:

def perc(beginning, ending):
    '''prints the percent increase or decrease between
    a given beginning value and ending value.'''
    percent = (ending - beginning) / beginning * 100
    return percent

This will give us a positive or negative number, but it might be a long decimal. We can make it round off to two decimal places by replacing the last line with this:

return round(percent,2)

So if it's positive, it's an increase and it it's negative it's a decrease. We might make it more user friendly by asking the user for input:

beginning = float(input("Enter the beginning value: "))
ending = float(input("Enter the ending value: "))

In Python, user input is assumed to be a string. "Float" changes it into a decimal. But now you have to change the "return" statement to a "print" statement:

print(round(percent,2))

So the output looks like this:

Enter the beginning value: 115
Enter the ending value: 73
-36.52

That might be enough, but for some students adding "percent" and "increase" or "decrease" might be helpful.

if ending - beginning > 0:
    change = 'increase'
else:
    change = 'decrease'
print(round(percent,2),"%",change)

Now the output is more descriptive.

Enter the beginning value: 21
Enter the ending value: 23
9.52 % increase

Not every Python exploration has to be rocket science! This 7th-grade math problem was perfect for automating.