Docsity

Python function notes, Study notes of Computer science

Toggle sidebar
bg1
Python Notes Class XI User Defined Function
FAIPS, DPS Kuwait Page 1 / 10 ©Bikram Ally
Python has rich collections of built-in functions. Still we need user defined function for the following
reasons:
1. Functions help divide a program into modules. This makes the code easier to manage and debug
2. It implements code reuse. To reuse the call, a function needs to be called (invoked)
Python function has two parts:
a) Function Header: it starts with keyword def, contains the name of the function and optional list of
formal parameters, that is, it is not necessary that every function must have parameters.
b) Function Block: it is the block after the function header. Function block contains equally indented
statements that carry out certain action inside the function. Function block may contain the optional
return statement. An example of a user defined function is given below:
User Defined
Function
OR
Function
Definition
def myfactorial(n):
fact=1
for k in range(1,n+1):
fact*=k
return fact
Function Header
Function Block
Or
Function Body
Name of the function is myfactorial(), function returns a value and it has a formal parameter n.
Function name is myfactorial(). In Python, formal parameter does not have any parameter (this issue
will be discussed later). Function’s return statement serves two purposes:
a) It terminates the function
b) Returns a value to the caller
When a function returns a value, the function may be called (invoked) as:
1. VarName=FunctionName(ActualParaList)
2. print(FunctionName(ActualParaList))
Complete Python script including user defined function myfactorial() with parameter no.
def myfactorial(no):
fact=1
for k in range(1, no+1):
fact*=k;
return fact
n=int(input('Input n? '))
f1=myfactorial(n)
f2=myfactorial(n+3)
f3=myfactorial(8)
print(f1)
print(f2)
print(f3)
print(myfactorial(5))
myfactorial(6)
• myfactorial() – user defined function
• no – Formal parameter
• Function call is:
f1=myfactorial(n)
f2=myfactorial(n+3)
f3=myfactorial(8)
print(myfactorial(5))
myfactorial(6)
• Actual parameter:
1st call – n (variable)
2nd call – n+3 (expression)
3rd call – 8 (constant)
4th call – 5 (constant)
5th call – 6 (constant)
Running of the Python script produces following outputs:
Input n? 7
5040
0320
3628800
120
No output
Variables f1, f2 and f3 stores the return values of myfactorial()
for the first call, for the second call and for third call respectively. Values
stored in f1, f2 and f3 are then displayed with print(). Fourth call
of the function is directly from print() and it displays the return value
of myfactoral(). Last call to myfactorial(6) does not display
any output since the return value of the function is discarded.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Python function notes and more Study notes Computer science in PDF only on Docsity!

Python has rich collections of built-in functions. Still we need user defined function for the following reasons:

  1. Functions help divide a program into modules. This makes the code easier to manage and debug
  2. It implements code reuse. To reuse the call, a function needs to be called (invoked) Python function has two parts: a) Function Header : it starts with keyword def , contains the name of the function and optional list of formal parameters, that is, it is not necessary that every function must have parameters. b) Function Block : it is the block after the function header. Function block contains equally indented statements that carry out certain action inside the function. Function block may contain the optional return statement. An example of a user defined function is given below: User Defined Function OR Function Definition def myfactorial(n): fact= for k in range(1,n+1): fact*=k return fact Function Header Function Block Or Function Body Name of the function is myfactorial(), function returns a value and it has a formal parameter n. Function name is myfactorial(). In Python, formal parameter does not have any parameter (this issue will be discussed later). Function’s return statement serves two purposes: a) It terminates the function b) Returns a value to the caller When a function returns a value, the function may be called (invoked) as:
  3. VarName=FunctionName(ActualParaList)
  4. print(FunctionName(ActualParaList)) Complete Python script including user defined function myfactorial() with parameter no. def myfactorial(no): fact= for k in range(1, no+1): fact*=k; return fact n=int(input('Input n? ')) f1=myfactorial(n) f2=myfactorial(n+3) f3=myfactorial( 8 ) print(f1) print(f2) print(f3) print(myfactorial(5)) myfactorial(6) - myfactorial () – user defined function - no – Formal parameter - Function call is: f1=myfactorial(n) f2=myfactorial(n+3) f3=myfactorial( 8 ) print(myfactorial(5)) myfactorial(6) - Actual parameter: 1st call – n (variable) 2nd call – n+3 (expression) 3 rd call – 8 (constant) 4th call – 5 (constant) 5th call – 6 (constant) Running of the Python script produces following outputs : Input n? 7 5040 0320 3628800 120 No output Variables f1 , f2 and f3 stores the return values of myfactorial () for the first call, for the second call and for third call respectively. Values stored in f1 , f2 and f3 are then displayed with print (). Fourth call of the function is directly from print () and it displays the return value of myfactoral (). Last call to myfactorial(6) does not display any output since the return value of the function is discarded.

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 :

  1. A global variable is updated inside a function
  2. A global variable can be created inside a function and can be used in the function and after the function Difference between global variable and local variable Global Variable Local Variable
  • Created outside the function, either before or after a function
  • Crated only inside the function
  • Can be used throughout the program / script • Can be used inside the function Difference between actual parameter and formal parameter Actual Parameter Formal Parameter
  • Used during the function call / invocation • Created in the function header
  • Can be either be variable / expression / constant • Can only be a variable By using global variable inside a function, one can eliminate use of formal parameter in a function. def chkarmstrong(): global 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') n=int(input('Input n? ')) chkarmstrong() def chkpalindrome(): global n s, t=0, n while t: d=t% s=10s+d t//= if s==n: print('Palindrome') else: print('Not Palindrome') n=int(input('Input n? ')) chkpalindrome() Non-recursive code for some important functions are given below: 1!+2!+3!+4!+…+n! def sumofseq(n): s= f= for k in range(1, n+1): f=k 2 !+ 4 !+ 6 !+ 8 !+…+(2n)! def sumofseq(n): s=f= for k in range(1, n+1): t=2k f=(t-1)t

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

  1. So, 7777777777 is displayed. foo('$',15) calls the function with two actual arguments. '$' replaces default value of ch and 12 replaces default value of n. So $$$$$$$$$$$$ is displayed. foo(n=20, ch='@') calls the function with two keyword arguments. '@' replaces default value of ch and 20 replaces default value of n. So @@@@@@@@@@@@@@@ is displayed.