Python optional function arguments

Posted: mxm2007 Date: 23.05.2017

Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value.

Futhermore, arguments can be specified in any order by using named arguments. If info is called with only one argument, spacing defaults to 10 and collapse defaults to 1.

If info is called with two arguments, collapse still defaults to 1.

Passing an optional argument in a function - python - Stack Overflow

Say you want to specify a value for collapse but want to accept the default value for spacing. In most languages, you would be out of luck, because you would need to call the function with three arguments.

python optional function arguments

But in Pythonarguments can be specified by name, in any order. This looks totally whacked until you realize that arguments are simply a dictionary.

Fun With Python Function Parameters | Python Central

Using Optional and Named Arguments. Here is an example of infoa function with two optional arguments: With two arguments, collapse gets its default value of 1.

Python: Function Optional Parameter

Here you are naming the collapse argument explicitly and specifying its value. Even required arguments like objectwhich has no default value can be named, and python optional function arguments arguments can appear 1st grade math money counting worksheets any order.

python optional function arguments

Further Reading on Optional Arguments Python Tutorial discusses exactly when and how default arguments are evaluatedwhich matters when the default value is a list or an expression with side effects.

Dive Into Python Python from novice to pro.

python optional function arguments

With only one argument, spacing gets its default value of 10 and collapse gets its default value of 1. The only thing you need to do to call a function is specify a value somehow for each required argument; the manner and order in which you do that is up to you.

Rating 4,4 stars - 507 reviews
inserted by FC2 system