FUCTIONS IN PYTHON CLASS 12 COMPUTER SCIENCE

 What is a function?

function is a named set of code written to carry out a specific task. A function is a block of organized, reusable code which is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse. 

Another definition of function is;

Large programs are generally avoided because it is difficult to manage a single list of instructions. Thus, a large program is broken down into smaller units known as functions.

 A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that are sent to the function when it is called.


 Advantages of function?

  • Increase code reusability 
  • Reduce program complexity 
  • Increase the readability of programs 
  • Ease of program updation 

Flow of Execution in a function call

The flow of Execution refers to the order  in which statements are executed during program run .



1->3->4->5->2->5
2->5->6->7->2->3->4->7->8

in the above program, the python compiler will execute line number 1, and then the main body of the program  which is line 5,6,7, then function called again line 2 then body of the function line 4,5, then take return value of sum line 7 then print line 8. 
--------------------------------------------------------------------------------------------------------------------------- 
Consider the following code and write the flow of execution for this. Line numbers have been given for your reference.
1. def power(b, p):
2.  y = b ** p
3.  return y
4. 
5. def calcSquare(x):
6.  a = power(x, 2)
7.  return a
8.
9.  n = 5
10. result = calcSquare(n)
11. print(result)

Answer

The flow of execution for the above program is as follows :

1 → 5 → 9 → 10 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 10 → 11

Types of function 

  • Built-in-function 
  • Function in module 
  • User define function 

Example of built-in function:

1. len() :- Returns the length of an object



Output is:

2. int(): Returns an integer number
3. input(): Take the input from the console.
4. print(): Prints to the standard output device
5. range(): Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
6. sum() Sums the items of an iterator

Function in Module 

Python offers many built-in modules. Some of the most commonly used modules are listed below.
  1.  Math module 
  2. Random Module 
  3. Statistics Module 
for using any module you have to import that module and then call by its function/method name 
example.                                                                    









output













































User Defined Function 

any user can define his own function by using the below syntax.
Syntax 
def  function_name ([Parameters]): #Function Definition 
                Statement-1
                Statement-2  #Function Body 
                Statement-n
function_name([Argument]) # Function Calling part 
Arguments: The values that are declared within a function when the function is called are known as an argument.
Parameter: The variables that are defined when the function is declared are known as parameters.

we can define our function in four different ways.
1. function with arguments with return(non-void function) values.
2. function without argument with return (non-void function)values.
3. function with arguments without (void) return values.
4. function without arguments without (void) return values.





python Function Example







 
 
 
 
 
 
Function Not Returning any Value (Void Function) 
  function which does not return any value to the function call is called void function  
Example 
def greet():
    print("Helloz")
    return 
greet() 
 
Function with return any value ( Non - Void Function) 
def Cal_To(x,y,z):
    return x*x,y/2,z**3
c,b,n=Cal_To(30,40,80)
print(c,b,n) 

Passing Parameters in Python

as you know function calls must provide all values as required by the function definition. if a function has three parameters in its header then the function call should also pass three values.
Python supports three types of formal arguments/parameters.
1. Positional arguments (Required arguments)
2. Default arguments 
3, Keyword (or named )arguments

Positional Arguments

In positional arguments, you need to match the number of arguments with the number of parameters.
Example:
python Function Example





In the above code, I have not passed any values in function calling, here I have to pass three different values for correct arguments and parameter matching.
if you pass only two arguments then also these errors will come again.






















Now this is an example of correct positional arguments where we are sending different values with three different calls.





















Default Arguments 

Python allows us to assign default values(s) to a function's parameters (s) which is useful in case a matching argument is not passed in the function call statement. The default values are specified in the function header of the function definition.
Example of Default Argument











Example -2


















Keyword (Named) Arguments

To have complete control and flexibility over the values sent as arguments for the corresponding parameters, python offers another type of argument; keyword arguments.

you can provide any arguments in any order when you call a function.
Example :
interest(prin=2000,time=2, rate=0.10)
interest(rate=0.10, prin=2000,time=2)
interest(time=2,rate=0.10, prin=2000)
 Program for Keyword Argument
































