I'll keep a note of how to create a function in Python.
Let the function name be function.
def function():
pass
#No arguments
Pass data (int, str, class, etc.) to the function. Let the argument (hikisu) name be args.
def function(args):
#With arguments
print(args)
def function2(args1,args2):
#You can take as many arguments as you like
print(args,args2)
def function3(args="Hello World"):
#Initial value can be set for the argument
#If there are no arguments at the time of the call, args will"Hello World"Enter
print(args)
Returns the result of processing in the function.
def function(args):
#There is a return value
n = args * 2 #Double the argument and return
return n
def function2(args,args2):
a = args + args2
b = args - args2
return (a,b) #Return as tuple type
Any type can be returned
To call a function, you can call it with the function name ().
def function():
print("Hello World")
function()
#------------
#Hello World
#------------
If there is no argument, you do not have to write anything in (). I get an error when I write it.
TypeError: function() takes 0 positional arguments but 1 was given
Arguments are written in ().
def function(args):
print(args)
function("Hello World")
#------------
#Hello World
#------------
TypeError occurs if no argument is set.
TypeError: function() missing 1 required positional argument: 'args'
The return value can be put in a variable.
def function(args):
n = args * 2
return n
n = function(5)#Assign the return value of the function function to the variable n
print(n)
#--------
#10
#--------
You can also call another function from within a function.
def function(args):
n = function2(args,10)#Calling the function2 function from within the function function
print(n)
def function2(args,args2):
n = args * args2
return n
function(5)
#--------
#50
#--------
Recommended Posts