0% found this document useful (0 votes)
5 views48 pages

Unit 2 Part 1 Final

The document explains the concept of functions in Python, detailing their structure, usage, and types of arguments such as default, keyword, positional, and arbitrary arguments. It also covers related topics like return values, recursion, the pass statement, and variable scope. Additionally, it discusses the global keyword and the Python Standard Library, emphasizing the importance of functions for modularity and code reusability.

Uploaded by

collegetrisha24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views48 pages

Unit 2 Part 1 Final

The document explains the concept of functions in Python, detailing their structure, usage, and types of arguments such as default, keyword, positional, and arbitrary arguments. It also covers related topics like return values, recursion, the pass statement, and variable scope. Additionally, it discusses the global keyword and the Python Standard Library, emphasizing the importance of functions for modularity and code reusability.

Uploaded by

collegetrisha24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Functions

Function
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.
 Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead
of writing the same code again and again for different inputs, we can do the function
calls to reuse code contained in it over and over again.
 The use of function is one of the means to achieve modularity and reusability
Arguments and Parametres
 In the above example, the numbers were accepted from the user within the
function itself, but it is also possible for a user defined function to receive values
at the time of being called.
 An argument is a value passed to the function during the function call which is
received in corresponding parameter defined in function header.
Practice Question

 Write a program using a user defined function calcFact() to calculate and display the
factorial of a number num passed as an argument.
 Write a program using a user defined function that accepts the first name and last name
as arguments, concatenate them to get full name and displays the output as:
Hello full name
Type of function argument
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following 4 types of function arguments.

 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)
Default argument

Write a program that accepts numerator and denominator of a fractional number


and calls a user defined function mixedFraction() when the fraction formed is not a proper
fraction. The default value of denominator is 1. The function displays a mixed fraction only
if the fraction formed by the parameters does not evaluate to a whole number.
Default argument
 def mixedFraction(num,deno = 1):
remainder = num % deno
 #check if the fraction does not evaluate to a whole number
 if remainder!= 0:
quotient = int(num/deno)
 print("The mixed fraction=", quotient,"(",remainder, "/",
 deno,")")
 else:
 print("The given fraction evaluates to a whole number")
 #function ends here
Default argument
 num = int(input("Enter the numerator: "))
 deno = int(input("Enter the denominator: "))
 print("You entered:",num,"/",deno)
 if num > deno: #condition to check whether the fraction is
 improper
 mixedFraction(num,deno) #function call
 else:
 print("It is a proper fraction")
 Output:
 Enter the numerator: 17
 Enter the denominator: 2
 You entered: 17 / 2
 The mixed fraction = 8 ( 1 / 2 )
Default argument
Default argument
Keyword Arguments
 The idea is to allow the caller to specify the argument name with values so
that the caller does not need to remember the order of parameters.
Find the output
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname=‘Hello', lastname=‘World')
student(lastname=‘World', firstname=‘Hello')
Positional Arguments
 We used the Position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or value)
is assigned to age.
Find the output
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

# You will get correct output because


# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
Arbitrary Keyword Arguments
 In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a
variable number of arguments to a function using special symbols. There are
two special symbols:

*args in Python (Non-Keyword Arguments)


**kwargs in Python (Keyword Arguments)

 If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
Variable length non-keywords argument
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun(‘Hy', 'Welcome', 'to', ‘India')


Variable length keyword arguments **kwargs
If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.

This way the function will receive a dictionary of arguments, and can access the
items accordingly:
Find the output
# Python program to illustrate
# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in [Link]():
print("%s == %s" % (key, value))

# Driver code
myFun(first=‘Welcome', mid=‘to', last=‘BPIT')
Output
first == Welcome
mid == to
last == BPIT
Passing a List as an Argument
 You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function
Find the output
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
Return Values
To let a function return a value, use the return statement:

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
Recursive Functions in Python
 Recursion in Python refers to when a function calls itself.
 There are many instances when you have to build a recursive function to solve
Mathematical and Recursive Problems.
 Using a recursive function should be done with caution, as a recursive function
can become like a non-terminating loop.
 It is better to check your exit statement while creating a recursive function.
Output
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))
Practice Questions

1. WAP to print Fibonacci series till the user specified number using Recursion.
2. WAP to find power of a number using Recursion.

The pass Statement

 null statement which can be used as a placeholder for future code.


 Suppose we have a loop or a function that is not implemented yet, but we want
to implement it in the future. In such cases, we can use t
 n=10
 If n>10
 pass
 Print(“hello”)
 However, nothing happens when the pass is executed. It results in no operation
(NOP).
The pass Statement

 It is a null operation; when it is executed, nothing happens. It is useful as a placeholder


when a statement is required syntactically, but no code needs to be executed. It is
commonly used in situations like:
 Empty Functions or Classes: When defining a function or class but the
implementation is deferred.
 Conditional Statements: in if, else blocks when no action is required.
 Loops: where the body is intentionally left empty
 Exception handling: in try… block where certain exceptions are to be ignored.
The pass Statement

 Def func():
 pass
 This works similar to an empty function .
None keyword
 None is used to define a null value or Null object in Python. It is not the same
as an empty string, a False, or a zero.
 It is a data type of the class NoneType object.
 Python None is the function returns when there are no return statements.
Null vs None
 None – None is an instance of the NoneType object type. And it is a particular
variable that has no objective value. While new NoneType objects cannot be
generated, None can be assigned to any variable.

 Null – There is no null in Python, we can use None instead of using null values.
Python null is refer to None which is instance of the NoneType object type
 x = None

if x is None:
print("x is None")
Python Function within Functions
 A function that is defined inside another function is known as the inner
function or nested function.
 Nested functions can access variables of the enclosing scope. Inner functions
are used so that they can be protected from everything happening outside the
function.
Find the output
# Python program to
# demonstrate accessing of
# variables of nested functions

def f1():
s = ‘hello'

def f2():
print(s)

f2()

# Driver's code
f1()
Output
Hello
Scope of a Variable
 The part of the program where a variable is accessible can be defined as the scope of that
variable. A variable can have one of the following two scopes:
 A variable that has global scope is known as a global variable and a variable that has a
local scope is known as a local variable.
Global Variable
 In Python, a variable that is defined outside any function or any block is known as a
global variable. It can be accessed in any functions defined onwards. Any change made
to the global variable will impact all the functions in the program where that variable
can be accessed.
Local Variable
 A variable that is defined inside any function or a block is known as a local variable. It
can be accessed only in the function or a block where it is defined. It exists only till the
function executes.
Scope of a Variable
Python Standard Library
 Python has a very extensive standard library. It is a collection of many built in functions
that can be called in the program as and when required, thus saving programmer’s time
of creating those commonly used functions everytime.
Python Standard Library
Global Keyword
 If you need to create a global variable, but are stuck in the local scope, you
can use the global keyword.

 The global keyword makes the variable global.


Find the output
def myfunc():
global x
x = 300

myfunc()

print(x)
Also, use the global keyword if you want to make a change to a global variable
inside a function.

x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)
Output
200

You might also like