Python optional parameters in function

How to pass optional parameters to a function in Python?

A type of argument with a default value is a Python optional parameter. A function definition’s assignment operator or the Python **kwargs statement can be used to assign an optional argument. Positional and optional arguments are the two sorts of arguments that a Python function can take. Values that are not required to be given in order to call a function are known as optional parameters.

Function in Python

A function is a section of code that only executes when called. You can supply parameters that is data to a function. As a result, a function may or may not return data.

Example

Let us understand what a function in python is with the help of an example.

def demo_function(): print("Hello World") demo_function() #the demo_function() method is called.

Output

The output obtained is as follows.

Arguments in a Function

Functions accept arguments that can contain data. The function name is followed by parenthesis that list the arguments. Simply separate each argument with a comma to add as many as you like. The function in the following example only takes one argument (fname). A first name is passed to the function when it is called, and it is utilized there to print the whole name.

Читайте также:  Any project in php

Optional Arguments in Python

An argument in Python that has a default value is called an optional argument. A default value for an argument can be specified using the assignment operator. When calling a function, there is no requirement to provide a value for an optional argument. This is because, in the absence of a value, the default value will be used.

Argument default values are possible. This renders an argument unnecessary. If a default value is present for an argument, it will be used if no alternative value is provided.

Python has two primary methods for passing optional parameters. They are as follows.

Passing without using keyword arguments

The following are some major considerations when passing without keyword arguments −

  • When invoking a function, the order of the parameters—that is, the order in which the parameters are defined in the function—should be preserved.
  • The non-optional arguments’ values must be provided otherwise an error will be thrown.
  • The default argument value can either be supplied or disregarded.

Example

Let’s look at an example to see how optional arguments are passed.

# Python program to demonstrate a optional argument. def function(a, b=999): return a+b print(function(2, 3)) # In the function 1 is represented as 'a' in the function and #The function uses the default value of b print(function(1))

Output

The following is the output that is generated upon executing the above program.

Источник

Python Optional Arguments: A How-To Guide

A Python optional argument is a type of argument with a default value. You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement.

There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what optional arguments are and how they work.

We’ll walk you through an example of optional arguments so you can learn how to use them in your programs. We’ll also discuss how to use the **kwargs method to accept variable numbers of arguments.

What is a Python Argument?

An argument is a value that is accepted by a Python function. This value becomes its own Python variable that can be used within a function. Consider the following code:

def show_the_day(day): print("Hello there. Today is <>.".format(day)) show_the_day("Thursday")

In this code, “day” is an argument. Whatever value you specify in parentheses when you call the show_the_day function will become “day”. In this case, “Thursday” is “day”.

The number of values we specify in a function call must be equal to the number of arguments that a function accepts. This is unless we use optional arguments. In which case, we can specify fewer arguments than a function accepts because some arguments are optional.

Python Optional Arguments

A Python optional argument is an argument with a default value. You can specify a default value for an argument using the assignment operator. There is no need to specify a value for an optional argument when you call a function. This is because the default value will be used if one is not specified.

Arguments can have default values. This makes an argument optional. If an argument has a default value, then it will use that default value if no other value is specified.

Default arguments are assigned using the assignment operator:

def print_student(student, grade="Fifth"): print("<> is in <> grade.".format(student, grade))

This user-defined function accepts two arguments: student and grade. Grade is an optional function argument which means we do not need to specify a value for it when we call the print_student() function.

Optional Arguments Python Example

We’re going to write a program that counts how many of a particular coffee was sold at a coffee shop on a Thursday morning. To start, define a list of coffees that were sold that morning:

coffees_sold = ["Espresso", "Espresso", "Latte", "Cappuccino", "Mocha", "Espresso", "Latte"]

Next, write a function that counts how many of a particular coffee was sold:

def count_coffees(coffees, to_find="Espresso"): number_sold = coffees.count(to_find) print("<> <> coffees were sold.".format(number_sold, to_find))

This function accepts two arguments: coffees and to_find.

The first argument is the list of coffees. Our second argument is the name of the coffee whose total sales we want to calculate. The Python count() method counts how many instances of the coffee for which we are looking exists in the “coffees” list.

The second argument is optional. If we don’t specify a value for the “to_find” argument, that argument will become equal to “Espresso”. Next, let’s call the function:

count_coffees(coffees_sold, "Latte")

This function call will make the value of “to_find” equal to “Latte” in our code. Let’s run the program and see what happens:

2 Latte coffees were sold.

The code tells us that two lattes were sold. Now, call our function without a second value:

count_coffees(coffees_sold)
3 Espresso coffees were sold.

We specified no value for “to_find” so, by default, its value became “Espresso”. We can see that if we specify no value for an argument, its default value is used. Otherwise, the value we specify is used for the argument.

Python Function Optional Arguments Error

Optional parameters must appear after required arguments when you define a function. Required arguments are those that do not have a default value assigned.

Required arguments are often called “required positional arguments” because they must be assigned at a particular position in a function call. If you specify an optional argument before a required argument, Python returns an error that looks like this:

This is because if optional arguments came before required arguments then it will eliminate the purpose of optional arguments. How would Python know what values to assign to what arguments if the optional ones came first?

Optional Arguments Python: **kwargs

The **kwargs keyword passes arguments to a function that are assigned to a particular keyword. **kwags represents an aribitrary number of keywords, whether that is zero, one, or more keywords. So, you can use **kwargs to use an optional argument with a function.

Let’s write a program that prints out information about the grades a student has earned on their tests to the console. To start, define a dictionary with some information about a student:

Our dictionary contains four keys and values. We’re going to write a function that prints out values from this dictionary to the console:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

def show_grades(student, **grades): print("Student record for <>: ".format(student)) for key, value in grades.items(): print("<> earned a grade of <> in their <>.".format(student, value, key))

This function prints out a message stating “Student record for X”, where X is equal to the name of a student.

Next, our program prints out all the items in the “grades” variable to the console. “grades” uses the “**” syntax which means it contains a dictionary of keys and values over which we can iterate in our program.

show_grades(amy["Name"], SecondTest=amy["Second Test"])

We have specified two arguments: the name of the student and the score they earned on their second test. The second argument needs to have a keyword because **kwargs represents keyword arguments.

Let’s run our code and see if it works:

Student record for Amy: Amy earned a grade of 72 in their SecondTest.

Our program informs us about the grade Amy, a student, earned in their second test. Try to pass another test score through our function as an argument:

show_grades(amy["Name"], FirstTest=amy["First Test"], SecondTest=amy["Second Test"])

Our function now accepts three arguments. The last two arguments are keyword arguments. Let’s run our program:

Student record for Amy: Amy earned a grade of 68 in their FirstTest. Amy earned a grade of 72 in their SecondTest.

Our program shows us the grades that Amy earned in both her first and second test. This is because the **kwargs keyword accepts a variable number of arguments.

Our program also works if we do not specify any keyword arguments:

Conclusion

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

To learn more about coding in Python, read our How to Learn Python guide.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

Оцените статью