Python-3.4.3/C4/Advanced-Features-of-Functions/English

From Script | Spoken-Tutorial
Jump to: navigation, search
Visual Cue
Narration
Show Slide title Welcome to the spoken tutorial on Advanced Features of Functions.
Show Slide

Objectives


In this tutorial, we will learn to-
  • Assign default values to arguments, when defining functions
  • Define and call functions with keyword arguments
  • Define and call functions with arbitrary arguments
  • Learn some of the built-in functions available in Python standard library.
Show Slide

System Specifications

To record this tutorial, I am using
  • Ubuntu Linux 16.04 operating system
  • Python 3.4.3
  • IPython 5.1.0
Show Slide

Pre-requisite slide

To practise this tutorial, you should know how to
  • run basic Python commands on the IPython console
  • use functions.

If not, see the relevant Python tutorials on this website.

Slide:


First let us see about default arguments in Python.


  • Function arguments can have default values in Python.
  • When we call a function without a value for an argument, its default value is used if available
  • Otherwise it will give error.

Open the terminal

Let us start ipython.


Open the terminal.

Type ipython3 and press Enter.


Type ipython3 and press Enter.


From here onwards, remember to press the Enter key after typing every command on the terminal.

Type,

def welcome(greet,name="World"):

print (greet, name)


Highlight welcome, greet, name


Highlight name

Let us define a function Welcome.


Type the code as shown.


Here,

  • welcome is the function name
  • greet is the argument with no default values and
  • the name argument has a default value World.

In a function, all the arguments with default values should come after non-default arguments.

Type,

welcome("Hi", "Chandru")

Let us first call the function welcome with two arguments

Type,

welcome inside brackets inside double quotes Hi comma inside double quotes Chandru

Point to the output We get the expected welcome message, Hi Chandru.
Type,

welcome("Hello")


Highlight hello, world

Now let us call the function with one argument only.


Type,

welcome inside brackets inside double quotes Hello


We get the output as Hello World.


Here,

  • “Hello” is passed to the parameter greet and
  • “World” is the default value of the name parameter.
Type,

def welcome(greet,age = 23, name="World"):

print (greet, name,age)


Type,

welcome("Hello")


Let us add another parameter age with default value as 23 as shown.


Now type, welcome inside brackets inside double quotes Hello


Here, welcome function still works since we have provided default value for age.


Default values allow us to add new parameters to an existing function.


It will not break the existing usage of the function.


<<PAUSE>>

Pause the video.


Try this exercise and then resume the video.

Show Slide


Exercise 1

Redefine the function welcome, by interchanging its arguments.


Place the name argument with its default value of "World" before the greet argument.

Switch terminal Switch to the terminal for the solution.
Type,

def welcome(name="World", greet):

print (greet, name)


Highlight SyntaxError

Type as shown.


We get an error that reads SyntaxError: non-default argument follows default argument.


When defining a function all the arguments with default values should come at the end.

Pause the video.


Try this exercise and then resume the video.

Show Slide


Exercise 2

Redefine the function welcome with a default value of "Hello" to the greet argument.


Then, call the function without any arguments.

Switch terminal Switch to the terminal for the solution.
Type,

def welcome(greet="Hello", name="World"):

print (greet, name)


welcome()

Type as shown.


Then type, welcome open and close brackets


As we can see, we get the output as Hello World.


Default values of both parameters are used since function is called without passing any value.

Show Slide

keyword arguments


Next let us see what are keyword arguments.


  • We no need to remember the order of arguments while calling functions by passing keyword arguments.
  • Instead, we can use name of the argument to pass a value to it.
Type,

def marks(first,second,third):

print("first: %d second: %d and third: %d" %(first,second,third))


Type,

marks(34,23,45)


Let us define a function with name marks which takes three marks as arguments.


Type as shown.


Then we will call the marks function without specifying the keywords.


Type, marks inside brackets 34 comma 23 comma 45


We get the output as “first: 34 second: 23 and third: 45


Here the values 34, 23 and 45 are passed according to the position.

Type,

marks(34,45,23)

To confirm this, we will try with different values.


Type,

marks inside brackets 34 comma 45 comma 23


We can see that the printed values are changed since they are passed according to the position.

Type,

marks(34,23,third=45)


Now let us pass two values without keyword and other one with keyword.


Type,

marks inside brackets 34 comma 23 comma third is equal to 45


