Functions: write once, use many times
A function is a named block of code that we write once and use many times. In def square(n): the name n is the parameter, a placeholder. When we call square(5), the value 5 is the argument, and n holds 5 while the function runs. The word return gives a result back to the place where the function was called, so square(5) is replaced by 25 and we can use it in a calculation, such as square(3) + 1, which is 10. A function with print but without return only shows something on the screen. It gives back the special value None. Compare r = show(4): the screen shows 16, but r holds None. A variable made inside a function, like tax inside add_tax, is local: it exists only while the function runs, and using it outside gives an error. A function can have several parameters, such as area(width, height), and the arguments are matched in order. Functions make programs shorter and let us test one small piece at a time.
1def square(n): 2 return n * n 3 4print(square(5)) 5print(square(3) + 1)
25 10
1def show(n): 2 print(n * n) 3 4r = show(4) 5print(r)
16 None
1def add_tax(price): 2 tax = price * 0.1 3 return price + tax 4 5print(add_tax(200))
220.0
1def area(width, height): 2 return width * height 3 4print(area(4, 3))
12
Write on paper a function double(n) that returns n * 2 and a function greet(name) that returns the text "Hello " followed by the name. Write the value of double(7) and of greet("Mina"). Which of your functions could you use inside a calculation, and why?