Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Python User define Function, How to create a function in the python program:-

using this we will create a set of methods to provide a proper structure to python code.

the function will subdivide the code in a single file that is easy to understand and re-use program code in the same or different file.

if we create a function-based program in python then it is called the procedural pattern of python code structure.



Syntax of function or procedure:-


def  Functionname():
     statements
     ......

Functionname()



Example of User define a function to calculate addition and subtraction:-

def addition():     #called function
    a = int(input("enter first number"))
    b = int(input("enter second number"))
    c = a+b
    print(c)

def substraction():
    a = int(input("enter first number"))
    b = int(input("enter second number"))
    c = a-b
    print(c)



    
addition()     #calling function
substraction()



Another example of a User define a function to calculate Simple Interest:-


def calculatesi():
    p = float(input("enter value for amount"))
    r = float(input("enter value for rate"))
    t = float(input("enter value for time"))
    si = (p*r*t)/100
    print("result is ",si)

calculatesi()    

Another Example of function:-


def addition(x,y):   # parametrised fuction

    print(x+y)

def substraction():    #default function

    x= int(input("Enter First Number"))

    y= int(input("Enter Second Number"))

    z = x-y

    print(z)

addition(int(input("Enter first number")),int(input("Enter Second number")))

substraction()

substraction()


Type of function:-

1)  Default or Without Parameter:- 

We can not pass input parameters in the default function, input variable will be defined under function block or globally.


1.1 With Return Type:-  

 We can return the output value from a function using return keyword.

Syntax of Return Type Function:-


def functionname():
     statements
     return value


var = functionname()

Example of return type function in the Python program:-

def calculatesi():

    p = float(input("enter value for amount"))

    r = float(input("enter value for rate"))

    t = float(input("enter value for time"))

    si = (p*r*t)/100

    return si


res = calculatesi()

print(res)




1.2 Without Return Type:-  

We can not return value or output, output will be display under the function block.

Syntax of function:-

def functionname():

       statements
       print(output)

functionname()


Example of default function 

def addition():
    x=100
    y=200
    print("result is ",(x+y))


def substraction():
    x=10
    y=2
    return x-y


addition()
res = substraction()
print(res)



Assignment of default function:-


1)  WAP to reverse a five-digit number using the no return type function.

2) WAP to perform addition of complex number using return type function

3)  WAP to create a salary calculator using no return type function

4)  WAP to calculate compound interest using no return type function.


2) Parametrised:-  

The parameter is used to pass input value from calling function to called function, python provides a different type of parameters based on the requirement.


2.1)  required argument:-  

it should take all input values from calling an argument to called an argument. if we did not pass any values then it will provide an error.


def Functionname(param1,param2):
       statements


Functionname(10,20)  #code will run
Functionname(10)  #code will provide error


Example of require:-


def addition(x,y):
   print("result is ",(x+y))

addition(10)  #error
addition(10,2)


2.2) keyword-based argument:- 

using this type of function we will create a keyword for the argument which will contain the value of calling arguments to called the argument, name of the keyword argument should be the same as called argument.

Keyword means the name of the argument that will be used in the calling function.


def Functionname(x,y):
      statements


Functionname(x=10,y=20) 
Functionname(y=100,x=200)


Example of Keyword based 


def addition(x,y):
   print("result is ",(x/y))


addition(x=10,y=20)
addition(y=100,x=20)
#addition(x=10,2) #error
addition(10,2)


2.3)  default argument:-  

using this function we can set the default value to called the argument from the calling argument.

If we do not pass any value from the calling argument then the default value will be set.



def Functionname(x=10,y=20):
      Statements


Functionname(100,200)
Functionname()
Functionname(2)

Functionname(x=value1,y=value2)\

\
def addition(x=1000,y=20):
    print(x/y)

addition()    
addition(400)  
addition(400,40)
addition(x=10,y=2)
    


2.4)  variable length arguments:- 

We can pass multiple parameters as a tuple arguments using variable length arguments

def functionname(*args):
    Statements
    Statements
functionname(10,20,30,40,...)


We can pass a value to nth parameters as a tuple object.


