Python-Ref > Basic usage > Functions > Creating functions
 
 

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

Creating functions

The ability to create functions is of highest importance once you need to create bigger than the smallest programs. It helps you organize your code and reinvent the wheel.
Function is defined using the def keyword.
Expand/Shrink
Zdroj: (func3-1.py)
  1   def second_power( x):   # definition of function second_power
  2       return x*x          # the result of this function is returned
  3   
  4   print second_power( 6)
  5   print second_power( -3567)
stdout:
36
12723489
Doba běhu: 21.0 ms
In the brackets after the name of function arguments are given. These are the names of variables that will be filled when the function is called.
Functions most usually return some value as a result of their application on the arguments. For this the keyword return is used. After this keyword the execution of a function is ended and the value given to return is given as the result of the function.
Expand/Shrink
Zdroj: (func3-2.py)
  1   def second_power( x):   # definition of function second_power
  2       return x*x          # the result of this function is returned
  3       print "This will never print"
  4   
  5   
  6   print second_power( 6)
  7   print second_power( -3567)
stdout:
36
12723489
Doba běhu: 20.9 ms
If the return keyword is not present, the return value of a function is None.
The return value does not have to be captured by your program at all. It may be just thrown away.
Expand/Shrink
Zdroj: (func3-3.py)
  1   def welcome( name):
  2       print "Welcome, "+name+"."
  3   
  4   
  5   x = welcome( "Trillian")   # 'x' stores the return value of 'welcome'
  6   print x                    # print 'x'
  7   
  8   welcome( "Arthur")         # the value does not have to be stored at all
  9   
 10   range( 10)   # even the result that is not None might be thrown away
 11                # however the decision to do so is questionable
 12   
stdout:
Welcome, Trillian.
None
Welcome, Arthur.
Doba běhu: 21.3 ms
It is possible (and useful) to supply some description of a function just below its header. This description is a string, usually given insite triple double-quotes so that it can span over more than one line.
Expand/Shrink
Zdroj: (func3-4.py)
  1   def do_nothing( x):
  2       """
  3       this function does nothing special,
  4       it just demonstrates the possibility for
  5       documentation string as part of the function
  6       definition
  7       """
  8       return x
  9   
 10   print do_nothing( 10)
 11   # this prints the documentation string of the function
 12   print do_nothing.__doc__
stdout:
10

    this function does nothing special,
    it just demonstrates the possibility for
    documentation string as part of the function
    definition
    
Doba běhu: 13.8 ms