Rules for combining all three types of Arguments

Python states that in a function call statement :
  • An arguments list must first contain positional(requited) arguments followed by any keyword argument.
  • Keyword arguments should be taken from the required arguments preferably.
  • You cannot specify a value for an argument more than once.
positional argument in python











positional argument in python








This is the correct Argument position, after the position argument you are allowed to put the keyword.
 argument.







Scope of  Variables 

There are two main scopes of variables in Python. first one is local scope and the second one is global scope. take an example as you have a tap in your home where no one can access your tab it is private to you and is locally accessible for you only. It's a local scope as your tap is on your premises.
where a tap is located beside of road which is available for all made by govt. this type of tap is global scope and can be accessed by all people. same as Python we have two scopes of variables.

1. Global Scope 
2. Local Scope 

Global Scope: A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.

Example of Global Scope 
Global scope of variable in python
Here you can see the Global Variable is b because b is defined outside of the function but the value of b is accessible to another function named test2































You can also make any variable global using the global keyword .
Use of Global keyword
        


  






Here an example of global variable which is used to make a keyword global to add another value to it .






Local Scope: A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
Example of local variable

Here x is local and its scope is also local you can not access the x value in another function.













Here you can see myfunc() is working as x is a local variable for and output 300 is coming but in the second function named myfunc2() an error has occurred because x is a locally defined in myfunc() only .
How you can solve this error ? think and tell .

See the difference between
two function . 
                            




-----------------------------------------------------------------------------------------------

What will be the output of following program ?

num = 1
def myfunc():
    num = 10
    return num
print(num)
print(myfunc())
print(num)
Output
1
10
1
----------------------------------------------------------------------------------------- 

What will be the output of following program ?

num = 1
def myfunc():
    global num
    num = 10
    return num
print(num)
print(myfunc())
print(num)

Answer

10
10 
-----------------------------------------------------------------------
Program for a calculator using User user-defined function.
import math
def add ( ) :
       x=int(input("Enter the first  :"))
       y=int(input("enter the 2nd number:"))
       sum=x+y
       print ("the addition of two numbers:", sum)
      
def multiply ( ) :
       x=int(input("Enter the first  :"))
       y=int(input("enter the 2nd number:"))
       mul=x*y
       print ("the multiply of two numbers:", mul)
def divide ( ) :
       x=int(input("Enter the first  :"))
       y=int(input("enter the 2nd number:"))
       div=x/y
       print ("the divide of two numbers:", div)
def sqrt2():
       x=int(input("Enter the Value for squire root  :"))
       print(math.sqrt(x))
n=int(input("enter how many time u want to calculate  :"))
for i in range(n):
        
    ch =input("enter your choice 1 for +, 2 for *, 3 for / ,4 for squire root:")
    if ch=='1':
        add()
    elif ch=='2':
        multiply()
    elif ch=='3':
        divide()
    elif ch=='4':
        sqrt2()
           
       
    else:
        print("wrong choice")

Exam Question from Function 

Write a user defined function in Python named Puzzle (W, N) which takes the argument w as an English word and as an integer and returns the string where every Nth alphabet of the word w is replaced with an underscore ("_").

For example: if w contains the word "TELEVISION" and N is 3, then the function should return the string "TE_EV_SI_N". Likewise for the word "TELEVISION" if N is 4, then the function should return "TEL_VIS_ON".

Answer :

word="TELEVISION"
def Puzzle(W,N):
    NW=""
    c=1
    for ch in W:
        if c!=N:
            NW +=ch
            c+=1
        else:
            NW+="_"
            c=1
    return NW
print(Puzzle(word,3))
print(Puzzle(word,4))
print(Puzzle(word,5))



Answer:

def show_Grade(S):
    for k in S:
        sum=0
        for i in range(3):
            sum+=S[k][i]
            if sum/3>90:
                grade="A"
            elif sum/3>=60:
                grade="B"
            else:
                grade="C"
        print(k,"_",grade)  
S1={"Amit":[92,86,64],"NAGNA":[65,42,43],"DAVID":[92,90,88]}
show_Grade(S1)      