Example of variable-length parameters


def addition(*x):
   for x1 in x:
     print("result is ",x1)

addition(100,4,23,34,45,5,67)



2.5) lambda function :-


It contains a single statement and is basically used to solve normal expressions in the program.

lambda is a keyword that is used to define the lambda function in the program.


Syntax:-


var = lambda arg1,arg2:statement


Example of lambda function in Python:-

sum = lambda x,y:x+y

print(sum(10,20))




Q) WAP to find max element using variable-length arguments?

#wap to find max element using variable length arguments

def calcMax(*x):
    m=0
    for d in x:
        if m<d:
            m=d
    else:
        print(m)

calcMax(10,23,67,89,11,45)        


Q)  How to pass dictionary object and List Object as a default function and keyword-based function in Python program?

def fun(x={'rno':0,'sname':'unknown'},m=[10,20,30]):

    print(x,m)

student= {'rno':1001,'sname':'manish kumar'}
marks = [12,45,78,89]

#fun(x=student,m=marks)  #keyword
#fun(m=marks,x=student)

#fun(student,marks)
fun()
fun(student)
fun('',marks)

fun(x=student)
fun(m=marks)
fun(x=student,m=marks)
fun(m=marks,x=student)






Assignment of Parametrised function in Python:-

1) WAP to create a mark sheet program using function takes the dictionary as an input variable

2)  Create an ATM Program using a parametrized function?




36 Comments

