Python Programming/Basic Math

From testwiki
Jump to navigation Jump to search

Template:Python Programming/TopNav

Now that we know how to work with numbers and strings, let's write a program that might actually be useful! Let's say you want to find out how much you weigh in stone. A concise program can make short work of this task. Since a stone is 14 pounds, and there are about 2.2 pounds in a kilogram, the following formula should do the trick:

mstone=mkg×2.214

So, let's turn this formula into a program!

print "What is your mass in kilograms?",
mass_kg = int(raw_input())
mass_stone = mass_kg * 2.2 / 14
print "You weigh " + str(mass_stone) + " stone."

Run this program and get your weight in stone! Notice that applying the formula was as simple as putting in a few mathematical statements:

mass_stone = mass_kg * 2.2 / 14

Mathematical Operators

Here are some commonly used mathematical operators

Syntax Math Operation Name
a+b a+b addition
a-b ab subtraction
a*b a×b multiplication
a/b a÷b division
a%b amodb modulo
-a a negation
abs(a) |a| absolute value
a**b ab exponent
sqrt(a) a square root

Note: in order to use the sqrt() function, you must explicitly tell Python that you want it to load this function. To do that, write

from math import sqrt

at the top of your file.

Formatting output

Wouldn't it be nice if we always worked with nice round numbers while doing math? Unfortunately, the real world is not quite so neat and tidy as we would like it to be. Sometimes, we end up with long, ugly numbers like the following:

What is your mass in kilograms? 65
You weigh 10.2142857143 stone.

By default, Python's print statement prints numbers to 10 significant figures. But what if you only want one or two? We can use the round() function, which rounds a number to the number of decimal points you choose. round() takes two arguments: the number you want to round, and the number of decimal places to round it to. For example:

>>> print round(3.14159265, 2)
3.14

Now, let's change our program to only print the result to two significant figures.

print "You weigh " + str(round(mass_stone, 2)) + " stone."

This also demonstrates the concept of nesting functions. As you can see, you can place one function inside another function, and everything will still work exactly the way you would expect. If you don't like this, you can always use multiple variables, instead:

twoSigFigs = round(mass_stone, 2)
numToString = str(twoSigFigs)
print "You weigh " + numToString + " stone."

Template:Python Programming/Navigation