Python-Ref > Basic usage > Functions > Why functions?
 
 

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

Why functions?

Code sample without functions..
Expand/Shrink
Zdroj: (func8-1.py)
  1   a = [1.3, 3.4, 5.6, 0.7, 10, 2.4]
  2   result = 1
  3   for x in a:
  4     result = result * x
  5   print result**(1.0 / len( a))
  6   
  7   b = [3, 4, 5, 7, 10, 8]
  8   result = 1
  9   for x in b:
 10     result = result * x
 11   print result**(1.0 / len( b))
 12   
 13   c = [3.2, 13.4, 5.2, 4.7, 0.4, 1.4]
 14   result = 1
 15   for x in c:
 16     result = result * x
 17   print result**(1.0 / len( c))
stdout:
2.73203712357
5.6805433649
2.89350342572
Doba běhu: 21.0 ms
..and with them.
Expand/Shrink
Zdroj: (func8-2.py)
  1   def geometric_mean( xs):
  2     result = 1
  3     for x in xs:
  4       result = result * x
  5     return result**(1.0 / len( xs))
  6   
  7   a = [1.3, 3.4, 5.6, 0.7, 10, 2.4]
  8   print geometric_mean( a)
  9   
 10   b = [3, 4, 5, 7, 10, 8]
 11   print geometric_mean( b)
 12   
 13   c = [3.2, 13.4, 5.2, 4.7, 0.4, 1.4]
 14   print geometric_mean( c)
stdout:
2.73203712357
5.6805433649
2.89350342572
Doba běhu: 18.8 ms