How do you write math equations in python?
Show So, let's turn this formula into a program! mass_kg = int(input("What is your mass in kilograms?" )) mass_stone = mass_kg * 2.2 / 14 print("You weigh", 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[edit | edit source]Here are some commonly used mathematical operators
Note: at the top of your file. For other functions made available by this statement, see here. Beware that due to the limitations of floating point arithmetic, rounding errors can cause unexpected results. For example: >>> print(0.6/0.2) 3.0 >>> print(0.6//0.2) 2.0 For the Python 2.x series, This can be fixed by putting a The operator >>> 0.6 == 0.2 * ( 0.6 // 0.2 ) + 0.6 % 0.2 True >>> 0.6 // 0.2 2.0 >>> 0.6 % 0.2 0.19999999999999996 The difference between the operations >>> print(0.6 / 0.2) 3.0 >>> 0.6 / 0.2 2.9999999999999996 >>> 2.0 + ( 0.6 % 0.2 ) / 0.2 3.0 >>> 0.6 / 0.2 == ( 0.6 // 0.2 ) + ( 0.6 % 0.2 ) / 0.2 False >>> round( 0.6 / 0.2 ) == ( 0.6 // 0.2 ) + ( 0.6 % 0.2 ) / 0.2 True Order of Operations[edit | edit source]Python uses the standard order of operations as taught in Algebra and Geometry classes at high school or secondary school. That is, mathematical expressions are evaluated in the following order (memorized by many as PEMDAS), which is also applied to parentheticals. (Note that operations which share a table row are performed from left to right. That is, a division to the left of a multiplication, with no parentheses between them, is performed before the multiplication simply because it is to the left.)
Formatting output[edit | edit source]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 (round(3.14159265, 2)) 3.14 Now, let's change our program to only print the result to two decimal places. print ("You weigh", 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.") To learn about more formatting options, see section Formatting in chapter Input and Output. Notes[edit | edit source]
Is there a math function in Python?The math module is a standard module in Python and is always available. To use mathematical functions under this module, you have to import the module using import math .
|