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

Week 4 Lect 2 Functions Class

The document provides an overview of functions in Python, including their definition, how to pass arguments, and various types of arguments such as arbitrary, keyword, and default parameters. It also covers lambda functions, the map function, and the filter function, demonstrating their usage with examples. Key concepts include the order of parameters, positional-only and keyword-only arguments, and the application of lambda functions in conjunction with map and filter.
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 views35 pages

Week 4 Lect 2 Functions Class

The document provides an overview of functions in Python, including their definition, how to pass arguments, and various types of arguments such as arbitrary, keyword, and default parameters. It also covers lambda functions, the map function, and the filter function, demonstrating their usage with examples. Key concepts include the order of parameters, positional-only and keyword-only arguments, and the application of lambda functions in conjunction with map and filter.
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
You are on page 1/ 35

Function

Week 4

Dr. Syed Imran Ali


Agenda
• Function
• Lambda
• Map
• Filter

Advanced Programming in Python 2


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.

def my_function():
print(“I am a function")

Advanced Programming in Python 3


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.

def my_function():
print(“I am a function")

my_function()

Advanced Programming in Python 4


Function - Arguments
• Information can be passed into functions as arguments.

def my_function(fname):
print(fname + " Khan")

my_function(“Ali")
my_function(“Jamil")
my_function(“Sara")

Advanced Programming in Python 5


Function - Arguments
• If you try to call the function with 1 or 3 arguments, you will get
an error:

def my_function(fname, lname):


print(fname + “ “ + “ Khan”)

my_function(“Ali")

Advanced Programming in Python 6


Function – Arbitrary 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

def my_function(*kids):
print(“The youngest child is “ + kids[2])

my_function(“Ali”, “Imran”, “Sara”)

• This way the function will receive a tuple of arguments.

Advanced Programming in Python 7


Function – Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.

def my_function(child3, child2, child1):


print(“The youngest child is “ + child3)

my_function(child1 = “Ali”, child2 = “Imran”, child3 = “Sara”)

• Keyword Arguments are often shortened to kwargs in Python


documentations
Advanced Programming in Python 8
Function – Arbitrary Keyword Arguments
• 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

def my_function(**kid):
print(“His last name is “ + kid[“lname”])

my_function(fname = “Imran”, lname = “Ali”)

• Function will receive a dictionary of arguments

Advanced Programming in Python 9


Function – Default Parameter Value
• The following example shows how to use a default parameter
value.
• If we call the function without argument, it uses the default
value
def my_function(country = “Pakistan”):
print("I am from " + country)

my_function(“Sweden”)
my_function(“UK")
my_function()
my_function(“Brazil”)
Advanced Programming in Python 10
Function – 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.
def my_function(food):
for x in food:
print(x)

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

my_function(fruits)

Advanced Programming in Python 11


Function – Positional-Only Arguments
• You can specify that a function can have ONLY positional
arguments, or ONLY keyword arguments.
• To specify that a function can have only positional arguments,
add , / after the arguments

def my_function(x, /):


print(x)

my_function(3)

Advanced Programming in Python 12


Function – Positional-Only Arguments
• Without the , / you are actually allowed to use keyword
arguments even if the function expects positional arguments

def my_function(x): def my_function(x, /):


print(x) print(x)

my_function(x = 3) my_function(x = 3)

• But when adding the , / you will get an error if you try to
send a keyword argument
Advanced Programming in Python 13
Function – Keyword-Only Arguments
• To specify that a function can have only keyword arguments,
add *, before the arguments:

def my_function(*, x):


print(x)

my_function(x = 3)

Advanced Programming in Python 14


Function – Keyword-Only Arguments
• Without the *, you are allowed to use positional arguments
even if the function expects keyword arguments

def my_function(x): def my_function(*, x):


print(x) print(x)

my_function(3) my_function(3)

• But with the *, you will get an error if you try to send a
positional argument:
Advanced Programming in Python 15
Function – Positional-Only and Keyword-Only Arguments
• You can combine the two argument types in the same function.
• Any argument before the / , are positional-only, and any
argument after the *, are keyword-only.

def my_function(a, b, /, *, c, d):


print(a + b + c + d)

my_function(5, 6, c = 7, d = 8)

Advanced Programming in Python 16


Function – Rule of parameter order in Python

• In a function definition, the order must be:


1. Positional-only (before /)
2. Positional or keyword (the normal ones)
3. *args (arbitrary positional)
4. Keyword-only (after *)
5. **kwargs (arbitrary keyword)

Advanced Programming in Python 17


Function – Lambda
• A lambda function is a small anonymous function.

• A lambda function can take any number of arguments, but can


only have one expression.

lambda arguments : expression

Advanced Programming in Python 18


Function – Lambda
• A lambda function is a small anonymous function.

• A lambda function can take any number of arguments, but can


only have one expression.

x = lambda a : a + 10 x = lambda a, b : a * b
print(x(5)) print(x(5, 6))

Advanced Programming in Python 19


Function – Lambda
• The power of lambda is better shown when you use them as an
anonymous function inside another function.

def myfunc(n):
return lambda a : a * n

• Say you have a function definition that takes one argument,


and that argument will be multiplied with an unknown
number
Advanced Programming in Python 20
Function – Lambda
• Use that function definition to make a function that always
doubles the number you send in:

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Advanced Programming in Python 21


Function – Lambda
• Use that function definition to make a function that always
triples the number you send in:

def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mydoubler(11))

Advanced Programming in Python 22


Function – Lambda
• Or, use the same function definition to make both functions, in
the same program
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

Advanced Programming in Python 23


Function – Map
• The map() function executes a specified function for each item
in an iterable. The item is sent to the function as a parameter.

map(function, iterables)

Parameter Description
function Required. The function to execute for each item
iterable Required. A sequence, collection or an iterator
object. You can send as many iterables as you like,
just make sure the function has one parameter for
each iterable.
Advanced Programming in Python 24
Function – Map
• Calculate the length of each word in the tuple

def myfunc(n):
return len(n)

x = map(myfunc, ('apple', 'banana', 'cherry'))

Advanced Programming in Python 25


Function – Map
• Make new fruits by sending two iterable objects into the
function

def myfunc(a, b):


return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon',


'pineapple'))

Advanced Programming in Python 26


Function – Map
• Make new fruits by sending two iterable objects into the
function

def myfunc(a, b):


return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon',


'pineapple'))

['appleorange', 'bananalemon', 'cherrypineapple']


Advanced Programming in Python 27
Function – Lambda and Map
• Square numbers using lambda express and map()

numbers = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, numbers))

print(squared)

// [1, 4, 9, 16, 25]

Advanced Programming in Python 28


Function – Lambda and Map
• Add two lists element-wise

a = [1, 2, 3]
b = [4, 5, 6]

Advanced Programming in Python 29


Function – Filter
• filter(function, iterable) keeps only the elements where
function(item) returns True.
• Returns an iterator → usually converted to list().

def is_even(n):
return n % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(is_even, numbers))
print(evens)

Advanced Programming in Python 30


Function – Filter
• Keep Only Words Longer Than 3 Characters

Advanced Programming in Python 31


Function – Filter
• Remove empty strings

Advanced Programming in Python 32


Function – Filter with lambda
• Keep only even numbers

Advanced Programming in Python 33


Function – Filter with lambda
• Filter Strings starting with “a”

Advanced Programming in Python 34


Function – Filter with lambda and map
• Double only the even numbers

Advanced Programming in Python 35

You might also like