Опциональный аргумент функции python

Функции и их аргументы

Python 3 логотип

В этой статье я планирую рассказать о функциях, именных и анонимных, инструкциях def, return и lambda, обязательных и необязательных аргументах функции, функциях с произвольным числом аргументов.

Именные функции, инструкция def

Функция в python — объект, принимающий аргументы и возвращающий значение. Обычно функция определяется с помощью инструкции def.

Определим простейшую функцию:

Инструкция return говорит, что нужно вернуть значение. В нашем случае функция возвращает сумму x и y.

Теперь мы ее можем вызвать:

 
  Функция может и не заканчиваться инструкцией return, при этом функция вернет значение None:

Функция может принимать произвольное количество аргументов или не принимать их вовсе. Также распространены функции с произвольным числом аргументов, функции с позиционными и именованными аргументами, обязательными и необязательными.

Функция также может принимать переменное количество позиционных аргументов, тогда перед именем ставится *:

    Как видно из примера, args - это кортеж из всех переданных аргументов функции, и с переменной можно работать также, как и с кортежем.

Функция может принимать и произвольное число именованных аргументов, тогда перед именем ставится **:

В переменной kwargs у нас хранится словарь, с которым мы, опять-таки, можем делать все, что нам заблагорассудится.

Анонимные функции, инструкция lambda

Анонимные функции могут содержать лишь одно выражение, но и выполняются они быстрее. Анонимные функции создаются с помощью инструкции lambda. Кроме этого, их не обязательно присваивать переменной, как делали мы инструкцией def func():

 

Для вставки кода на Python в комментарий заключайте его в теги

  • Книги о Python
  • GUI (графический интерфейс пользователя)
  • Курсы Python
  • Модули
  • Новости мира Python
  • NumPy
  • Обработка данных
  • Основы программирования
  • Примеры программ
  • Типы данных в Python
  • Видео
  • Python для Web
  • Работа для Python-программистов

Источник

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.

Источник

Читайте также:  Как затемнить бэкграунд css
Оцените статью