






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Python has rich collections of built-in functions. Still we need user defined function for the following reasons:
A function with return statement will always return a value to the caller. A function can return more than one values to the caller. But for the time being we will discuss functions that returns only one value. Generally, a return statement is followed by either a variable or an expression or a constant. Value of the variable / expression / constant is returned to the caller by a return statement. Just a return statement without any variable/expression/constant will return None to the caller. A function without a return statement also returns a value None. Complete Python script including user defined function myfactorial() with parameter n and without return statement is given below. def myfactorial(no): fact= for k in range(1, no+1): fact*=k; print(fact) n=int(input('Input n? ')) myfactorial(n) myfactorial(n+2) print(myfactorial( 8 )) Now edited myfactorial () does not return any value. Factorial calculated is displayed within the function. When a function does not return any value, function call is FuncName ( Parameter ). Let us assume inputted value of n is 5. First call to the function display factorial of n , second call to the function display factorial of n+ and third call to the function displays factorial 8 and finally None is displayed. Running of the Python script produces following outputs : Input n? 5 120 5040 40320 None Parameter is used to transfer data between caller and user defined function. The data transfer can be either one-way or it can be two ways. Parameter used in the function header is called formal parameter. Parameter used during the function call is called actual parameter. Formal parameter receives value from actual parameter. Data type of formal parameter depends on data type of actual parameter. As shown in the above example, actual parameter can either be a variable or an expression or a constant. But formal parameter is a variable. When invoking a function list of actual parameters must be equal to list of formal parameters. List of actual parameters must be compatible with list of formal parameters. def add(a, b): t=a+b print(t) add(20,20) #call # add(10,15.5) #call # add(5.7,8.8) #call # add('DP','S') #call # add(20,'DPS') #call # add('DPS',5.3)#call # add(40) #call # add(23,45,64) #call # First call to function has two int as actual parameters, values stored two format parameters are added and their sum is displayed. Second call to function has an int and a float ( int and float can be added) as actual parameters and their sum is displayed. Third call to function has two float actual parameters and their sum is displayed. Fourth call to function has two str (two strings are concatenated) as actual parameters and concatenated string is displayed. Fifth call to function has an int and a str as actual parameters and they are not compatible hence run- time error. Sixth call to function has a str and a float as actual parameter and they are not compatible hence run-time error. Seventh call and eight call to function, number of actual parameter(s) does not match with number formal parameters and hence run-time error. Running of the Python script produces following outputs : 40
FAIPS Triggers Run-time Error Triggers Run-time Error Triggers Run-time Error Triggers Run-time Error
x= 10 def foo(): global x, y x, y=100, 200 print(x,y) y= 20 foo() print(x,y) x= 10 def foo(): x, y=100, 200 #Syntax error global x, y print(x,y) y= 20 foo() print(x,y) Running of the Python script produces following outputs : 100 200 100 200 Running of the Python script produces syntax error because keyword global is used after the statement x, y=100, 200 Keyword global to be used before the updation. The keyword global, will make variables x and y as global variable and hence the variables x and y can be updates inside the function foo(). The keyword global is to be used before accessing or updating the global variables x and y. Without using the keyword global, variable created inside a function with same name as a global variable, becomes the local variable. x= 10 def foo(): global x x, y=100, 200 print(x,y) y= 20 foo() print(x,y) x= 10 def foo(): global y x, y=100, 200 print(x,y) y= 20 foo() print(x,y) Running of the Python script produces following outputs : 100 200 100 20 Variable x is global variable and variable y is a local variable. Global variable x is updated. Running of the Python script produces following outputs : 100 200 10 200 Variable y is global variable and variable x is a local variable. Global variable y is updated. Keyword global has to be used in every function where a global variable is to be updated. x= 10 def foo(): global x x= print(x) def moo(): x=1000 #x is local to moo() print(x) foo() print(x) moo() print(x) x= 10 def foo(): global x x= print(x) def moo(): global x x= print(x) foo() print(x) moo() print(x) Running of the Python script produces following outputs : 100 100 1000 100 Without the keyword global , x is a local to moo() and hence global variable x does not get updated. Running of the Python script produces following outputs : 100 100 1000 1000 Because of the keyword global in the function moo() , global variable x get updated.
Keyword global can be used to create a global variable inside a user defined function. x= 10 def foo(): global x, y x, y=100, print(x,y) def moo(): global x, y x, y=1000, print(x,y) print(x) foo() print(x,y) moo() print(x,y) Global variable x=10 is created right in the beginning. Inside the function foo() , global variable y is created. Inside the function foo() , global variable x is 100 and global variable y is 100. Function print(x,y) after foo() displays 100 100. Inside the function moo() , global variable x is 1000 and global variable y is 1000. Function print(x,y) after foo() displays 1000 1000. Running of the Python script produces following outputs : 10 100 200 100 200 1000 2000 1000 2000 Use of keyword global :
while n: d=n% s+=dd #Or, s+=d* n//= return s #Or, print(s) while n: d=n% s+=ddd #Or, s+=d** n//= return s #Or, print(s) #products of digits def productdigit(n): p= while n: d=n% p=d n//= return p #Or, print(p) #products of digits ignore 0 def productdigit(n): p= while n: d=n% if d: p=d n//= return p #Or, print(p) #sum of reciprocal of digits def sumdigitreci(n): s= while n: d=n% if d: s+=1/d n//= return s #Or, print(s) #reversing digits def reversedigits(n): s= while n: d=n% s=10s+d n//= return s #Or, print(s) #check for Armstrong Number def chkarmstrong(n): s, t, power=0, n, len(str(n)) while t: d=t% s+=dpower t//= if s==n: print('Armstrong') else: print('Not Armstrong') #Or, return int(s==n) #check for Palindrome Number def chkpalindrome(n): s, t=0, n while t: d=t% s=10s+d t//= if s==n: print('Palindrome') else: print('Not Palindrome') #Or, return int(s==n) #HCF of two numbers def hcf(a,b): r= while r: r=a%b a=b b=r return a #Or, print(a) #LCM of two numbers def lcm(a,b): p, r=a*b, 1 while r: r=a%b a=b b=r return p//a #Or, print(p//a) #check for Prime Number def chkprime(n): k= prime= while k<n//2 and prime==1: if n%k==0: prime= k+= if prime==1: print('Prime') else: print('Composite') #Or, return prime #check for Prime Number def chkprime(n): k, prime=2, 1 while k<n//2: if n%k==0: prime= break k+= if prime==1: print('Prime') else: print('Composite') #Or, return prime
#check for Prime Number def chkprime(n): prime= for k in range(2, n//2): if n%k==0: prime= break if prime==1: print('Prime') else: print('Composite') #Or, return prime #check for Prime Number def chkprime(n): for k in range(2, n//2): if n%k==0: print('Composite Number') #Or, prime= break else: print('Prime Number') #Or, prime= #Or, return prime #check for Fibonacci Number def chkfibo(n): f1, f2=0, 1 while n>=f1: if n==f1: print('Fibonacci No') fibo= break elif n>f1: print('Not Fibonacci No') fibo= break f1,f2=f2,f1+f #return fibo #check for Fibonacci Number def chkfibo(n): f1= f2= fibo= while n>=f1: if n==f1: fibo= f1,f2=f2,f1+f if fibo: print('Fibonacci No') else: print('Not Fibonacci No') #return fibbo #Generate first n Fibonacci numbers def genfibbo(n) f1= f2= 1 for k in range(n): print(f1) f1, f2=f2, f1+f #Generate first n Fibonacci numbers def genfibbo(n) f1, f2, k=0, 1, 1 while k<=n: print(f1) f1, f2=f2, f1+f k+= #check for Perfect Number def chkperfect(n) s= for k in range(1, n): if n%k==0: s+=k if s==n: print('Perfect Number') else: print('Not Perfect Number') #Or, return int(s==n) #check for Perfect Number def chkperfect(n) k, s=0, 1 while k<=n: if n%k==0: s+=k k+- 1 if s==n: print('Perfect Number') else: print('Not Perfect Number') #Or, return int(s==n) #Generate Prime Numbers def genprime(n): for num in range(2, n+1): for k in range(2, num//2): if num%k==0: break else: print(num) #Generate Prime Numbers def genprime(n): for num in range(2, n+1): prime= for k in range(2, num//2): if num%k==0: prime= break if prime: print(num)
Outputs produced by the script : Roll= 12 Name= RANJAN YADAV Marks= 78. Roll= RANJAN YADAV Name= 78. Marks= 12 Roll= 78. Name= 12 Marks= RANJAN YADAV Above example shows that using keyword arguments , even if the order of actual arguments does not match with order of formal arguments but correct values are assigned to the formal arguments. Default argument (parameter) As discussed above, every function with arguments must have same number of formal arguments and actual arguments. But we will see now that may not true every time. In Python, formal arguments can be assigned constant values and that function can be called without any actual arguments. Constant values assigned to the formal arguments are called Default Arguments. When actual argument is present during the function call, formal argument's default value is replaced by value present in the actual argument. Default arguments always starts from the right. An example is given below: def foo(ch='*', n=10): for x in range(n): print(ch, end='') print() foo() foo('#') foo(7) foo('$',12) foo(n=15, ch='@') Outputs produced by the script :
########## 7777777777 $$$$$$$$$$$$ @@@@@@@@@@@@@@@ As mentioned earlier, default arguments start from right. Examples of incorrect use of default arguments are given below: def foo(a=10,b,c= 3 0): avg=(a+b+c)/ print(avg) Syntax error Non-default argument follows default argument. Since formal argument b is non-default argument. Possible solution, make formal argument b as default argument. def foo(a=10,b= 2 0,c): avg=(a+b+c)/ print(avg) Syntax error Non-default argument follows default argument. Since formal argument c is non-default argument. Possible solution, make parameter c as default argument. def foo(a=10,b,c): avg=(a+b+c)/ print(avg) Syntax error Non-default argument follows default argument. Since formal arguments b and c are non-default arguments. Possible solution, make formal argument b and c as default argument. def foo(a,b=20,c): avg=(a+b+c)/ print(avg) Syntax error Non-default argument follows default argument. Since formal argument c is non-default argument. Possible solution, make formal argument c as default argument. Explanation of outputs foo() calls the function without any actual arguments. Function foo() uses default values of the formal arguments to display **********. foo('#') calls the function with one actual argument. '#' replaces the default of ch but n's default value is still 10. So ########## is displayed. foo( 7 ) calls the function with one actual argument. 7 replaces the default value of ch but n's default value is still