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:
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:
Here are some examples on functions:
Creating a simple function.
def say_hello(): print("Hello") say_hello()
Passing value to function.
def square(x): print("Square of %d is %d" % (x, x*x)) square(5)
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)
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)))
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))))
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)))
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))