Write the definition of a method/function SearchOut (Teachers, Name) to search for TName from a list Teachers, and display the position of its presence.

For example:

If the Teachers contain ["Ankit", "Siddharth", "Rahul", "Sangeeta", "rahul"] and TName contains "Rahul"

The function should display

Rahul at 2

rahul at 4

def SearchOut(Teachers,TName):
    for index ,i in enumerate(Teachers):
        if i==TName:
            print(f"{TName} at {index}")
T1=["Ankit","Siddharth","Rahul","Sangeeta","rahul"]
SearchOut(T1,'Rahul')
SearchOut(T1,'rahul')
'''
In Python, the enumerate() function is a built-in function
 that adds a counter to an iterable and returns
 it as an enumerate object. This can be particularly
 useful when you need both the item and its index while
 looping over an iterable
Example

Here's how you can use enumerate() with a list:

colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
This will output:

0 red
1 green
2 blue

'''
unc_Teachers.py" Rahul at 2 rahul at 4 PS C:\Users\MD SAKIB AHSAN>

Question :Predict the the output of the following code ?

 

def Total(Num=10):

    sum=0

    for c in range(1,Num+1):

        if c%2!=0:

            continue

        sum+=c

    return sum

print(Total(4) ,end="$")

print("\n")

print(Total() )

 

Answer :

                6$

                            30

Question : Write the output of the code given below :

a =30

def call (x) :

global a

if a%2==0:

x + = a

else:

x - = a

return x

x=20

print(call(35),end="#")

print(call(40),end= "@")

 

Answer :

65#70@ 

Predict the output of the following code?

s="India Growing"

n=len(s)

m=" "

for i in range(0,n):

    if (s[i]>="a" and s[i]<="m"):

        m=m+s[i].upper()

    elif (s[i]>="o" and s[i]<="z"):

        m=m+s[i-1]

    elif (s[i].isupper()):

        m=m+s[i].lower()

    else:

        m=m+"@"

print(m)

Answer :

i@DIA@gGroI@G 

Write the output of the code given below :

def short_sub (lst,n) :

    for i in range (0,n) :

if len (lst)>4:

lst [i]=lst [i ] + lst[i]

else:

lst[i]=lst[i]

subject=['CS', 'HINDI', 'PHYSICS', 'CHEMISTRY', 'MATHS']

short_sub (subject, 5)

print (subject)

 

Answer:

['CSCS', 'HINDIHINDI', 'PHYSICSPHYSICS', 'CHEMISTRYCHEMISTRY', 'MATHSMATHS']
 

 


 












Predict the output of the following code:
 
s="Racecar Car Radar"
L=s.split()
for w in L:
    x=w.upper()
    if x==x[::-1]:
        for i in x:
            print(i,end="*")
    else:
        for i in w:
            print(i,end="#")
    print()
Answer :
 
R*A*C*E*C*A*R*
C#a#r#
R*A*D*A*R*
 


 Predict the output of the following code:
 
 
 the new string is : g0n2Ge
Find the output of the given below :
 
x=25
def modify(s,c=2):
    global x
    for a in 'QWEiop':
         x=x//5
         print(a.upper() ,'#',c*x)
    else:
        print(a)
        x+=5
        print(a.lower(),'@',c+x)
string='we'
modify(string,10)
print(x,'$',string)
---------------------------------------------------------------------------------------------

Write a program with a function that takes an integer and prints the number that follows after it. Call the function with these arguments :

4, 6, 8, 2 + 1, 4 - 3 * 2, -3 -2

Answer

1. def print_number(number):
2.    next_number = number + 1
3.    print("The number following", number, "is", next_number)
4. print_number(4)
5. print_number(6)
6. print_number(8)
7. print_number(2 + 1)
8. print_number(4 - 3 * 2)
9. print_number(- 3 - 2)
Output
The print_number following 4 is 5
The print_number following 6 is 7
The print_number following 8 is 9
The print_number following 3 is 4
The print_number following -2 is -1
The print_number following -5 is -4


Comments