Python User Defined Function — How to Create Functions in Python
User-defined functions allow us to divide program logic into small reusable blocks. This improves code readability, reduces repetition, and follows the procedural pattern of Python.
Syntax of a Function
def functionname():
statements
...
functionname()
Example — Addition & Subtraction Using Functions
def addition():
a = int(input("enter first number"))
b = int(input("enter second number"))
print(a + b)
def substraction():
a = int(input("enter first number"))
b = int(input("enter second number"))
print(a - b)
addition()
substraction()
Example — Simple Interest Program Using Function
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()
Parameterized Function Example
def addition(x, y):
print(x + y)
def substraction():
x = int(input("Enter First Number"))
y = int(input("Enter Second Number"))
print(x - y)
addition(
int(input("Enter first number")),
int(input("Enter Second number"))
)
substraction()
Complete Function Based Calculator (6 Functions)
def acceptInput():
global a, b
a = int(input("Enter first number"))
b = int(input("Enter second number"))
def add():
print(a + b)
def sub():
print(a - b)
def multi():
print(a * b)
def division():
print(a / b)
def executeFunction():
while True:
ch = input("Press + for addition \n - for Subtraction \n * for multiplication \n / for division\n")
if ch == '+':
acceptInput()
add()
elif ch == '-':
acceptInput()
sub()
elif ch == '*':
acceptInput()
multi()
elif ch == '/':
acceptInput()
division()
else:
break
executeFunction()
Same Program Using Parameterized Functions
def add(a, b):
print(a + b)
def sub(a, b):
print(a - b)
def multi(a, b):
print(a * b)
def division(a, b):
print(a / b)
def executeFunction():
while True:
ch = input("Press +, -, *, /\n")
if ch == '+':
add(int(input("Num1")), int(input("Num2")))
elif ch == '-':
sub(int(input("Num1")), int(input("Num2")))
elif ch == '*':
multi(int(input("Num1")), int(input("Num2")))
elif ch == '/':
division(int(input("Num1")), int(input("Num2")))
else:
break
executeFunction()
Example — Using Function From Separate File
File 1: Ope.py
def Add():
a=100
b=200
print(a+b)
def Sub():
a=100
b=20
return a - b
def Multiplication(a,b):
print(a*b)
def Division(a,b):
return a/b
File 2: Access File
import Ope
Ope.Add()
x = Ope.Sub()
print(x)
Ope.Multiplication(100,2)
y = Ope.Division(10,2)
print(y)
Types of Functions in Python
1) Default / Without Parameter Function
- Input is taken inside the function
- Can be with return type or without return type
Example — With Return Type
def calculatesi():
p = float(input("enter amount"))
r = float(input("enter rate"))
t = float(input("enter time"))
return (p*r*t)/100
res = calculatesi()
print(res)
Example — Without Return Type
def addition():
x = 100
y = 200
print("result is ", (x+y))
addition()
Assignment for Default Functions
- Reverse a five-digit number using no-return function
- Add complex numbers using return function
- Create salary calculator (no return)
- Calculate compound interest (no return)
2) Parameterized Functions
2.1 Required Arguments
def addition(x, y):
print(x + y)
addition(10, 2)
2.2 Keyword Arguments
def addition(x, y):
print(x / y)
addition(x=10, y=20)
addition(y=100, x=20)
2.3 Default Arguments
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 (*args)
def addition(*x):
for val in x:
print("result is ", val)
addition(100,4,23,34,45,5,67)
Lambda Function
sum = lambda x, y: x + y
print(sum(10, 20))
Q) Find Max Using Variable Length Arguments
def calcMax(*x):
m = 0
for d in x:
if d > m:
m = d
print(m)
calcMax(10,23,67,89,11,45)
Salary Calculator Using User Defined Function
def SalaryCal():
name = input("Enter name")
basic = float(input("Enter basic salary"))
ta = float(input("Enter ta"))
da = float(input("Enter da"))
comm = float(input("Enter comm"))
pf = float(input("Enter pf"))
hra = float(input("Enter HRA"))
lv = float(input("Enter leave days"))
ctc = basic + ta + da + comm + hra + pf
print("CTC of employee is ", ctc)
tsal = basic + ta + da + comm + hra
lvded = (tsal/30)*lv
gsal = tsal - lvded - pf
print("Gross Salary is ", gsal)
f = open("salaryslip.doc","a")
f.write("\n--------------------")
f.write("\n Name: "+name)
f.write("\n Gross Salary: "+str(gsal))
f.write("\n Leave Deduction: "+str(lvded))
f.write("\n--------------------")
f.close()
Execution File
import SalaryCalc
num = int(input("Enter number of employees"))
for i in range(1, num+1):
SalaryCalc.SalaryCal()
Assignments for Parameterized Functions
- Create mark-sheet program using dictionary
- ATM program using parameterized functions
56 Comments
#WAP to reverse a five-digit number using no return type function.
ReplyDeletedef 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
#WAP to perform addition of complex number using return type function
ReplyDeletedef complex():
a=2+3j
b=4+5j
return a+b
res=complex()
print(res)
#WAP to create a salary calculator using no return type function
ReplyDeletedef 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()
# WAP to calculate compound interest using no return type function.
ReplyDeletedef 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()
#WAP to calculate Simple Interest where rate and time will be constant and
ReplyDelete#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()
#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.
ReplyDeletedef 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()
#WAP to convert temperature from Celsius to Fahrenheit?
ReplyDeletedef temp():
c=int(input("enter temprature in celsius"))
f=((9*c)+160)/5
print(f)
temp()
#WAP to swap two numbers without using a third variable by using function
ReplyDeletedef 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()
#WAP to calculate square and cube of any entered number(by using function)
ReplyDeletedef 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()
sir this program not run properly is it right logic or not
ReplyDelete# 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()
#sir not run properly is it right logic for function
ReplyDeletedef 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)
#WAP to reverse a five-digit number using the no return type function.
ReplyDelete#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()
#WAP to perform addition of complex number using return type function
ReplyDelete#Ravi
def complex():
a =1+2j
b=3+4j
return a+b
add=complex()
print(res)
#WAP to reverse a five-digit number using no return type function.
ReplyDelete#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()
# WAP to calculate compound interest using no return type function
ReplyDelete#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()
#Create an ATM Program using a function?
ReplyDeletebalance=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()
def sub(x,y):
ReplyDeletex=int(input("Enter The first value"))
y=int(input("Enter The second value"))
print("substraction is",(x-y))
sub(x=10,y=5)
WAP to reverse a five-digit number using the no return type function
ReplyDeletedef reverse():
i=input("enter number")
x=i[::-1]
print(x)
reverse()
WAP to perform addition of complex number using return type function
ReplyDeletedef complex():
x=(4+3j)
y=(9+1j)
return(x+y)
r=complex()
print(r)
WAP to create a salary calculator using no return type function
ReplyDeletedef 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()
WAP to calculate compound interest using no return type function
ReplyDeletedef 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()
WAP to calculate compound interest using no return type function
ReplyDeletedef 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()
def reverseno():
ReplyDeleten=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()
def complexadd():
ReplyDeletea=complex(input("enter a 1st complex number"))
b=complex(input("enter a 2nd complex number"))
c=a+b
return c
res=complexadd()
print(res)
def sal():
ReplyDeletes=int(input("enter monthly salary"))
d=s/30
l=int(input("enter leaves"))
ts=d*(30-l)
print(ts)
sal()
def calci():
ReplyDeletep=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()
def marksheet():
ReplyDeletems={}
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()
def atm():
ReplyDeletebal=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()
to reverse a five-digit number using the no return type function
ReplyDeletedef rev():
i=input("enter number")
x=i[::-1]
print(x)
rev()
to perform addition of complex number using return type function
ReplyDeletedef complex():
x=(4+3j)
y=(9+1j)
return(x+y)
r=complex()
print(r)
# WAP to calculate compound interest using no return type function.
ReplyDeletedef 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()
# WAP to create a salary calculator using no return type function.
ReplyDeletedef 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()
# WAP to perform addition of complex number using return type function.
ReplyDeletedef addComplex():
a=2+2j
b=4+9j
return a+b
res=addComplex()
print(res)
#WAP to reverse a five-digit number using the no return type function.
ReplyDeletedef 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()
#WAP to reverse a five-digit number using the no return type function.
ReplyDeletedef revnum():
num=int(input("Enter number to reverse: "))
for i in range(0,5):
i=num%10
num=num//10
print(i)
revnum()
def credit(balance):
ReplyDeletebal=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()
#WAP to reverse a five-digit number using the no return type function.
ReplyDeletedef reverse():
num=1234
for i in range(0,4):
a=num%10
num= num//10
print(a,end=" ")
reverse()
#WAP to print charecter A to Z using user difine function?
ReplyDeletedef funAZ(asc):
if asc>90:
return 1
print(chr(asc))
funAZ(asc+1)
funAZ(65)
#WAP to reverse a five-digit number using the no return type function without useing loop.
ReplyDeletedef REVpro():
num=int(input("Enter any Number "))
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
rev=a*10000+b*1000+c*100+d*10+e*1
return rev
n=REVpro()
print(n)
#WAP to perform addition of complex number using return type function
ReplyDeletedef ComplexNum():
t=2+9j
d=6+8j
com=t+d
return com
num=ComplexNum()
print(num)
#reverse 5 digit using no return
ReplyDeletedef reverse():
num=int(input("enter number "))
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
print(a*10000+b*1000+c*100+d*10+e*1)
reverse()
#WAP to perform addition of complex number using return type function
ReplyDeletedef complex():
a=3+4j
b=6+7j
return(a+b)
x=complex()
print(x)
#WAP to perform addition of complex number using no return type function
ReplyDeletedef complex():
a=3+4j
b=6+7j
c=a+b
print(c)
complex()
#factorial using return?
ReplyDeletedef fact():
a=1
n=int(input("enter number "))
for i in range(1,n+1):
a=a*i
return(a)
x=fact()
print(x)
# WAP to create a salary calculator using no return type function
ReplyDeletedef calSalary():
basic=10000
ta=1000
da=500
pf=300
hra=200
leave=3
sal=(basic+ta+da+pf+hra)
oneday=(sal/30)
dl=oneday*leave
totalsal=sal-dl
print(totalsal)
calSalary()
#WAP to calculate Campound Intrest using user difine function with return type?
ReplyDeletedef calCI():
p=int(input("Enter The Amount "))
r=int(input("Enter The Rate "))
t=int(input("Enter The Time"))
ci=(p*(1+r/100)**t)-p
return ci
s=calCI()
print("Campound Intrest %.2f"%s)
#WAP to reverse a five-digit number using the no return type function.
ReplyDeletedef rev():
n=int(input("Enter a no. to reverse:"))
for i in range(0,5):
i=n%10
n=n//10
print(i,end='')
rev()
#Program to add complex no. with return type
ReplyDeletedef comp():
a=complex(input("Enter a complex number"))
b=complex(input("Enter a complex number"))
return (a+b)
res=comp()
print(res)
#program to reverse a string
ReplyDeletedef rev_strng(s):
x=''
i=len(s)
while i > 0:
x=x+s[i-1]
i=i-1
return x
print(rev_strng("Nagpur"))
#WAP to find minimum element using variable-length arguments?
ReplyDeletedef swap(*a):
m=a[1]
for data in a:
if m>data:
m=data
print(m)
swap(12,32,44,3,55,66,10,5)
#Wap to swap two number using variable length?
ReplyDeletedef swap(*s):
print(s[1],s[0])
swap(100,99)
#WAP to find max element using variable-length arguments?
ReplyDeletedef maximum(*x):
print('maximum',max(x))
maximum(61,22,32,44,85,63,29,27)
def maximum(*x):#diffrent type
m=0
for data in x:
if m<data:
m=data
else:
print('maximum',m)
maximum(61,22,32,44,85,63,29,27)
WAP to reverse a five-digit number using the no return type function.
ReplyDeletedef reverse():
n=int(input("Enter a five digit number: "))
s=""
b=n
for i in range(0,5):
a=b%10
b=b//10
s=s+str(a)
print(s)
reverse()
WAP to perform addition of complex number using return type function
ReplyDeleteimport cmath
def complexFun():
x=2+6j
y=3+4j
z=x+y
return z
a=complexFun()
print(a)
WAP to create a salary calculator using no return type function
ReplyDeletedef salaryCal(s,l,b):
t=s-(l*250)
if l==0:
t=t+b
print("You will get a bonus for 0 leaves")
print("Your Total Salary is: ",t)
salaryCal(int(input("salary: ")),int(input("leaves: ")),5000)
#complex number multiplication
ReplyDeletea=10+1j
b=20+2j
def add(a,b):
c=a+b
print(c)
def subtraction(a,b):
c=a-b
print(c)
def multi(a,b):
c=a*b
print(c)
def division(a,b):
c=a//b
print(c)
multi(a,b)
POST Answer of Questions and ASK to Doubt