Here first two values are passed according to the position and the third as keyword argument.


But, the keyword arguments should be specified at the end.

Type,

marks(34,second=23,45)


Now type,

marks inside brackets 34 comma second is equal to 23 comma 45


We get the SyntaxError, positional argument follows keyword argument.


This is because here the keyword argument is not specified at the end.

Type,

marks(second=34,first=23,third=45)

We can pass all the parameters as keyword arguments.


Type,

marks inside brackets second is equal to 34 comma first is equal to 23 comma third is equal to 45


Here even though the order of keyword is changed, we get the output as:

first: 23 second: 34 and third: 45

Type,

def marks(*, first, second, third):

print("first: %d second: %d and third: %d" %(first,second,third))


Type,

marks(second=34,first=23,third=45)


Next we will learn to define a function to take only keyword arguments.


Type as shown.


Then to call the function, type,

marks inside brackets second is equal to 34 comma first is equal to 23 comma third is equal to 45


Note the asterisk symbol at the starting of parameters.


It restricts the function to accept keyword only arguments.

Type,

marks(45, 34, 23)


highlight TypeError in output


Again we will try to call the function without keyword arguments.


Type,

marks inside brackets 45 comma 34 comma 23


It gives a TypeError as marks() takes 0 positional arguments but 3 were given.

This way we can enforce usage of keyword only arguments without positional arguments.

Slide:


Next let us learn to use arbitrary arguments.


  • We may not always know in advance the number of arguments that will be passed into a function.
  • Use an asterisk(*) before an argument name to denote arbitrary number of arguments.
Type,

def family(*names):

print(names)


Type,

family("Duryodhana", "Dushasana")

We can define a function to accept any number of positional arguments.


Type as shown.


Then type,

family inside brackets inside double quotes Duryodhana comma inside double quotes Dushasana


Here, we have called the function with multiple arguments.


These arguments get wrapped up into a tuple while passed into the function.

Type,

family("Duryodhana", "Dushasana", "Dushla", "Jalsandha")


Now type as shown.


As you can see, we can call the function family with more values passed to the names argument.


We have passed 2 values in the first call and 4 values in the second call to the function family.


In both cases these values are assigned to the parameter names.

Type,

def person(**attributes):

print(attributes)


Type,

person(name="John",age=34,height=182)


Highlight * and **


We can also define a function to receive arbitrary number of keyword arguments.


Type as shown.


Then to call the function type as shown.


The person function prints a dictionary of keyword arguments passed to it.


Note the double asterisk symbol at the beginning of the parameter names.


It enables to pass zero or more keyword arguments.


Note: Single asterisk (*) symbol is used to accept arbitrary number of positional arguments.


And the double asterisk (**) symbol is used to accept arbitrary number of keyword arguments.

Type,

person(name="Lisa",age=27,height=162,weight=58)


Now call the person function as shown.


Here we have passed 3 keyword arguments in the first case and 4 in the second case.


The function prints a dictionary of keyword arguments with values.

Show Slide

Built-in functions

https://docs.python.org/3/library/functions.html

Python also provides built-in functions.

Some are

  • abs()
  • any()
  • dir()
  • help()

You can visit this link to get the full list of built-in functions and their usage.

Show Slide

Summary slide


This brings us to the end of this tutorial. Let us summarize.


In this tutorial, we have learned to define functions with,

  • Default arguments
  • keyword arguments
  • Arbitrary arguments
Show Slide

Evaluation


Here are some self assessment questions for you to solve.


  • All the arguments of a function cannot have default values. - True or False?
  • The following is a valid function definition. True or False?
  • While calling a function, which one is correct in the following.
Show Slide


Solutions


And the answers,
  1. False. All the arguments of a Python function can have default values.
  2. False. All the parameters with default arguments should be defined at the end.
  3. While calling a function, only keyword arguments can be in any order, but should be called at the end.
Show Slide Forum Please post your timed queries in this forum.
Show Slide

Fossee Forum

Please post your general queries on Python in this forum.
Slide Textbook Companion FOSSEE team coordinates the TBC project.
Show Slide

Acknowledgement

Spoken Tutorial Project is funded by NMEICT, MHRD, Govt. of India.

For more details, visit this website.

Show Slide Thank You This is Priya from IIT Bombay signing off. Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Nirmala Venkat, Priyacst