Function
A function is a block of code that performs a task. It can be called and reused multiple times.
1. no return function
2. return function
Syntax:
def FunctionName(parameters):
Statements
Example(1)
def showMsg(): #function definition
print("Hello World")
print("Python Program")
print("test Function")
def sum(x,y): #function definition
print("Sum=",x+y)
print("do somthing")
showMsg() # function calling
sum(1,2) # function calling
single value return function
Example(2)
def sum(x,y):
return x+y
print("Sum
print("Total=",result)
print("Average=",result/2)
Example(3)
def max_Num(a,b):
if(a>b):
return a
else:
return b
a=int(input("Enter first num:"))
b=int(input("Enter first num:"))
print("Maximum Number=",max_Num(a,b))
Global Variable
A global variable in Python is a variable that is declared outside of any function or class and is accessible from
anywhere in the program. Global variables are usually used to store information that needs to be accessed by
multiple functions or classes.
Example(4)
x="orginal"
def changeOriginal():
y="inside function"
global x #global
x="Update Value"
print(y)
changeOriginal()
print(x)
Default Parameter
Example(5)
def show_Greeting(name="Susan"):
print("Have a nice day!",name)
show_Greeting("Michael")
show_Greeting()
Example(6)
def show_Greeting1(name="John",age=30,phone=9567543):
print("Name!",name)
print("Age!",age)
print("Phone
show_Greeting1()
Exercise
Write a Python program to calculate the difference between a given number and 17. If the number is
greater than 17, return twice the absolute difference.