A Fuction has 2 steps; Define & Call .
It operates when it is called.
# Define
def func_name():
operation
# Call
func_name()- Example
def printer():
print("Python!")
printer()
#'Python!'It returns the result object of a Fcuntion When the Function is called.
Using return can assign the result of a Function as an object.
Look at the difference between print and return
With print, it just prints the result.
def adder(a, b):
print(a + b)
res = adder(1, 2)
#3 (print operation)
res
#Nothing is shown!With return Statements:
def adder(a, b):
return a + b
res = adder(1, 2)
#Nothing is shown, but assignment is done!
res
#3When Using a Function, the variables inside of the Function and ones outside of the Function are separate.
Inside of Objects like Classes or Functions are called Local Environments,
and Outside of Objects is called Global Environment.
The variables belong to Local Environments are called Local Variables,
and the variables belong to Global Environment are called Global Variables.
Local Variables cannot affected to Global Variables
x = 2 # 'x' is a global variable.
def funct():
x = 10 # This 'x' is a local variable.
print(x)
funct()
10 # It's about the local.
x
2 # It's about the global.But in Local(in this case, inside of Functions), you can use Global Variables.
This way is **not recommended** because operations in the local environments get affected to the Global Environment and throw Errors & Exceptions, despite Local operations are CORRECT!.
That's why we should use Arguments.
x = 2 # 'x' is a global variable.
def funct():
print(x)funct() 2 # Local 'x' is not defined: then it refers to Global.
### ```global``` Statements
To change **_Global Variables_** in **_Local Environments_**, use ```global``` Statements.
```python
x = 2 # 'x' is a global variable.
def funct():
global x # For now, we use this 'x' as a global variable.
x = 10 # Assign 10 to 'x' in the global environment.
print(x)
funct()
#10
x
#10
A Function can have arguments.
def adder(a, b):
return(a + b)
adder(1, 2)
#3Using arguments should be careful, because of its data type.
If you don't you would encounter many Errors & Exceptions.
adder('q', 2)
#Trackback (most recent call last):'
#TypeError: Can't convert 'int' object to str implicitlyThe way to use arguments depending on its order.
def adder(string, num1, num2):
print(string, ': ', num1 + num2)
adder('Result', 2, 3)
#'Result : 5'The way to use arguments depending on its keyword(parameter).(Don't need to keep arguments in order!)
When using Keyword Arguments, you can set default values.
The default values should be Constants
def adder(srt=string, num1=1, num2=2):
print(srt, ': ', num1 + num2)
adder(num1=4, str='Result')
#'Result : 6'Keyword Arguments should be defined behind Positional Arguments. This is correct:
def func(a, b=1):The following is wrong:
def func(a=1, b):Using *, you can express variable numbers of Positional Arguments.
At this time, *argsare gathered as a Tuple.
It should be the end of the Positional Arguments lists.
- Example:
*args
def printer(num1, num2, *args):
print('num1:', num1)
print('num2:', num2)
print(args)
printer(2, 3, 4, 5, 7, 24)
num1: 2
num2: 3
(4, 5, 7, 24) # a tupleUsing **, you can express variable numbers of Keyword Arguments.
At this time, *argsare gathered as a Dictionary.
It should be the end of the Keword Arguments lists.
- Example:
**kwargs
def printer(num1, num2=11, **args):
print('num1:', num1)
print('num2:', num2)
print(kwargs)
printer(2, num2=4, num7=5, num8=7, num9=24)
num1: 2
num2: 4
{'num8': 7, 'num9': 24, 'num7': 5) # a dict- Order of Arguments:
(arg, *args, kwarg, **kwargs)
def printer(num1, num2=11, **args):
print('num1:', num1)
print(args)
print('num2:', num2)
print(kwargs)
printer(1, 2, 3, num2=4, num7=5, num8=7, num9=24)
num1: 1
(2, 3) # a tuple
num2: 4
{'num8': 7, 'num9': 24, 'num7': 5) # a dictFor Readability, You can attach Documentation Strings.
Just put the strings at the beginning of the function body; the first line of it!
def adder(a, b):
'This function operates addition.'
return(a + b)
adder(1, 2)You can make multilined-Docstrings.
def adder(a, b):
'''
This function
operates
addition.
'''
return(a + b)**_Docstrings doesn't appear when the function is called.
adder(1, 2)
3To show Docstrings(if it exists), call the help() function.
help(adder)
Help on function adder in module __main__:
adder(a, b)
This function operates addition.To show the raw Docstrings, call the __doc__ variable.
It is the internal name of Docstrings within the function.
adder.__doc__
'This function operates addition.'
print(adder.__doc__)
'This function operates addition.'