Function
By: Deepak Kumar
PGT(CS)
Contents
Functions
arguments and parameters
flow of execution
scope of a variable
PYQ
Introduction
A function is a reusable block of code that performs a specific task. It takes inputs (known as
parameters or arguments), processes them, and can return an output. Functions help organize
code into manageable sections, making it easier to read, maintain, and reuse.
Basic Structure of a Function
In most programming languages, the structure includes:
•Function Name: Identifies the function.
•Parameters: Inputs to the function (optional).
•Function Body: The code that defines what the function does.
•Return Statement: Outputs a value (optional).
Example (in Python)
def add(a, b):
return a + b
5
Applications of Functions
Functions are widely used in programming for various applications:
1.Modularity:
1. Breaks down complex problems into smaller, manageable parts.
2. Each function can be developed, tested, and debugged independently.
2.Code Reusability:
1. Allows the same code to be reused multiple times without rewriting it.
2. Enhances productivity and reduces errors.
3.Abstraction:
1. Hides complex implementation details from the user.
2. Users can utilize functions without needing to understand their internal workings.
4.Improved Readability:
1. Organizes code into logical sections, making it easier to understand.
2. Well-named functions can convey their purpose clearly.
5.Facilitates Testing and Debugging:
1. Functions can be tested independently, making it easier to isolate and fix issues.
6.Encapsulation:
1. Allows related data and functions to be packaged together, especially in object-oriented
programming.
7.Recursion:
1. Functions can call themselves to solve problems that can be broken down into smaller,
similar problems (e.g., factorial calculation, Fibonacci series).
Real-World Applications
•Data Processing: Functions are used to process and manipulate data in applications
like data analysis and machine learning.
•Web Development: Functions handle specific tasks, such as user authentication,
database queries, and form processing.
•Game Development: Functions manage game mechanics, character behaviors, and
user interactions.
•API Development: Functions serve as endpoints that perform actions based on
requests from clients.
7
8
Built-in Functions: Pre-defined functions provided by the programming language.
Examples:
•print() , len() , max()n , min()
Usage: Commonly used for performing standard operations without needing to define them.
Functions Defined in a Module: Functions that are part of a module/library that can be imported and used in a progra
Examples:
•Functions from the math module (e.g., math.sqrt(), math.factorial())
•Functions from third-party libraries (e.g., numpy, pandas)
Usage: Enhance functionality by leveraging external code.
User-Defined Functions: Functions created by the programmer to perform specific tasks.
Syntax (in Python):
def function_name(parameters):
# function body
return value
Creating User-Defined Functions
•Steps to Create:
1.Use the def keyword.
2.Provide a name for the function.
3.Specify parameters (if any) in parentheses.
4.Write the function body.
5.Use the return statement to return a value (optional).
def add_numbers(a, b):
sum = a+b
return sum
10
Arguments and
Parameters
11
•Parameters: Variables listed in the function definition.
•Arguments: Actual values passed to the function when called.
def add_numbers(a, b): # Parameters
sum = a+b
return sum
add_number(3 ,6) # Arguments
12
Types of Parameters:
•Positional Parameters: Must be passed in the correct order.
•Default Parameters: Have default values if no argument is provided.
1. Positional Parameters: Positional parameters are variables defined in a function that must be supplied
in a specific order when the function is called. The values passed to these parameters are assigned
based on their position.
Characteristics:
•The order of arguments matters; they must be passed in the same order as the parameters are defined in
the function.
•If fewer arguments are provided than there are parameters, it will lead to a TypeError.
def greet(first_name, last_name):
return f"Namaste, {first_name} {last_name}!" # Calling with positional
arguments print(greet("Rahul", "Sharma")) # Output:
Namaste, Rahul Sharma!
print(greet("Anjali", "Patel")) # Output: Namaste, Anjali
Patel!
13
2. Default Parameters: Default parameters allow you to define a default value for a parameter in
a function. If an argument is not provided for that parameter when the function is called, the
default value is used.
Characteristics:
•Default parameters can be useful for creating functions with optional arguments.
•Default parameters must be defined after any positional parameters in the function definition.
•If an argument is provided for a default parameter, that value will override the default.
def order_chai(size, type="masala"):
return f"A {size} cup of {type} chai is on its way!" # Calling with and without the default
argument
print(order_chai("medium")) # Output: A medium cup of masala chai is on
its way!
print(order_chai("large", "ginger")) # Output: A large cup of ginger chai is on its
way!
14
Combining Positional and Default Parameters
def order_food(dish, quantity=1):
return f"Order placed for {quantity} plate(s) of {dish}.“
print(order_food("Biryani")) # Output: Order placed for 1 plate(s) of Biryani.
print(order_food("Paneer Tikka", 2)) # Output: Order placed for 2 plate(s) of Paneer Tik
15
Summary
•Positional Parameters: Like addressing someone by their first and last names, requiring
them in the correct order.
•Default Parameters: Like ordering a standard type of chai, but allowing customization if
desired.
16
Flow of Execution
The program executes the main code and calls functions as needed.
•When a function is called:
1.Control is transferred to the function.
2.The function executes its code.
3.The function returns control back to the caller.
17
Scope of a Variable
Global Scope: Variables defined outside any function, accessible from anywhere in the module.
Example:
x = 10 # Global variable
def display():
print(x)
display() # Output: 10
Local Scope: Variables defined within a function, accessible only within that function.
Example:
def example():
y = 5 # Local variable
print(y)
example() # Output: 5 #
print(y) # Raises an error: NameError
18
Scope Resolution: Local variables take precedence over global variables within the same
function.
Use the global keyword to modify a global variable within a function.
Example
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # Output: 1
19
PYQ
Q1. State True or False :
While defining a function in Python, the positional parameters in the function header must always be
written after the default parameters
Q2. Observe the given Python code carefully :
a=20
def convert(a):
b=20
a=a+b
convert(10)
print(a)
Select the correct output from the given options :
(a) 10 (b) 20 (c) 30 (d) Error
20
PYQ
Q3. The code given below accepts five numbers and displays whether they are
even or odd: Observe the following code carefully and rewrite it after removing all
syntax and logical errors :
Underline all the corrections made.
def EvenOdd()
for i in range(5) :
num=int(input("Enter a number")
if num/2==0:
print("Even")
else:
print("Odd")
EvenOdd()
21
PYQ
Q4. Write a user defined function in Python named showGrades(S) which takes the dictionary S as an
argument. The dictionary, S contains Name:[Eng,Math,Science] as key:value pairs. The function displays the
corresponding grade obtained by the students according to the following grading
For example : Consider the following dictionary
S={"AMIT":[92,86,64],"NAGMA":[65,42,43],"DAVID":[92,90,88]}
The output should be :
AMIT – B
NAGMA – C
DAVID – A
22
PYQ
def showGrades(S):
for K, V in S. items():
if sum(V)/3>=90:
Grade="A"
elif sum(V)/3>=60:
Grade="B"
else:
Grade="C"
print(K,"–",Grade)
S={"AMIT":[92,86,64],"NAGMA":[65,42,43],"DAVID":[92,90,88]}
showGrades(S)
23
PYQ
Q5. Write a user defined function in Python named Puzzle(W,N) which takes the argument W as an English
word and N as an integer and returns the string where every N th 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".
24
PYQ
def Puzzle(W,N):
W1=""
for i in range(len(W)):
if (i+1)%N==0:
W1=W1+"_"
else:
W1=W1+W[i]
return W1
print(Puzzle("TELEVISION",4))
25
PYQ
Q6. Predict the output of the following code :
def callon(b=20,a=10) :
b=b+a
a=b-a
print(b, "#" , a )
return b
x=100
y=200
x=callon(x,y)
print (x,"@", y)
y=callon(y)
print (x,"@",y)
26
PYQ
300#100
300@200
210#200
300@210
Thank you

Function oneshot with python programming .pptx

  • 1.
  • 2.
    Contents Functions arguments and parameters flowof execution scope of a variable PYQ
  • 3.
  • 4.
    A function isa reusable block of code that performs a specific task. It takes inputs (known as parameters or arguments), processes them, and can return an output. Functions help organize code into manageable sections, making it easier to read, maintain, and reuse. Basic Structure of a Function In most programming languages, the structure includes: •Function Name: Identifies the function. •Parameters: Inputs to the function (optional). •Function Body: The code that defines what the function does. •Return Statement: Outputs a value (optional). Example (in Python) def add(a, b): return a + b
  • 5.
    5 Applications of Functions Functionsare widely used in programming for various applications: 1.Modularity: 1. Breaks down complex problems into smaller, manageable parts. 2. Each function can be developed, tested, and debugged independently. 2.Code Reusability: 1. Allows the same code to be reused multiple times without rewriting it. 2. Enhances productivity and reduces errors. 3.Abstraction: 1. Hides complex implementation details from the user. 2. Users can utilize functions without needing to understand their internal workings. 4.Improved Readability: 1. Organizes code into logical sections, making it easier to understand. 2. Well-named functions can convey their purpose clearly. 5.Facilitates Testing and Debugging: 1. Functions can be tested independently, making it easier to isolate and fix issues. 6.Encapsulation: 1. Allows related data and functions to be packaged together, especially in object-oriented programming. 7.Recursion: 1. Functions can call themselves to solve problems that can be broken down into smaller, similar problems (e.g., factorial calculation, Fibonacci series).
  • 6.
    Real-World Applications •Data Processing:Functions are used to process and manipulate data in applications like data analysis and machine learning. •Web Development: Functions handle specific tasks, such as user authentication, database queries, and form processing. •Game Development: Functions manage game mechanics, character behaviors, and user interactions. •API Development: Functions serve as endpoints that perform actions based on requests from clients.
  • 7.
  • 8.
    8 Built-in Functions: Pre-definedfunctions provided by the programming language. Examples: •print() , len() , max()n , min() Usage: Commonly used for performing standard operations without needing to define them. Functions Defined in a Module: Functions that are part of a module/library that can be imported and used in a progra Examples: •Functions from the math module (e.g., math.sqrt(), math.factorial()) •Functions from third-party libraries (e.g., numpy, pandas) Usage: Enhance functionality by leveraging external code. User-Defined Functions: Functions created by the programmer to perform specific tasks. Syntax (in Python): def function_name(parameters): # function body return value
  • 9.
    Creating User-Defined Functions •Stepsto Create: 1.Use the def keyword. 2.Provide a name for the function. 3.Specify parameters (if any) in parentheses. 4.Write the function body. 5.Use the return statement to return a value (optional). def add_numbers(a, b): sum = a+b return sum
  • 10.
  • 11.
    11 •Parameters: Variables listedin the function definition. •Arguments: Actual values passed to the function when called. def add_numbers(a, b): # Parameters sum = a+b return sum add_number(3 ,6) # Arguments
  • 12.
    12 Types of Parameters: •PositionalParameters: Must be passed in the correct order. •Default Parameters: Have default values if no argument is provided. 1. Positional Parameters: Positional parameters are variables defined in a function that must be supplied in a specific order when the function is called. The values passed to these parameters are assigned based on their position. Characteristics: •The order of arguments matters; they must be passed in the same order as the parameters are defined in the function. •If fewer arguments are provided than there are parameters, it will lead to a TypeError. def greet(first_name, last_name): return f"Namaste, {first_name} {last_name}!" # Calling with positional arguments print(greet("Rahul", "Sharma")) # Output: Namaste, Rahul Sharma! print(greet("Anjali", "Patel")) # Output: Namaste, Anjali Patel!
  • 13.
    13 2. Default Parameters:Default parameters allow you to define a default value for a parameter in a function. If an argument is not provided for that parameter when the function is called, the default value is used. Characteristics: •Default parameters can be useful for creating functions with optional arguments. •Default parameters must be defined after any positional parameters in the function definition. •If an argument is provided for a default parameter, that value will override the default. def order_chai(size, type="masala"): return f"A {size} cup of {type} chai is on its way!" # Calling with and without the default argument print(order_chai("medium")) # Output: A medium cup of masala chai is on its way! print(order_chai("large", "ginger")) # Output: A large cup of ginger chai is on its way!
  • 14.
    14 Combining Positional andDefault Parameters def order_food(dish, quantity=1): return f"Order placed for {quantity} plate(s) of {dish}.“ print(order_food("Biryani")) # Output: Order placed for 1 plate(s) of Biryani. print(order_food("Paneer Tikka", 2)) # Output: Order placed for 2 plate(s) of Paneer Tik
  • 15.
    15 Summary •Positional Parameters: Likeaddressing someone by their first and last names, requiring them in the correct order. •Default Parameters: Like ordering a standard type of chai, but allowing customization if desired.
  • 16.
    16 Flow of Execution Theprogram executes the main code and calls functions as needed. •When a function is called: 1.Control is transferred to the function. 2.The function executes its code. 3.The function returns control back to the caller.
  • 17.
    17 Scope of aVariable Global Scope: Variables defined outside any function, accessible from anywhere in the module. Example: x = 10 # Global variable def display(): print(x) display() # Output: 10 Local Scope: Variables defined within a function, accessible only within that function. Example: def example(): y = 5 # Local variable print(y) example() # Output: 5 # print(y) # Raises an error: NameError
  • 18.
    18 Scope Resolution: Localvariables take precedence over global variables within the same function. Use the global keyword to modify a global variable within a function. Example counter = 0 def increment(): global counter counter += 1 increment() print(counter) # Output: 1
  • 19.
    19 PYQ Q1. State Trueor False : While defining a function in Python, the positional parameters in the function header must always be written after the default parameters Q2. Observe the given Python code carefully : a=20 def convert(a): b=20 a=a+b convert(10) print(a) Select the correct output from the given options : (a) 10 (b) 20 (c) 30 (d) Error
  • 20.
    20 PYQ Q3. The codegiven below accepts five numbers and displays whether they are even or odd: Observe the following code carefully and rewrite it after removing all syntax and logical errors : Underline all the corrections made. def EvenOdd() for i in range(5) : num=int(input("Enter a number") if num/2==0: print("Even") else: print("Odd") EvenOdd()
  • 21.
    21 PYQ Q4. Write auser defined function in Python named showGrades(S) which takes the dictionary S as an argument. The dictionary, S contains Name:[Eng,Math,Science] as key:value pairs. The function displays the corresponding grade obtained by the students according to the following grading For example : Consider the following dictionary S={"AMIT":[92,86,64],"NAGMA":[65,42,43],"DAVID":[92,90,88]} The output should be : AMIT – B NAGMA – C DAVID – A
  • 22.
    22 PYQ def showGrades(S): for K,V in S. items(): if sum(V)/3>=90: Grade="A" elif sum(V)/3>=60: Grade="B" else: Grade="C" print(K,"–",Grade) S={"AMIT":[92,86,64],"NAGMA":[65,42,43],"DAVID":[92,90,88]} showGrades(S)
  • 23.
    23 PYQ Q5. Write auser defined function in Python named Puzzle(W,N) which takes the argument W as an English word and N as an integer and returns the string where every N th 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".
  • 24.
    24 PYQ def Puzzle(W,N): W1="" for iin range(len(W)): if (i+1)%N==0: W1=W1+"_" else: W1=W1+W[i] return W1 print(Puzzle("TELEVISION",4))
  • 25.
    25 PYQ Q6. Predict theoutput of the following code : def callon(b=20,a=10) : b=b+a a=b-a print(b, "#" , a ) return b x=100 y=200 x=callon(x,y) print (x,"@", y) y=callon(y) print (x,"@",y)
  • 26.
  • 27.