Python-Ref > Basic usage > Operators > Mathematical operators
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

Mathematical operators

+, -, / and other operators.
Basic Mathematical operators are used to carry out mathematical operations. They are used in much the same way as one is used to.
Expand/Shrink
Zdroj: (operators1-1.py)
  1   print 3 + 3
  2   print 7 * 6
  3   print 32 - 26 * 2    # the precedence of operators is as expected
  4   print (3.5+2) / (46.7-29)
  5   print 4**3           # the power operator **
  6   print 1.27**3.14     # the same with float values
  7   print 25 % 4         # modulo, the remainder of integer division
stdout:
6
42
-20
0.310734463277
64
2.11808645916
1
Doba běhu: 20.9 ms
Brackets may be used to group together operations and change the default precedence of operators.
The only exception to this rule is the division of integers. In python versions 2.4 and below, the result of such a division is also an integer, not a float as one would expect.
Expand/Shrink
Zdroj: (operators1-2.py)
  1   print 4 / 3       # integer / integer = integer
  2   print 4.0 / 3     # float / integer = float
  3   print 4 / 3.0     # integer / float = float
  4   print 4.0 / 3.0   # float / float = float
stdout:
1
1.33333333333
1.33333333333
1.33333333333
Doba běhu: 21.4 ms
To get around this problem, at least one of the operands has to be float. To accomplish this, one can multiply one of the operands by 1.0.
Because this function of the / operator will be changed in new versions of Python, the operator // is provided for integer division.
Expand/Shrink
Zdroj: (operators1-3.py)
  1   print 1 / 2
  2   print 1.0 / 2.0
  3   print 1 // 2
  4   print 1.0 // 2.0   # integer division works even for floats
stdout:
0
0.5
0
0.0
Doba běhu: 21.2 ms
Of course, the operators work the same way with variables as with numbers.
Expand/Shrink
Zdroj: (operators1-4.py)
  1   x = 2.4
  2   y = 3.5
  3   i = 5
  4   j = 7
  5   
  6   print x / y
  7   print i / j
  8   print 1.0*i / j
  9   print (x+y) / i / j
 10   print (j * x) / (i * y)
stdout:
0.685714285714
0
0.714285714286
0.168571428571
0.96
Doba běhu: 21.0 ms