Review the basic operations of Python only for the parts that you are uneasy about. As the second step, we describe the function.
python
def function name(argument):
Processing content
Although defined in this way, I personally didn't pay much attention to the arguments. Here, we will deepen our understanding of functions by paying attention to the arguments.
There are two main types of arguments. -Dummy argument: Argument declared by the function -Actual argument: Argument to be passed to the function
example.py
#Function definition
def main(a):
return a+1
#Use of functions
main(x)
In the above code, a is a formal argument and x is an actual argument.
When using a function, the actual argument is specified, but it means that the value is passed to the formal argument.
There are two types of delivery methods. -Pass by value: Copy the actual argument to the formal argument (the value of the actual argument is not changed) -Pass by reference: Refers to the address of the actual argument (the value of the actual argument can be changed)
Passing by reference is basically used However... It behaves differently depending on the variable in the actual argument. It can be further divided into two according to its operation.
✓ Integers, floating point numbers, character strings, tuples, etc.
✓ List, dictionary type (dict), set (set), etc.
I verified whether the variable used for the actual argument is really rewritten by the following code.
def_arg.py
"""
2020/12/13
@Yuya Shimizu
Function arguments
"""
#Define function
def func_num(a):
a -= 1
return a
def func_char(a):
a += " Hello"
return a
def func_list(a):
a[0] -= 1
return a
def func_dict(a):
a["1"] -= 1
return a
##############immutable type
#Actual argument: Integer
x_int = 1
func_num(x_int)
print("Actual argument", x_int)
#Actual argument: Floating point number
x_float = 1.5
func_num(x_float)
print("Actual argument", x_float)
#Actual argument: string
x_char = "abc"
func_char(x_char)
print("Actual argument", x_char)
##############mutable type
#Actual arguments: list
x_list = [1, 2, 3]
func_list(x_list)
print("Actual argument", x_list)
#Actual argument: dictionary type(dict)
x_dict = {"1":10, "2":20, "3":30}
func_dict(x_dict)
print("Actual argument", x_dict)
Certainly, the data of immutable type actual arguments did not change even after the function was executed, and the mutable type actual arguments were affected by the function execution.
I've been using functions, but I'm not aware that there are such rules for arguments, and I'm refreshed to realize that it was one of the causes of errors I didn't understand until now.
Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha
Recommended Posts