Built-in Functions
As
with other languages, Python uses functions to improve the program structurally
and to remove duplicate code. Python supports a variety of built-in functions
that can be used by including a function call or importing a module. The
“print” function is used most frequently and can be used without import statements,
but mathematical functions can only be used after importing the “math” module.
import math print “value of cos 30:”, math.cos(30) >>>>>cos value of 30: 0.154251449888 |
1.3.2
User-defined Functions
It is possible to define
functions to improve the program structure at the user level. The most typical
grammar to use as a reserved word is “def”. “def” explicitly defines functions,
and the function name and arguments then follow. It is therefore possible to specify
the default values behind an argument.
def function(argument 1, argument 2=default value) |
Let's change the
Example 1-1 by using the user-defined function.
#story of "hong gil dong" skill =
["sword","spear","bow","axe"] power = [98.5, 89.2, 100, 79.2] #start of function def printItem(inSkill, idx=0): #(1) name = "Hong Gil
Dong" age = 18 weight = 69.3 print "\n" print
"----------------------------------------" print "1.name:",
name print "2.age:",
age print "3.weight:",
weight print "4.armed
weapon:",inSkill, "[ power", power[idx],"]" print ">>>i am
ready to fight" #end of function querySkill = raw_input("select weapon: ") i=0 for each_item in skill: if(each_item == querySkill): printItem(querySkill,
i) #(2) i = i+1 print "----------------------------------------" print "\n" |
Example 1-2 User-defined
Functions
(1) Function declaration: Declare
the “printItem” function that prints the value of the “power” list at a
position corresponding to “inSkill” and “idx” received as an argument
(2) Calling User-Defined
Functions: To
perform a function, an index value for the “querySkill” value is passed, and
the “skill” list that is received on the user input matches as the function of
an argument
Since the default value is
declared in the second argument “idx” of the “printItem” function, the function
can be called without error even when passing only one argument at the time of
the function call.
printItem(“sword”, 1) printItem(“sword”) printItem(“sword”, i=0) |