Python Open Lab October 26

This week we learned functions, which is very important for programmers. Functions are useful for procedural decomposition, maximize code reuse and minimize redundancy.
Functions should be declared like a variable before using.

def function(parameter1, parameter2…):
    do something
    return value

‘def’ is the keyword to show that we are defining a function. ‘function’ can be replaced by the function name.
An example :

def printHelloWorld():
    print(“hello world”)
    printHelloWorld()

After declaring a function, we call it when we want to use it. In the above example, we define a function called ‘printHelloWorld’ in line1 and line2. In the line3, we call it by its name.
Function parameters are values passed into the function when we call the function. By using parameters, we can introduce variables outside into the function.
 
The return value is to show the result of function to the main program. So main program assigns a task to the function and function executes the task. After the execution, function gives the result to main program.
An example of using function parameter and return(get the bigger number from two sums):

def sum(x, y):
    return float(x)+float(y)
    num1 = sum(1.0, 2.5) #num1 = 3.5
    num2 = sum(2.4, 1.6) #num2 = 4.0
    if num1 > num2:
        print(num1)
    else:
        print(num2)