Basic grammar of Python3 system (how to use functions, closures, lambda functions)

Overview

You will study the basic grammar of Python 3 by referring to "Introduction to Python 3" by O'Reilly Japan. I hope it will be helpful for those who want to study Python in the same way.

Basic usage of functions

Function definition

>>> def print_sum(num1, num2):
...     print(num1 + num2)

Function call

>>> print_sum(10, 20)
30

Arguments used in function definitions are formal arguments (parameters), The argument passed at the time of calling is called an actual argument (argument).

Positional argument

An argument that copies a value to a formal argument at the corresponding position in order from the beginning is called a "positional argument".

>>> def print_args(arg1, arg2, arg3):
...     print('arg1:', arg1, 'arg2:', arg2, 'arg3:', arg3)
...
>>> print_args(1111, True, 'Python')
arg1: 1111 arg2: True arg3: Python

Keyword arguments

You can also specify the actual argument by specifying the name of the formal argument, in which case it will be treated as a "keyword argument".

>>> def print_args(arg1, arg2, arg3):
...     print('arg1:', arg1, 'arg2:', arg2, 'arg3:', arg3)
...
>>> print_args(arg2='two', arg1='one', arg3='three')
arg1: one arg2: two arg3: three

Specifying the default argument value

You can also specify a default value for the formal argument. The default value is used if the caller does not pass the corresponding actual argument.

>>> def print_args(arg1, arg2, arg3='default value'):
...     print('arg1:', arg1, 'arg2:', arg2, 'arg3:', arg3)
...
>>> #If the default value is used (no actual arguments passed)
>>> print_args('one', 'two')
arg1: one arg2: two arg3: default value
>>>
>>> #If the default value is not used (passing the actual argument)
>>> print_args('one', 'two', 'three')
arg1: one arg2: two arg3: three

Tuple of positional arguments with *

If * is used as part of the formal argument when defining a function, a variable number of positional arguments are set together in a tuple.

>>> def print_args(*args):
...     print('args tuple:', args)
...
>>> #Specify multiple arguments
>>> print_args('one', 'two', 'three')
args tuple: ('one', 'two', 'three')
>>>
>>> #No arguments
>>> print_args()
args tuple: ()

If there are required positional arguments, you can also use them as follows.

>>> def print_args(arg1, arg2, *args):
...     print('arg1:', arg1)
...     print('arg2:', arg2)
...     print('args:', args)
...
>>> print_args('one', 'two', 1, 10, 100)
arg1: one
arg2: two
args: (1, 10, 100)

Dictionary of keyword arguments by **

If you use ** when defining a function, you can set keyword arguments collectively in a dictionary.

>>> def print_kwargs(**kwargs):
...     print('kwargs:', kwargs)
...
>>> print_kwargs(arg1='one', arg2='two', arg3='three')
kwargs: {'arg1': 'one', 'arg2': 'two', 'arg3': 'three'}

Set function as argument

You can treat the function as an argument of the function, or return the function as the return value from the function.

>>> def print_string():
...     print('print_string')
...
>>> def execute_func(arg_func):
...     arg_func()
...
>>> execute_func(print_string)
print_string

In-function function

You can also define a function inside a function.

>>> def outer():
...     def inner():
...         print('inner function')
...     inner()
...
>>> outer()
inner function

closure

It is also possible to make an in-function function function as a closure and dynamically generate a function.

>>> def todays_weather(arg1):
...     def return_weather():
...         return 'It’s ' +  arg1 + ' today.'
...     return return_weather
...
>>> day1 = todays_weather('sunny')
>>> day2 = todays_weather('cloudy')
>>>
>>> day1()
'It’s sunny today.'
>>> day2()
'It’s cloudy today.'

Lambda function

Implementation without lambda function

>>> def return_sum(num1, num2):
...     return num1 + num2
...
>>> print('answer:', return_sum(10, 20))
answer: 30

Implementation using lambda function

>>> return_sum = lambda num1, num2 :num1 + num2
>>> print('answer:', return_sum(10, 20))
answer: 30

Example of using lambda function in combination with map ()

When combined with map (), iterables elements such as the list passed as an argument, The following implementation that passes it to func and processes it is also possible. (* 1)

[Addition]

https://docs.python.jp/3/library/functions.html#map

>>> help(map)
Help on class map in module builtins:

class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.

Implementation example

>>> num_list = list(range(1, 6))
>>> num_list
[1, 2, 3, 4, 5]
>>>
>>> list(map(lambda x: x**2, num_list))
[1, 4, 9, 16, 25]

Recommended Posts

Basic grammar of Python3 system (how to use functions, closures, lambda functions)
How to use Python lambda
Basic grammar of Python3 system (dictionary)
[Python] Summary of how to use split and join functions
Comparison of how to use higher-order functions in Python 2 and 3
[Python] Summary of how to use pandas
[Python2.7] Summary of how to use unittest
Basic grammar of Python3 system (character string)
[Python] Understand how to use recursive functions
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
Basic grammar of Python3 system (included notation)
[Question] How to use plot_surface of python
Summary of how to use MNIST in Python
Summary of studying Python to use AWS Lambda
[Introduction to Python] Basic usage of lambda expressions
python3: How to use bottle (2)
I tried to summarize how to use matplotlib of python
How to use Python argparse
How to use Python Kivy ① ~ Basics of Kv Language ~
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
Summary of how to use pandas.DataFrame.loc
[Python] How to use Pandas Series
How to use Requests (Python Library)
How to use SQLite in Python
Summary of how to use pyenv-virtualenv
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to use python zip function
Summary of how to use csvkit
[Python] How to use Typetalk API
How to use Python Kivy (reference) -I translated Kivy Language of API reference-
[Introduction to Python] How to use class in Python?
How to install and use pandas_datareader [Python]
[python] How to use __command__, function explanation
How to calculate Use% of df command
[Python] How to use import sys sys.argv
[Python] Organizing how to use for statements
Memorandum on how to use gremlin python
How to access RDS from Lambda (python)
python: How to use locals () and globals ()
Basic grammar of Python3 series (list, tuple)
How to use __slots__ in Python class
Jupyter Notebook Basics of how to use
How to use "deque" for Python data
Basics of PyTorch (1) -How to use Tensor-
How to use Python zip and enumerate
[Road to intermediate Python] Use lambda expressions
How to use regular expressions in Python
How to use Jupyter notebook [Super Basic]