October 2

Functions

Functions are a convenient way to divide your code into reusable block, make it more readable and save your time.Writing functions are way to define interface and which you can incorporate into your own or other program.
Python functions should start with def and every Python function returns a value,if the function ever executes a return statement, it will return that value, otherwise it will return None

Output of the above code will be :

Execution will follow like this :

  • When def user_function_name block was run,a function called user_function_name was created
  • When print first_function() was run, function first_function was executed
  • print statement was executed and “My First Function” was printed on screen
  • return True , will send back to the main program and True will get stored in place where the function was called
  • finally print first_function() will print True on screen
  • You can use following types of arguments:

      i. Required arguments
      ii. Keyword arguments
      iii. Default arguments
      iv. Variable-length arguments

    Required arguments User need to call this function with correct order. Number of argument while calling should be same as function definition.User will get error if number of argument doesn’t match.

    Function should be called with one argument.

    Keyword arguments are come into picture while calling of function.Arguments will be defined in key-value pair. In Keyword argument order does not matter.

    Both function will print same output on the screen

    Default arguments We provide default value in function declaration itself. If user does not provide any value to default parameter while calling function, it will take the default value.

    Both function will print same output on the screen

    Variable-length arguments When we do not know how many argument will be required at the time of calling, then we use Variable length argument. Argument must start with an asterisk(*). All non keyword argument will be stored in that variable as tuple.If calling function does not provide any value then argument will be an empty tuple.

    Output of the function will be