Monday, August 30, 2021

Real Python: Using Python Optional Arguments When Defining Functions

Defining your own functions is an essential skill for writing clean and effective code. In this tutorial, you’ll explore the techniques you have available for defining Python functions that take optional arguments. When you master Python optional arguments, you’ll be able to define functions that are more powerful and more flexible.

In this tutorial, you’ll learn:

  • What the difference is between parameters and arguments
  • How to define functions with optional arguments and default parameter values
  • How to define functions using args and kwargs
  • How to deal with error messages about optional arguments

To get the most out of this tutorial, you’ll need some familiarity with defining functions with required arguments.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Creating Functions in Python for Reusing Code

You can think of a function as a mini-program that runs within another program or within another function. The main program calls the mini-program and sends information that the mini-program will need as it runs. When the function completes all of its actions, it may send some data back to the main program that has called it.

The primary purpose of a function is to allow you to reuse the code within it whenever you need it, using different inputs if required.

When you use functions, you are extending your Python vocabulary. This lets you express the solution to your problem in a clearer and more succinct way.

In Python, by convention, you should name a function using lowercase letters with words separated by an underscore, such as do_something(). These conventions are described in PEP 8, which is Python’s style guide. You’ll need to add parentheses after the function name when you call it. Since functions represent actions, it’s a best practice to start your function names with a verb to make your code more readable.

Defining Functions With No Input Parameters

In this tutorial, you’ll use the example of a basic program that creates and maintains a shopping list and prints it out when you’re ready to go to the supermarket.

Start by creating a shopping list:

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

You’re using a dictionary to store the item name as the key and the quantity you need to buy of each item as the value. You can define a function to display the shopping list:

# optional_params.py

shopping_list = {
    "Bread": 1,
    "Milk": 2,
    "Chocolate": 1,
    "Butter": 1,
    "Coffee": 1,
}

def show_list():
    for item_name, quantity in shopping_list.items():
        print(f"{quantity}x {item_name}")

show_list()

When you run this script, you’ll get a printout of the shopping list:

$ python optional_params.py
1x Bread
2x Milk
1x Chocolate
1x Butter
1x Coffee

The function you’ve defined has no input parameters as the parentheses in the function signature are empty. The signature is the first line in the function definition:

def show_list():

You don’t need any input parameters in this example since the dictionary shopping_list is a global variable. This means that it can be accessed from everywhere in the program, including from within the function definition. This is called the global scope. You can read more about scope in Python Scope & the LEGB Rule: Resolving Names in Your Code.

Using global variables in this way is not a good practice. It can lead to several functions making changes to the same data structure, which can lead to bugs that are hard to find. You’ll see how to improve on this later on in this tutorial when you’ll pass the dictionary to the function as an argument.

In the next section, you’ll define a function that has input parameters.

Defining Functions With Required Input Arguments

Instead of writing the shopping list directly in the code, you can now initialize an empty dictionary and write a function that allows you to add items to the shopping list:

Read the full article at https://realpython.com/python-optional-arguments/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...