Docsity

Python Functions: Keyword Arguments, Default Arguments, and Recursion, Slides of Object Oriented Programming

Partial preview of the text

Download Python Functions: Keyword Arguments, Default Arguments, and Recursion and more Slides Object Oriented Programming in PDF only on Docsity!

Functions

Keyword Arguments in Python

  • (^) The functions we have looked at so far were called with a fixed number of positional arguments. A positional argument is an argument that is assigned to a particular parameter based on its position in the argument list, as illustrated below.

Keyword Arguments in Python Contd..

  • (^) A keyword argument is an argument that is specified by parameter name, rather than as a positional argument as shown below

Default Arguments in Python

  • (^) A default argument is an argument that can be optionally provided,
  • (^) In this case, the third argument in calls to function mortgage_rate is optional. If omitted, parameter term will default to the value 20 (years) as shown. If, on the other hand, a third argument is provided, the value passed replaces the default parameter value.

Defaults

>>> def f(a, b=2, c=3): print(a, b, c)

a required, b and c optional

>>> f(1) # Use defaults 1 2 3 >>> f(a=1) 1 2 3 >>> f(1, 4) # Override defaults 1 4 3 >>> f(1, 4, 5) 1 4 5

Defaults

>>> f(1, c=6) # Choose defaults 1 2 6 Combining keywords and defaults def func(spam, eggs, toast=0, ham=0):

First 2 required

print((spam, eggs, toast, ham))

Arbitrary Arguments Examples

  • (^) Use of โ€˜*โ€™
  • (^) collects unmatched positional arguments into a tuple: >>> def f(*args): print(args)

Arbitrary Arguments Examples

  • (^) >>> f() ()
  • (^) >>> f(1) (1,) >>> f(1, 2, 3, 4) (1, 2, 3, 4)

Arbitrary Arguments Examples

>>> def f(a, *pargs, **kargs): print(a, pargs, kargs) >>> f(1, 2, 3, x=1, y=2) 1 (2, 3) {'y': 2, 'x': 1}

Calls: Unpacking arguments

>>> def func(a, b, c, d): print(a, b, c, d) >>> args = (1, 2) >>>args += (3, 4) >>> func(*args)

Same as func(1, 2, 3, 4)

1 2 3 4

Different patterns in Algorithm

Recursive algorithms

  • (^) In recursive problem solving , a problem is repeatedly broken down into similar sub problems, until the sub problems can be directly solved without further breakdown.

Recursive algorithms

  • (^) Recursive algorithms โ–  The functions computed by the algorithms The functions computed by the algorithms are expressed in terms of itself โ–  The functions computed by the algorithms Example Task: Find the Factorial of a positive integer