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

74 lines
2.2 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
Parameter names, like variable names, must start with a letter or underscore and may contain letters, underscores, or numbers.
2022-05-27 06:55:03 -05:00
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
...
# Passing data to the function by position.
2022-05-27 06:55:03 -05:00
>>> print(concat("Hello, ", "Bob"))
Hello, Bob
...
# Passing data to the function using the parameter name.
2022-05-30 15:26:24 -05:00
>>> print(concat(name="Bob", greeting="Hello, "))
2022-05-27 06:55:03 -05:00
Hello, Bob
```
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.
2022-05-27 06:55:03 -05:00
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
```
## Keyword Arguments
Keyword arguments use the parameter name when calling a function.
Keyword arguments can optionally be referred to by position.
2022-05-27 06:55:03 -05:00
Following is an example of keyword arguments being referred to by their parameter name and by position:
2022-05-27 06:55:03 -05:00
```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
...
# Function call using parameter names as argument keywords.
2022-05-30 15:26:24 -05:00
>>> print(concat(name="Bob", greeting="Hello, "))
2022-05-27 06:55:03 -05:00
Hello, Bob
...
# Function call with positional data as arguments.
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