[Go to site: main page, start]

0% found this document useful (0 votes)
2 views47 pages

Functions in Python

The document provides an overview of functions in Python, including how to define and call them, the difference between global and local variables, and the use of parameters. It also covers advanced topics such as keyword arguments, default argument values, returning values, and using lambda functions, as well as built-in functions like map(), filter(), and reduce(). Additionally, it includes examples and assignments for practice.

Uploaded by

dextrojha
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)
2 views47 pages

Functions in Python

The document provides an overview of functions in Python, including how to define and call them, the difference between global and local variables, and the use of parameters. It also covers advanced topics such as keyword arguments, default argument values, returning values, and using lambda functions, as well as built-in functions like map(), filter(), and reduce(). Additionally, it includes examples and assignments for practice.

Uploaded by

dextrojha
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

⚫ A function is a block of instructions that performs an action


and, once defined, can be reused. Functions make code
more modular, allowing you to use the same code over and
over again.

⚫ Python has a number of built-in functions that you may be


familiar with, including:

⚫ print() which will print an object to the terminal


⚫ int() which will convert a string or number data type to an
integer data type
⚫ len() which returns the length of an object

⚫ Function names include parentheses and may or may not


include parameters.
⚫ Defining a Function

⚫ A function is defined by using the def keyword, followed by


a name of your choice, followed by a set of parentheses
which hold any parameters the function will take (they can
be empty), and ending with a colon.
⚫ In this case, we’ll define a function named hello():

def hello():
print("Hello, World!")

⚫ Our function is now fully defined, but if we run the program


at this point, nothing will happen since we didn’t call the
function.
⚫ So, outside of our defined function block, let’s call the
function with hello():

def hello():
print("Hello, World!")
hello()

⚫ After running the program, You should receive the


following output:

