Τρίτη 27 Νοεμβρίου 2012

Πως δουλεύουν οι μαθηματικοί τελεστές στην Python

Math in Python
Now try typing the stuff in bold. You should get the output shown in blue. I’ve given explainations in brackets.


Code Example 2 – Maths
>>> 1 + 1
2

>>> 20+80
100
>>> 18294+449566
467860
(These are additions)
>>> 6-5
1
(Subtraction)
>>> 2*5
10
(Multiply, rabbits!)
>>> 5**2
25
(Exponentials e.g. this one is 5 squared)

>>> print "1 + 2 is an addition"
1 + 2 is an addition
(the print statement, which writes something onscreen)
>>> print "one kilobyte is 2^10 bytes, or", 2**10, "bytes"
one kilobyte is 2^10 bytes, or 1024 bytes
(you can print sums and variables in a sentence.
 The commas seperating each section are a way of
 seperating clearly different things that you are printing)

>>> 21/3
7
>>> 23/3
7
>>> 23.0/3.0
7.6666...
(division, 2nd time ignoring remainder/decimals,
 3rd time including decimals)
>>> 23%3
2
>>> 49%10
9
(the remainder from a division)
As you see, there is the code, then the result of that code. I then explain them in brackets. These are the basic commands of python, and what they do. Here is a table to clarify them (because tables look cool, and make you feel smarter ;) ):
Table 1 – Python operators
commandnameexampleoutput
+Addition4+59
-Subtraction8-53
*Multiplication4*520
/Division19/36
%Remainder19%35
**Exponent2**416

Remember that thing called order of operation that they taught in maths? Well, it applies in python, too. Here it is, if you need reminding:
  1. parentheses ()
  2. exponents **
  3. multiplication *, division \, and remainder %
  4. addition + and subtraction -

Order of Operations

Here are some examples that you might want to try, if you’re rusty on this:
Code Example 3 – Order of Operations
>>> 1 + 2 * 3
7
>>> (1 + 2) * 3
9
In the first example, the computer calculates 2 * 3 first, then adds 1 to it. This is because multiplication has the higher priority (at 3) and addition is below that (at lowly 4).
In the second example, the computer calculates 1 + 2 first, then multiplies it by 3. This is because parentheses (brackets, like the ones that are surrounding this interluding text ;) ) have the higher priority (at 1) and addition comes in later than that.
Also remember that the math is calculated from left to right, UNLESS you put in parentheses. The innermost parentheses are calculated first. Watch these examples:
Code Example 4 – Parentheses
>>> 4 - 40 - 3
-39
>>> 4 - (40 - 3)
-33
In the first example, 4 -40 is calculated,then – 3 is done.
In the second example, 40 – 3 is calculated, then it is subtracted from 4.

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου