Python: Functions and parameters


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. ## Functions are objects in the Python language and the parameters that are passed are really "applied" to the function object.
  2. To create a function, use the def functionname(parameters): statement, and then define the function in the following code block. Once the function has been defined, you can call it by specifying the function name and passing the appropriate parameters.
  3.  
  4. def fun(name, location, year=2006):
  5. print "%s/%s/%d" % (name, location, year)
  6.  
  7.  
  8. ## The first example shows the function being called by passing the parameter values in order. Notice that the year parameter has a default value set in the function definition, which means that this parameter can be omitted and the default value will be used.
  9.  
  10. >>>fun("Teag", "San Diego")
  11. Teag/San Diego/2006
  12.  
  13. ## The next example shows passing the parameters by name. The advantage of passing parameters by name is that the order in which they appear in the parameter list does not matter.
  14.  
  15. >>>fun(location="L.A.", year=2004, name="Caleb" )
  16. Caleb/L.A./2004
  17.  
  18. ## This example illustrates the ability to mix different methods of passing the parameters. In the example, the first parameter is passed as a value, and the second and third are passed as an assignment.
  19.  
  20. >>>fun("Aedan", year=2005, location="London")
  21. Aedan/London/2005
  22.  
  23. ## Parameters can also be passed as a tuple using the * syntax, as shown in this example. The items in the tuple must match the parameters that are expected by the function.
  24.  
  25. >>>tuple = ("DaNae", "Paris", 2003)
  26. >>>fun(*tuple)
  27. DaNae/Paris/2003
  28.  
  29. ## Parameters can also be passed as a dictionary using the ** syntax, as shown in this example. The entries in the dictionary must match the parameters that are expected by the function.
  30.  
  31. >>>dictionary = {'name':'Brendan',
  32. 'location':'Orlando', 'year':1999}
  33. >>>fun(**dictionary)
  34. Brendan/Orlando/1999

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.