Here, we will explain "functions" for Python beginners. It is supposed to use Python3 series.
Use def
when creating a function.
The line following the def function name (formal argument 1, formal argument 2, ...):
starts writing with indentation for 4 single-byte spaces.
Write the return value as return
.
Be careful not to make the function name the same as the built-in function.
function_1.py
def hello_python(): #There is no need for formal arguments.
return 'Hello, Python!'
def average(a, b): #Specify two formal arguments.
return (a + b) / len([a, b])
def greeting(word, n = 3): #Specify the default value of the formal argument (second argument in this example).
return (word * n)
After creating the function, call the function name where you want to execute it. Just creating a function does not mean that it will be executed.
function_2.py
print(hello_python())
print(average(1, 3))
print(greeting('Hello!', n = 2))
print(greeting('Bye!')) #If the second argument is not specified, the default value will be used.
Variables defined inside a function (local variables) cannot be used as the same object outside the function. Variables defined outside the function (global variables) can be used inside the function, but if you want to reflect the changes inside the function, you need to specify that they are global variables when defining the function.
function_3.py
def add_one(n):
a = 1
return n + a
print(add_one(2))
print(a) #An error occurs because the variable a is not defined.
function_4.py
a = 1
def add_one(n):
return n + a
print(add_one(2))
print(a) #No error occurs.
function_5.py
a = 5
def add_one(n):
a = 1 #Local variables
return n + a
print(add_one(2))
print(a) #Changes in the value of variable a within the function are not reflected.
function_6.py
a = 5
def add_one(n):
global a
a = 1 #Global variables
return n + a
print(add_one(2))
print(a) #Changes in the value of variable a within the function are reflected.
Here, I explained the basics of "functions" in Python. Particular attention should be paid to the scope of variables.
What is the programming language Python? Can it be used for AI and machine learning?
Recommended Posts