In previous articles, we have learned the basic concepts of Python Functions. In this article, let us do some practice programs on Python functions. These are some basic programs to clear the concept.
Table of Contents
Python program to print the string using the function
def display():
#return
print("In Display function")
print("In Main function")
display()
print("Back to Main")
input()
Python program to check the difference between a local and global variable
a=5#global
def display():
a=10#local
print("In display function a = ",a)
def show():
a=20#local
print("In Show function a = ",a)
def function():
global a
a=30
print("In function a = ",a)
display()
show()
function()
input()
Addition of two number without parameter
def add():
print("Enter the two Numbers ")
a=int(input())
b=int(input())
sum=a+b
print("Sum = ",sum)
add()
input()
Addition of two number with parameter
def add(x,y):
sum=x+y
print("Sum = ",sum)
print("Enter the two Numbers ")
a=int(input())
b=int(input())
add(a,b)
input()
Function with return value without parameter
def add():
print("Enter the two Numbers ")
a=int(input())
b=int(input())
sum=a+b
return sum
print("Sum = ",add())
input()
Function with return value with a parameter
def add(x,y):
sum=x+y
return sum
print("Enter the Two Numbers : ")
a=int(input())
b=int(input())
c=add(a,b)
print("Sum = ",c)
input()
Function return more than one value
def swap(x,y):
temp=x
x=y
y=temp
return x,y
print("Enter the Two Numbers : ")
a=int(input())
b=int(input())
print("Before Calling Swap function a = ",a," and b = ",b)
a,b=swap(a,b)
print("After Calling Swap function a = ",a," and b = ",b)
input()
Function call by value
def swap(x,y):
temp=x
x=y
y=temp
print("Enter the Two Numbers : ")
a=int(input())
b=int(input())
print("Before Calling Swap function a = ",a," and b = ",b)
swap(a,b)
print("After Calling Swap function a = ",a," and b = ",b)
input()
Program to create the calculator
def add(x,y):
sum=x+y
print(a," + ",b," = ",sum)
def sub(x,y):
s=x-y
print(a," - ",b," = ",s)
def mul(x,y):
m=x*y
print(a," * ",b," = ",m)
def div(x,y):
d=x/y
print(a," / ",b," = ",d)
def floor_div(x,y):
d=x//y
print(a," // ",b," = ",d)
print("Enter the Two Numbers : ")
a=int(input())
b=int(input())
print("Press + for Addition")
print("Press - for Subtraction")
print("Press * for multiplication")
print("Press / for Division")
print("Press // for Floor Division")
ch=input()
if(ch=='+'):
add(a,b)
elif(ch=='-'):
sub(a,b)
elif(ch=='*'):
mul(a,b)
elif(ch=='/'):
div(a,b)
elif(ch=='//'):
floor_div(a,b)
else:
print("Invalid Choice")
Python recursion function
def display():
global a
a=a+1
print("In Display function")
if(a<5):
display()
print("Back to display")
a=0
print("In Main")
display()
print("Back to main")
input()
Program to get the factorial using recursion
def fact(num):
if(num<=0):
return 1
else:
return num*fact(num-1)
n=int(input('Enter the number to get Factorial '))
f=fact(n)
#print("Factorial of ",n," is = ",f)
print("Factorial of %d is = %d"%(n,f))
input()