⚫ Output
Hello, World!
def add():
a=int(input(“enter number 1”))
B=int(input(“enter number 2”))
c=a+b
print ( c )
add()
Global & Local Variables
There are two types of variables: global variables and
local variables.
The scope of global variables is the entire program
whereas the scope of local variable is limited to the
function where it is defined.
def func1():
x = "Python"
print(x)
print(s)
s = "Tutorialspoint"
print(s)
func1()
print(x)
output
Tutorialspoint
Python
Tutorialspoint
Traceback (most recent call last):
File "C:/Users/SONALI/Desktop/Python
programs/global [Link]", line 18, in
<module>
print(x)
NameError: name 'x' is not defined
x is a local variable whereas s is a global
variable.
we can access the local variable only within
the function it is defined (func1() above) and
trying to call local variable outside its
scope(func1()) will throw an Error.
However, we can call global variable
anywhere in the program including functions
(func()) defined in the program.
def func1():
x = "Python"
s="hello"
print(x)
print(s)
s = "Tutorialspoint"
print(s)
func1()
print(x)
Tutorialspoint
Python
hello
Traceback (most recent call last):
File "C:/Users/SONALI/Desktop/Python
programs/global [Link]", line 18, in
<module>
print(x)
NameError: name 'x' is not defined
Global variables
A global variable can be used anywhere in the
program as its scope is the entire program.
def func():
global z
z=25
print(z)
z=20
print(z)
func()
print(z)
Output
20
25
25
The global variable value is changed for the entire
program.
Working with Parameters
A parameter is a named entity in a function definition,
specifying an argument that the function can accept.
def add_numbers(x, y, z):
a=x+y
b=x+z
c=y+z
print(a, b, c)
add_numbers(1, 2, 3)
We passed the number 1 in for the x parameter, 2 in
for the y parameter, and 3 in for the z parameter.
These values correspond with each parameter in the
order they are given.
The program is essentially doing the following math
based on the values we passed to the parameters:
a=1+2
b=1+3
c=2+3
Output
345
Keyword Arguments
In addition to calling parameters in order, you can use
keyword arguments in a function call, in which the caller
identifies the arguments by the parameter name.
When you use keyword arguments, you can use parameters
out of order because the Python interpreter will use the
keywords provided to match the values to the parameters.
def profile_info(username, followers):
print("Username: " , username)
print("Followers: " , followers)
# Call function with parameters assigned as above
profile_info(“Mohan", 945)
# Call function with keyword arguments
profile_info(followers=342, username=“Rohan")
Output
Username: Mohan
Followers: 945
Username: Rohan
Followers: 342
Default Argument Values
We can also provide default values for one or both of
the parameters. Let’s create a default value for the
followers parameter with a value of 1:
def profile_info(username, followers=1):
print("Username: " , username)
print("Followers: " , followers)
profile_info(username=“Sham")
profile_info(followers=945, username=“Nishant")
Output
Username: Sham
Followers: 1
Username: Nishant
Followers: 945
Providing default parameters with values can
let us skip defining values for each argument
that already has a default.
Returning a Value
You can pass a parameter value into a function, and a function can
also produce a value.
A function can produce a value with the return statement, which will
exit a function and optionally pass an expression back to the caller.
If you use a return statement with no arguments, the function will
return None.
we’ll create a program that squares the parameter x and returns the
variable y. We issue a call to print the result variable, which is
formed by running the square() function with 3 passed into it.
def square(x):
y = x ** 2
return y
result = square(3)
print(result)
Output
9
Returning multiple values
def add_numbers(x, y, z):
a=x+y
b=x+z
c=y+z
return a, b, c
sums = add_numbers(1, 2, 3)
a,b,c=add_numbers(1, 2, 3)
print(sums)
print(a,b,c)

Output
(3, 4, 5)
345
Passing a List as an Argument
You can send any data types of argument to
a function (string, integer, list, dictionary
etc.), and it will be treated as the same data
type inside the function.
E.g. if you send a List as an argument, it will
still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Passing a tuple to a function
def tupleArg(inputTuple):
for i in inputTuple:
print(i)
print("Tuple argument passed as input to the
function is: ", inputTuple)
a=(1, 2, 3)
tupleArg(a)
Passing a Set to a function
def SetArgs(inputSet):
for i in inputSet:
print(i)
a={1,2,3,4,5}
SetArgs(a)
Passing a dictionary to a function
def func(d):
for i,j in [Link]():
print(i,j)
D = {'a':1, 'b':2, 'c':3}
func(D)
Assignments
• Write a Python function to find the Max of three numbers
• Write a Python program to reverse a string.
Sample String : "1234abcd"
Expected Output : "dcba4321"
• Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20
• Pass the following dictionary to a function and print the
details of country “India”.
Country_details = { "name1":[ "Germany", "83 million", "Berlin",
"Euro“],”name2”:[“India”,”1400 million”,”New
Delhi”,”Rupees”,”name3”:[“USA”,”332 million”,”Washington
DC”,”Dollar”}
Recursive function
In programming terms a recursive function can be defined as
a routine that calls itself directly or indirectly.
# Recursive function to calculate factorial
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
num = 7
print("The factorial of ",num," is ",factorial(num))
Output
The factorial of 7 is 5040
#Recursive function to calculate sum of n numbers
def sum(n):
if n != 0:
return n+sum(n-1)
else:
return 1
num = int(input("Enter a number: "))
result=sum(num)
print("The sum is: ", result)

Output
Enter a number: 10
The sum is: 55
Assignments (Recursion)
Program to check whether a number is prime
or not
To find LCM of two numbers using recursion
To count number of digits using recursion
To find number is even or odd
To convert a decimal number to binary
Lambda function

⚫ Shorthand version of def statement, useful


for “inlining” functions and other situations
where it's convenient to keep the code of the
function close to where it's needed
⚫ Can only contain an expression in the
function definition, not a block of statements
Lambda example
def sum(x,y):
return x+y
print(sum(1,2))

Output
3
Alternative way
sum2 = lambda x, y: x+y
print(sum2(1,2))
Output
3
A lambda function can take any number of
arguments, but can only have one expression
Syntax
lambda arguments : expression

The expression is executed and the result is


returned:

Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))
Map() function
map() function returns a map object(which is an
iterator) of the results after applying the given
function to each item of a given iterable (list, tuple
etc.)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each
element of given iterable.
iter : It is a iterable which is to be mapped.
, 8]

def addition(n):
return n + n

# We double all numbers using map()


numbers = (1, 2, 3, 4)
result = map(addition,numbers)
print(list(result))

Output :
[2, 4, 6, 8]
map
⚫ Map calls a given function on every element of a
sequence
def double(x):
return x*2
a = [1, 2, 3]
print (list(map(double, a)))
output
[2, 4, 6]
Alternatively:
a = [1, 2, 3]
print (list(map((lambda x: x*2), a)))
output
[2, 4, 6]
Normal code writing to uppercase the list
items

my_pets = ['alfred', 'tabitha', 'william', 'arla']


uppered_pets = []
for pet in my_pets:
pet = [Link]()
uppered_pets.append(pet)
print(uppered_pets)

Output
['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']
Same above code using map function
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(map([Link], my_pets))
print(uppered_pets)

Output
['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']
Map Example
1nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0,3]
2
3
4nums = list(map(lambda x : x % 5, nums))
5
6print(nums)
7

#[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]
The syntax of filter() method is:
filter(function, iterable)

It takes two parameters:


•function - function that tests if elements of an
iterable return true or false
iterable - iterable which is to be filtered, could
be sets,lists,tuples

It filters the given iterable with the help of a function that


tests each element in the iterable to be true or not.
Filter Example
Filter Function

nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6,
8, 0, 3]
nums = list(filter(lambda x : x != 0,
nums))
print(nums)
#[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]
scores = [66, 90, 68, 59, 76, 60, 88, 74, 81,
65]
over_75 = list(filter(lambda x:x>75,
scores))
print(over_75)

Output
[90, 76, 88, 81]
Reduce() function
The reduce(fun,seq) function is used to apply a particular
function passed in its argument to all of the list
elements mentioned in the sequence passed [Link]
function is defined in “functools” module.
Working :
• At first step, first two elements of sequence are picked and
the result is obtained.
• Next step is to apply the same function to the previously
attained result and the number just succeeding the second
element and the result is again stored.
• This process continues till no more elements are left in the
container.
• The final returned result is returned and printed on console.
reduce

Reduce is like map but it reduces a list to a


single value (each operation acts on the result
of the last operation and the next item in the
list):
import functools
print([Link]((lambda x, y: x+y), [0,
1, 2, 3, 4]))
10
For using reduce() function you must have to
include functools module in the program
import functools

# initializing list
lis = [ 1 , 3, 5, 6, 2, ]

# using reduce to compute sum of list


print ("The sum of the list elements is : ",end="")
print ([Link](lambda a,b : a+b,lis))

# using reduce to compute maximum element from list


print ("The maximum element of the list is : ",end="")
print ([Link](lambda a,b : a if a > b else b,lis))

Output
The sum of the list elements is : 17
The maximum element of the list is : 6
import functools
nums = [92, 27, 63, 43, 88, 8, 38, 91, 47, 74, 18,
16, 29, 21, 60, 27, 62, 59, 86, 56]
sum = [Link](lambda x, y : x + y,
nums) / len(nums)
print(sum)
Output
50.25
Assignment
• my_floats = [4.35, 6.09, 3.25, 9.77, 2.16, 8.88, 4.59]
• To print the square of each numbers rounded to two decimal
places
• my_names = ["olumide", "akinremi", "josiah", "temidayo",
"omoseun"]
• To print only the names that are less than or equal to seven
letters
• my_numbers = [4, 6, 9, 23, 5]
• To print the product of these numbers
• Using the filter function, find the values that are common to the
two lists below
• a = [1,2,3,5,7,9]
• b = [2,3,5,6,7,8]
• output: [2, 3, 5, 7]
from functools import reduce
# Use map to print the square of each numbers rounded to two
decimal places
my_floats = [4.35, 6.09, 3.25, 9.77, 2.16, 8.88, 4.59]
# Use filter to print only the names that are less than or equal to
seven letters
my_names = ["olumide", "akinremi", "josiah", "temidayo",
"omoseun"]
# Use reduce to print the product of these numbers
my_numbers = [4, 6, 9, 23, 5]
map_result = list(map(lambda x: round(x**2,2), my_floats))
filter_result = list(filter(lambda name: len(name)<=7, my_names))
reduce_result = reduce(lambda num1, num2: num1 * num2,
my_numbers)
print(map_result)
print(filter_result)
print(reduce_result)
Output
[18.92, 37.09, 10.56, 95.45, 4.67, 78.85, 21.07]
['olumide', 'josiah', 'omoseun']
24840
a = [1,2,3,5,7,9]
b = [2,3,5,6,7,8]
print (list(filter(lambda x: x in a, b)))
output: [2, 3, 5, 7]

You might also like