Functions are named block of code that can be used anywhere any number of times in the program. It allow us to re-use the code instead of writing the code again and again.
To define a function, we write:
Syntax:
def function_name: statement_1 statement_2
Here is an example:
def say_hello(): print("Hello")
Now, to call this function, we can simply write:
say_hello()
Here are some examples on functions:
Example 1
Creating a simple function.
def say_hello(): print("Hello") say_hello()
Example 2
Passing value to function.
def square(x): print("Square of %d is %d" % (x, x*x)) square(5)
Example 3
Returning value from function.
def find_big(x,y): return x if x>y else y big = find_big(7,5) print("The bigger number is " , big)
Example 4
Loop inside function.
def factorial(x): fact = 1 for i in range(1,x+1): fact *= i return fact x = 5 print("Factorial of %d is %d" % (x, factorial(x)))
Example 5
Passing a function into another function call.
def square(x): return x*x def find_big(x,y): return x if x>y else y a,b = 7,5 print("The square of bigger number between %d and %d is %d" % (a,b,square(find_big(a,b))))
Example 6
Recursive function.
def factorial(x): if x>1: return x * factorial(x-1) else: return 1 x = 5 print("Factorial of %d is %d" % (x, factorial(x)))
Example 7
Returning multiple values from function.
def numbers(): return (4,5) x,y = numbers() print("Sum of %d and %d is %d" % (x,y, x+y))