a = 23 b = -23 if a < 0: a = -a if b < 0: b = -b if a == b: print "The absolute values of", a,"and",b,"are equal" else: print "The absolute values of a and b are different"
The absolute values of 23 and 23 are equal
a = 23 b = -23 def abs(num): if num < 0: num = -num return num if abs(a) == abs(b): print "The absolute values of", a,"and",b,"are equal" else: print "The absolute values of a and b are different"
The absolute values of 23 and -23 are equal
Notice how the values of a and b are not changed. Functions of course can be used to repeat tasks that don't return values. Here's some examples:
def hello(): print "Hello" def area(width,height): return width*height def print_welcome(name): print "Welcome",name hello() hello() print_welcome("Fred") w = 4 h = 5 print "width =",w,"height =",h,"area =",area(w,h)
Hello Hello Welcome Fred width = 4 height = 5 area = 20
Functions can be used to eliminate repeat code.