Wednesday, 2 August 2017

Returning a value from a python function

Python Function:

Returning a value from a function

Functions that return values are sometimes called fruitful functions. In many other languages, a function that doesn’t return a value is called a procedure, but we will stick here with the Python way of also calling it a function, or if we want to stress it, a non-fruitful function.



How do we write our own fruitful function? Let’s start by creating a very simple mathematical function that we will call square. The square function will take one number as a parameter and return the result of squaring that number. Here is the black-box diagram with the Python code following. 


def square(x):
    y = x * x
    return y

toSquare = 10
result = square(toSquare)
print "The result of " + str(toSquare) + " squared is " + str(result)


There is one more aspect of function return values that should be noted. All Python functions return the value None unless there is an explicit return statement with a value other than None. Consider the following common mistake made by beginning Python programmers. As you step through this example, pay very close attention to the return value in the local variables listing. Then look at what is printed when the function returns
  

def square(x):
    y = x * x
    print y   # Bad! should use return instead!

toSquare = 10
squareResult = square(toSquare)
print "The result of " + str(toSquare) + " squared is " + str(squareResult)



No comments:

Post a Comment