Introduction To Functions: Syntax of Function Is As Follows
Introduction To Functions: Syntax of Function Is As Follows
Output:
Welcome to the Concepts of Functions
Parameters, Arguments in a
Function
Parameters are used to give input to a
function.
def FindMin(num1,num2):
if num1 < num2:
print(num1, 'is smaller than ',num2)
elif num2 < num1:
print(num2,' is smaller than ', num1)
else:
print(' Both are equal')
FindMin(20,40)
Output:
20 is smaller than 40
Positional Arguments
Positional arguments must be must be passed as in exact
order i.e. the way they are defined.
def Display(Name,age):
print("Name = ",Name,"age = ",age)
Display("John",25)
Display(40,"Sachin")
Output:
Name = John age = 25
Name = 40 age = Sachin
Thus, the first argument binds to the first parameter and second
argument binds to the second parameter. This style of matching up
arguments and parameter is called “positional argument style” or
“positional parameter style”.
Keyword Arguments
An alternative to positional argument is keyword
argument.
Output:
Name = John age = 25
Precautions while using Keyword Arguments
A positional argument cannot follow a keyword
argument.
Display( num2=10,40)
Display(40,num1=40)
Parameters with Default Values
Parameters within the function definition can have
default values.
Default value to an parameter can be given by using
assignment (=) Operator.
Output:
Hello Virat Welcome to Python!!
Note:
Syntax Error: Non default argument follows default argument
The Local and global Scope of Variable
p = 20 #global variable p
def Demo():
q = 10 #Local variable q
print('The value of Local variable q:',q)
#Access global variable p within this function
print('The value of Global Variable p:',p)
Demo()
#Access global variable p outside the function Demo()
print('The value of global variable p:',p)
Example:
def minimum(a,b):
if a<b:
return a
elif b<a:
return b
else:
return "Both the numbers are equal"
print(minimum(100,85))
Output:
8 is minimum
Returning Multiple Values
In python yes it is possible to return multiple values.
Syntax to return multiple values is as follows
return Value1,Value2,Value3
import math
def Sq_Cub_Srt(a,b,c):
return a**2, b**3, math.sqrt(c)
S,C,Sq = Sq_Cub_Srt(2,3,4)
print('Square = ',S)
print('Cube = ',C)
print('Cube = ',Sq)
Output
Square = 4
Cube = 27
Cube = 2.0
Conclusion
A function is a self contained block of one or more
statements that perform a special task when called.