Files
python/concepts/function-arguments/introduction.md

68 lines
2.0 KiB
Markdown
Raw Normal View History

2022-05-27 06:55:03 -05:00
# Introduction
For the basics on function arguments, please see the [function concept][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
2022-05-31 17:30:41 -05:00
Positional arguments are values passed to a function in the same order as the parameters which bind to them.
2022-05-31 21:16:58 -05:00
Positional arguments can optionally be passed by using their parameter name.
2022-05-27 06:55:03 -05:00
2022-05-31 21:16:58 -05:00
Following is an example of positional arguments being passed by position and by their parameter name:
2022-05-27 06:55:03 -05:00
```python
2022-05-30 15:26:24 -05:00
>>> def concat(greeting, name):
... return f"{greeting}{name}"
2022-05-29 06:48:10 -05:00
...
2022-05-27 06:55:03 -05:00
>>> print(concat("Hello, ", "Bob"))
Hello, Bob
2022-05-30 15:26:24 -05:00
>>> print(concat(name="Bob", greeting="Hello, "))
2022-05-27 06:55:03 -05:00
Hello, Bob
```
Note that positional arguments cannot follow keyword arguments.
This
```python
2022-05-30 15:26:24 -05:00
>>> print(concat(greeting="Hello, ", "Bob"))
2022-05-27 06:55:03 -05:00
```
results in this error:
```
SyntaxError: positional argument follows keyword argument
```
The first call to `concat` passes the arguments by position.
2022-05-28 13:28:11 -05:00
The second call to `concat` passes the arguments by name, allowing their positions to be changed.
2022-05-27 06:55:03 -05:00
## Keyword Arguments
Keyword arguments are for parameters defined with a [default argument][default arguments].
Keyword arguments can optionally be called by their position.
Following is an example of keyword arguments being called by their keyword and by position:
```python
2022-05-30 15:26:24 -05:00
>>> def concat(greeting="Hello, ", name="you"):
... return f"{greeting}{name}"
2022-05-29 06:48:10 -05:00
...
2022-05-30 15:26:24 -05:00
>>> print(concat(name="Bob", greeting="Hello, "))
2022-05-27 06:55:03 -05:00
Hello, Bob
2022-05-30 15:26:24 -05:00
>>> print(concat("Hello, ", name="Bob"))
2022-05-27 06:55:03 -05:00
Hello, Bob
2022-05-27 07:10:32 -05:00
>>> print(concat())
Hello, you
2022-05-27 06:55:03 -05:00
```
[default arguments]: https://www.geeksforgeeks.org/default-arguments-in-python/
[function concept]: ../functions/about.md
2022-05-31 17:30:41 -05:00
[parameters]: https://www.codecademy.com/learn/flask-introduction-to-python/modules/learn-python3-functions/cheatsheet