Social Media

2/04/2019

Functions Introduction

Function is actually a block of code.
It increases the reusability of code in our script or program.
The syntax for function in the python language is as:
def f1():
    statement 1
    statement 2
A function can take any number of arguments.

Example1: Write an script to multiply two  numbers entered by the user.
def multiply(n1,n2):
    print("The multiplication is ",n1*n2)

a,b=int(input("enter first number")), int(input("Enter second number"))

multiply(a,b)

A function can also return any kind of data, means it can be used to return an integer, string, list tuple etc.

Example2: Write an script which return the factorial of a given number.
def fact(n):
    s=1
    while n!=1:
        s=s*n
        n-=1
    return s

x=int(input("Enter the number "))
f=fact(x)
print("factorial is",f)

Note* If a function does not return anything in python then it will automatically return None.


Be First to Post Comment !
Post a Comment