Functions in python(def) - Letsprogram

Share:
Before discussing functions first of all why function?
Whenever you want to repeat multiple lines of codes many times then you have to use functions because it reduces the memory consumption, the length of the code, speed of the process.

In python defining a function is done with the keyword called def. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented.
Example :

def fib(n):
    """Print the Fibonacci series up to n """
    a,b = 0,1
    while a<n :
        print(a, end="")
        a,b = b,a+b

This is an example of a function in python.
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string. It’s good practice to include docstrings in code that you write, so make a habit of it.

Defining the function will never give you the output instead you have to make a function call then the function will execute.
>>fib(n)

Coming from other languages, you might object that fib is not a function but a procedure since it doesn’t return a value. In fact, even functions without a return statement do return a value. The value is None it is actually a built-in value. In interpreter mode, you cannot see the None value by the just function call.

>>fib(0)
>>print(fib(0))
None

Actually, we can give the function name to another value. This serves as a general renaming mechanism or aliasing. The value of the function name have a type that is recognized by the interpreter as a user-defined function.
>>> fib
<function fib at 0x000001CD6AE25430>
>>> f=fib
>>> f
<function fib at 0x000001CD6AE25430>

By the above example, you may understand that even after giving function name to another value the value also has the same type.

Arguments in functions

The argument is a value that is sent to the function when you are calling the function.
Parameters are variables that are listed when defining a function.

You have to give the same number of arguments as listed in the function definition.
For example, the function fib is taking only one argument but you gave it three arguments then you will get an error.

Arbitrary Arguments: If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. By putting   **before a parameter then it can accept a dictionary into it.

>>>def function(**dic):
   print("my name is",dic(name))
>>>function(fname="max",lname="Payne")
my name is max

Keyword Arguments: You can give the argument value with the key in this way the order in which you are giving the value is not important.

def example(bool,try=4,message="Please try again!"):
    while True:
        ok=input(prompt)
        if ok in ('y','ye','yes',1,'True'):
            return True
        if ok in('no','n',0,'False'):
            return False
        try=try-1
        if try<0:
            raise ValueError("Invalid Response")
        print(message)

You can call this function in many ways like :
example('no')
example("Python Blog",2)
example("True",4,"Come on,only yes or no")

There are three possibilities to call the function example because of default arguments.
Function calls in the file are valid.

But all the function calls below are invalid.
parrot() 
parrot(voltage=5.0,'dead') 
parrot(110,voltage=220)
parrot(actor="IronMan")

No comments

F