RSS Planet Python

Real Python: Using Python Optional Arguments When Defining Functions

Python functions can be made flexible using optional arguments, default values, *args, and kwargs. Parameters are names in a function, arguments are values passed when calling it. Default values make arguments optional, but avoid mutable defaults to prevent unexpected issues. *args gathers positional arguments, while kwargs handles keyword arguments. Omitting required arguments causes TypeErrors, ordering issues cause SyntaxErrors. Functions are mini-programs, promoting code reuse with various inputs. Functions extend Python's vocabulary, leading to clearer solutions. The tutorial uses a shopping list example to demonstrate function definition. A function to display the shopping list is created, then improved by passing the list as an argument. Using global variables with functions is discouraged due to potential bugs.
favicon
realpython.com
realpython.com
Image for the article: Real Python: Using Python Optional Arguments When Defining Functions
Create attached notes ...