POST Answer of Questions and ASK to Doubt

  1. #WAP to reverse a five-digit number using no return type function.
    def reverse():#define a function
    num=int(input("enter any 5-digit number"))
    for i in range(0,5):
    i=num%10
    num=num//10
    print(i)
    reverse()#calling a function

    ReplyDelete
  2. #WAP to perform addition of complex number using return type function
    def complex():
    a=2+3j
    b=4+5j

    return a+b
    res=complex()
    print(res)

    ReplyDelete
  3. #WAP to create a salary calculator using no return type function
    def salary():
    name=input("enter name of employee")
    basic=float(input("enter basic salary"))
    da=float(10*basic)/100
    hra=float(15*basic)/100
    pf=float(5*basic)/100
    ta=float(8.5*basic)/100
    perday=float(basic/30)
    netpay=float(basic+hra+ta+da-(2*perday))
    grosspay=float(netpay-pf)
    print(grosspay)
    salary()

    ReplyDelete
  4. # WAP to calculate compound interest using no return type function.
    def compoundinterest():
    p=float(input("enter value of p"))
    r=float(input("enter value of r"))
    t=float(input("enter value of n"))
    Amount = p * (pow((1 + r / 100), t))
    CI = Amount - p
    print("Compound interest is", CI)
    compoundinterest()




    ReplyDelete
  5. #WAP to calculate Simple Interest where rate and time will be constant and
    #the principal will be an integer? (by using function)
    def simpleinterest():
    p=int(input("enter principle amount"))
    const=(2,4)
    SI=p*const[0]*const[1]

    print(SI)
    simpleinterest()

    ReplyDelete
  6. #WAP to calculate the area of a triangle, circle, and rectangle in the same program where the value of pi, the base of the triangle, and the height of the rectangle will be constant.
    def traingle():
    H=int(input("enter value of H"))
    const=(2,0)
    area=(const[0]*H)/2
    print(area)
    def circle():
    r=int(input("enter the value of radius"))
    const=(3.14,0)
    area=(const[0]*r*r)
    print(area)
    def rectangle():
    B=int(input("enter value of base"))
    const=(3,0)
    area=(const[0]*B)
    print(area)
    traingle()
    circle()
    rectangle()



    ReplyDelete
  7. #WAP to convert temperature from Celsius to Fahrenheit?
    def temp():
    c=int(input("enter temprature in celsius"))
    f=((9*c)+160)/5
    print(f)
    temp()

    ReplyDelete
  8. #WAP to swap two numbers without using a third variable by using function
    def swap():
    a=int(input("enter value of a"))
    b=int(input("enter value of b"))
    print("before swappine",a,b)
    a,b=b,a
    print("after swapping",a,b)
    swap()

    ReplyDelete
  9. #WAP to calculate square and cube of any entered number(by using function)
    def square():
    a=int(input("enter value of a"))
    sqr=a*a
    print(sqr)
    def cube():
    b=int(input("enter value of b"))
    cub=b*b*b
    print(cub)

    cube()
    square()

    ReplyDelete
  10. sir this program not run properly is it right logic or not
    # Create ATM Program using function ?

    name=input("enter your name")
    balance=float(input("enter balance"))

    def menu():
    print(name,"welcome to our bank")
    print("\n 1-debit,\n 2-credit,\n 3-viewbalance,\n 4-exit")
    def debit():
    print("enter amount that you want to withdraw",amount)
    balance=balance-amount
    def credit():
    print("enter amount that you want deposit",amount)
    balance=balance+amount
    def showbalance():
    print("total balance is",balance)

    def ATM():
    flag=False
    PIN=1234

    for i in range(1,4):
    p=int(input("enter 4 digit pin number"))
    if p==PIN:
    flag=True
    print(flag)
    break
    else:
    print("pin is incorrect and number of attempt is attempted")
    while(True):
    print("\n 1-debit,\n 2-credit,\n 3-viewbalance,\n 4-exit")
    select=int(input("enter your choice"))
    if select==1:
    print("name","amount to withdraw",debit())
    menu()
    if select==2:
    print("name","amount to withdraw",credit())
    menu()
    if select==3:
    print("name","amount to withdraw",showbalance())
    menu()
    if select==4:
    print("name","amount to withdraw",exit())
    menu()
    called by
    import atm
    atm.ATM()
    debit.atm()
    credit.atm()
    showbalance.atm()






    ReplyDelete
  11. #sir not run properly is it right logic for function
    def marksheet(dict):
    dict={"phy":60,"eng":40,"res":90,"hindi":40,"maths":50}
    count=0
    gm=0
    s=""
    dist=""
    for i in dict:
    if dict[i]>=0 and dict[i]<=100:
    print(dict[i])
    if dict[i]<33:
    count=count+1
    s=s+i+ " "
    gm=dict[i]
    else:
    if dict[i]>=75:
    dist = dist+ i + " "
    else:
    print("All subject marks should be 0 to 100")
    break


    total=total+marks[i]
    else:
    if count==0 or(count==1 and gm>=29):
    per= total/5
    if per>33 and per<45:
    print("Third division with {0} %".format(per))
    elif per<60:
    print("Second division with {0} %".format(per))
    else:
    print("First division with {0} %".format(per))

    if gm>0:
    print("You are pass by grace and grace marks is ",str(33-gm), "grace subject is ",s)
    if dist!=0:
    print("Distinction subject name is ",dist)

    elif count==1:
    print("suppl in ",s)
    else:
    print("fail in ",s)

    marksheet(dict)

    ReplyDelete
  12. #WAP to reverse a five-digit number using the no return type function.
    #Ravi vyas
    def reverse():
    reverse=0
    num=12345
    while (num>0):
    reminder=num%10
    reverse=(reverse*10)+reminder
    num=num//10
    print("Reverse Number Is:-",reverse)
    reverse()

    ReplyDelete
  13. #WAP to perform addition of complex number using return type function
    #Ravi
    def complex():
    a =1+2j
    b=3+4j
    return a+b
    add=complex()
    print(res)

    ReplyDelete
  14. #WAP to reverse a five-digit number using no return type function.
    #AKASH PATEL
    def reverse():
    rev=0
    num=int(input("enter five digit number")
    while (num>0):
    rem=num%10
    rev=(rev*10)+rem
    num=num//10
    print("Reverse Number Is:-",rev)
    reverse()

    ReplyDelete
  15. # WAP to calculate compound interest using no return type function
    #AKASH PATEL
    def compoundinterest():
    p=float(input("enter value of principal "))
    r=float(input("enter value of rate"))
    t=float(input("enter value of time"))
    Amount = p * (pow((1 + r / 100), t))
    CI = Amount - p
    print("Compound interest is", CI)
    compoundinterest()

    ReplyDelete
  16. #Create an ATM Program using a function?
    balance=5000
    pin=9171
    def atm():
    psw=int(input("Enter your Password"))
    if psw==pin:
    print("Please choose your option")
    print("1.Available balance\n2.Debit\n3.creadt\n4 exit")
    option=int(input())
    if option==1:
    print("your balace is",balance)
    elif option==2:
    Debit=int(input("enter Amount"))
    print("Available balance is",balance-Debit)
    elif option==3:
    Creadit=int(input("enter Amount"))
    print("Available balance is",Creadit+balance)
    elif option==4:
    print("thanks for visit")
    else:
    print("incorect password")

    atm()

    ReplyDelete
  17. def sub(x,y):
    x=int(input("Enter The first value"))
    y=int(input("Enter The second value"))
    print("substraction is",(x-y))

    sub(x=10,y=5)





    ReplyDelete
  18. WAP to reverse a five-digit number using the no return type function

    def reverse():
    i=input("enter number")
    x=i[::-1]
    print(x)
    reverse()

    ReplyDelete
  19. WAP to perform addition of complex number using return type function

    def complex():
    x=(4+3j)
    y=(9+1j)
    return(x+y)
    r=complex()
    print(r)

    ReplyDelete
  20. WAP to create a salary calculator using no return type function

    def salary():
    s=int(input("enter basic salary"))
    ta=int(input("enter tallowance"))
    da=int(input("enter dallowance"))
    pf=int(input("enter pf"))
    g=int(input("enter gratuity"))
    gs=s+ta+da-pf-g
    print("Gross salary",gs)
    salary()

    ReplyDelete
  21. WAP to calculate compound interest using no return type function

    def compound():
    p=int(input("enter principle"))
    r=int(input("enter rate of interest"))
    t=int(input("enter time period"))
    i=(1+(r/100))**t
    a=p*i
    it=a-p
    print("The interst is",it)
    compound()

    ReplyDelete
  22. WAP to calculate compound interest using no return type function

    def compound():
    p=int(input("enter principle"))
    r=int(input("enter rate of interest"))
    t=int(input("enter time period"))
    i=(1+(r/100))**t
    a=p*i
    it=a-p
    print("The interst is",it)
    compound()

    ReplyDelete
  23. def reverseno():
    n=int("enter a number")
    a=n%10
    n=n//10
    b=n%10
    n=n//10
    c=n%10
    n=n//10
    d=n%10
    n=n//10
    e=n%10
    n=n//10
    n2=a*10000+b*1000+c*100+d*10+e
    print(n2)
    reverseno()

    ReplyDelete
  24. def complexadd():
    a=complex(input("enter a 1st complex number"))
    b=complex(input("enter a 2nd complex number"))
    c=a+b
    return c
    res=complexadd()
    print(res)

    ReplyDelete
  25. def sal():
    s=int(input("enter monthly salary"))
    d=s/30
    l=int(input("enter leaves"))
    ts=d*(30-l)
    print(ts)
    sal()

    ReplyDelete
  26. def calci():
    p=int(input("enter principal"))
    r=float(input("enter interest rate"))
    n=int(input("enter time period"))
    ta=(p*(1+r/100)**n)-p
    print(ta)
    calci()

    ReplyDelete
  27. def marksheet():
    ms={}
    ss=5
    tm=0
    for i in range(0,5):
    sub=input("enter subject")
    marks=int(input("enter obtained marks out of 100"))
    ms.update({sub:marks})

    tm=tm+marks
    p=(tm/500)*100
    print("your obtained score is",ms)
    if p>75:
    print("your total percentge is",p,"you are pass with A grade")
    elif p<=75 and p>60:
    print("your total percentge is",p,"you are pass with B grade")
    elif p<=60 and p>45:
    print("your total percentge is",p,"you are pass with C grade")
    elif p<=45 and p>33:
    print("your total percentge is",p,"you are pass with D grade")
    else:
    print("your are fail your obtained marks are",tm)



    marksheet()

    ReplyDelete
  28. def atm():
    bal=13000
    pin=4133
    psw=int(input("Enter your Password"))
    if psw==pin:
    print("Hii Grv Please choose your option")
    print("1.Balance\n2.Debit\n3.credit\n4 exit")
    select=int(input())
    if select==1:
    print("your balace is",bal)
    elif select==2:
    Debit=int(input("enter Amount"))
    print("Available balance is",bal-Debit)
    elif select==3:
    Credit=int(input("enter Amount"))
    print("Available balance is",Credit+bal)
    elif select==4:
    print("thanks for visit")
    else:
    print("incorect password")

    atm()

    ReplyDelete
  29. to reverse a five-digit number using the no return type function

    def rev():
    i=input("enter number")
    x=i[::-1]

    print(x)
    rev()

    ReplyDelete
  30. to perform addition of complex number using return type function

    def complex():
    x=(4+3j)
    y=(9+1j)
    return(x+y)
    r=complex()
    print(r)

    ReplyDelete
  31. # WAP to calculate compound interest using no return type function.
    def comInte():
    p=float(input("enter principal:-"))
    r=float(input("enter interest:-"))
    t=float(input("enter time:-"))
    n=float(input("compounding frequency:-"))
    r=r/100
    i=p*((1+r/n)**(n*t))-p
    print("compound interest is:-",i)
    print("total amount is:-",i+p)
    comInte()

    ReplyDelete
  32. # WAP to create a salary calculator using no return type function.
    def salary():
    sal=int(input("enter empolyee salary:="))
    wd=int(input("enter wworking days:-"))
    ot=int(input("enter over time in hours:-"))
    pf=int(input("enter pf charges:-"))
    can=int(input("enter canteen charges:-"))
    if wd>23:
    sal=sal/26*wd+2000

    elif wd>20 and wd<=23:
    sal=sal/26*wd+1500
    else:
    sal=sal/26*wd+0
    ot=ot/8
    a=ot*sal/26
    total=sal+a-pf-can
    print(total)
    salary()

    ReplyDelete
  33. # WAP to perform addition of complex number using return type function.
    def addComplex():
    a=2+2j
    b=4+9j
    return a+b
    res=addComplex()
    print(res)

    ReplyDelete
  34. #WAP to reverse a five-digit number using the no return type function.
    def rev():
    num=int(input("enter five digits numbers:-"))
    a=num%10
    num=num//10
    b=num%10
    num=num//10
    c=num%10
    num=num//10
    d=num%10
    num=num//10
    e=num%10
    num=num//10
    print(a,b,c,d,e)
    rev()

    ReplyDelete
  35. #WAP to reverse a five-digit number using the no return type function.

    def revnum():
    num=int(input("Enter number to reverse: "))
    for i in range(0,5):
    i=num%10
    num=num//10
    print(i)
    revnum()

    ReplyDelete
  36. def credit(balance):
    bal=balance
    print("deposite balance is:-",bal)
    def debit(balance,dbi):
    bal=balance
    d=dbi
    print("withdrawal balance is:-",d)
    print("available balance is:-",bal)
    def checkBal(balance):
    bal=balance
    print("available amount is:-",bal)
    def exit1():
    exit()
    def atm():
    bal=0
    for i in range(0,3):
    pin=int(input("enter your 4 digits pin:-"))
    if pin==1234:
    ch=input(" 1.press c for credit \n 2.press d for debit \n 3.press b for check balance \n 4.press e for exit \n 5.press r for repeat \n")

    if ch=='c':
    ac=int(input("enter your account number:-"))
    if ac==123456789:
    cb=int(input("enter your deposite balance:-"))
    bal=bal+cb
    credit(bal)
    else:
    print("wrong account number")


    if ch=='d':
    db=int(input("enter withdrawal amount:-"))
    if bal>=db:
    bal=bal-db
    debit(bal,db)
    else:
    print("insufficient balance")
    if ch=='e':
    exit1()
    if ch=='b':
    checkBal(bal)

    else:
    print("you entered wrong pin ")

    atm()

    ReplyDelete

Post a Comment

POST Answer of Questions and ASK to Doubt

Previous Post Next Post