So now that you know how to generate output, let's generate some output that is a little harder to predict. Let's do some math!

The field of scientific computing concerns itself almost solely with this problem, so obviously we will just be skimming the surface. Computer math, like all math, is easy to start learning, but can go amazing places. We'll start with some basics. The program below shouldn't be too hard to figure out, but you should run it yourself, anyway.

print 3
print 3+3
print 3*3
print 3/3
print 3-3
print ((3+3)*(3*3)/(3/3))-(3-3)+3
print 3+3*3*3/3/3-3-3+3
print 3**3
After inputting and running it, you should see the following:
Programming languages, having been designed by mathematicians, and engineers, follow the same precedence rules as the math you were taught as a child. First, do everything in parentheses, then all of the exponentiation (the ** stuff), then all the multiplication and division, then all the addition and subtraction..

This means that you can use your newfound programming skills as a crude calculator. But wait! Now your programs can be more useful. You can now convert from Celsius to Farenheit! Make a program that has as its one line: print (98.6-32)*5/9. That program will now print out what the average person's body temperature is in Celsius. Something that I, at least, can never remember, and always have to recalculate.

Because computers work in binary with a finite number of digits, they work best with integers. Any time you involve floating point numbers (numbers whose decimal representation involves a decimal point) you should be careful of the fact that there is going to be a loss of precision in the final few decimal points. This can bite you in many ways, but the most comman thing is adding a number that is too small to a number that is too large. Try print 1 + .0000000000000000001. It will print out 1. Working with/around this limitation is one of the prime occupations of people who practice numerical analysis. Unless you are doing something like writing a gravity simulator (a good way to get extra credit in your Physics class!) you shouldn't have to worry about this, though. But if it bites you in the butt, don't say I didn't warn you.

Also due to a computer's binary nature, they have an built in mathematical operation that you probably learned in the fourth grade and promptly forgot: modulus (aka remainder or mod). % will cause your computer to find the remainder. print 5 % 3 will print out 2, as will print 11 % 3 or print 3002 % 3. Modulus comes up a lot more than you would initially suspect, so just be aware of its existence so that you can avoid reinventing the wheel.

Now play around! Screw up and have fun. When you are done, proceed to the next lesson.

<< | Learn to Program | >>

Log in or register to write something here or to contact authors.