## Example 1: Defining a non-parameterized function which returns nothing
# use the 'def' keyword to define a function followed by its name with
# rounded brackets, function names are recommended as snake_cases
def my_function1():
# this is function's body
# Note: 'pass' is to ensure the program runs this empty function
pass
# Note: If the function is not empty 'pass' is not required at all
## Example 2: Defining a function with parameters which returns nothing
def my_function2(var1, var2):
pass
# Alternative way is to describe the input/return type hints
# as they are just hints, it does not matter what is send/returned
# But this acts as self documenting code, so good to use in bigger projects
def my_function2(var1: int, var2: str) -> None:
pass
#3 Example 3: Defining a function with a default parameter and return statement
def my_function3(var1, var2, var3, return_op=False):
# Note: 'return_op' is a default parameter, they should always follow later
if return_op:
return var1 + var2 + var3
# calling a function without a return statement or
# did not hit the return condition in a function
# will returns 'None' by default
print(my_function1()) # None
# calling a function and passing the arguments
print(my_function3(30, 20, 10, return_op=True)) # 60
# check if it is a function using the built-in 'callable()' function
# classes and functions are the callables
print(callable(my_function1)) # True
## Example: Define a function that also takes a function as parameter
def square_or_some_fun(number, some_fun=None):
if some_fun:
# if 'some_fun' is a function it can be callable, can check it
# with 'callable()'
output = some_fun(number)
else:
output = number ** 2
return output
def cube_num(n):
return n ** 3
## Assigning a function to a variable/data structure:
# It is not same as calling a function.
# Notice: No rounded brackets on the function
my_var = cube_num
print(my_var) # <function cube_num at 0x000001C1FDFAF0D0>
# Note: 'my_var' is only referring to 'cube_num()', so both are the same
print(my_var(2)) # 8
# passing a argument to a function
print(square_or_some_fun(2)) # 4
## Passing a function as argument
print(square_or_some_fun(2, my_var)) # 8
# passing a list at 'some_fun()' will raise 'TypeError'
print(square_or_some_fun(2, [4, 4])) # TypeError: 'list' object is not callable