Files
python/concepts/function-arguments/introduction.md
2022-06-03 11:12:17 -05:00

2.0 KiB

Introduction

For the basics on function arguments, please see the function concept.

Parameter Names

Paramater names, like variable names, must start with a letter or underscore and may contain letters, underscores, or numbers. Parameter names should not contain spaces or punctuation.

Positional Arguments

Positional arguments are values passed to a function in the same order as the parameters which bind to them. Positional arguments can optionally be passed by using their parameter name.

Following is an example of positional arguments being passed by position and by their parameter name:

>>> def concat(greeting, name):
...         return f"{greeting}{name}"
... 
>>> print(concat("Hello, ", "Bob"))
Hello, Bob
>>> print(concat(name="Bob", greeting="Hello, "))
Hello, Bob

Note that positional arguments cannot follow keyword arguments.

This

>>> print(concat(greeting="Hello, ", "Bob"))

results in this error:

SyntaxError: positional argument follows keyword argument

The first call to concat passes the arguments by position. The second call to concat passes the arguments by name, allowing their positions to be changed.

Keyword Arguments

Keyword arguments are for parameters defined with a default argument. Keyword arguments can optionally be passed by their position.

Following is an example of keyword arguments being passed by their keyword and by position:

>>> def concat(greeting="Hello, ", name="you"):
...         return f"{greeting}{name}"
... 
>>> print(concat(name="Bob", greeting="Hello, "))
Hello, Bob
>>> print(concat("Hello, ", name="Bob"))
Hello, Bob
>>> print(concat())
Hello, you