Skip to main content

Python 3 Part 7 - Functions in Python 3

Functions in Python 3

Table of content

  1. Function
  2. Default value of argument
  3. Passing arbitrary arguments using *args
  4. Passing arbitrary keyword arguments using **kwargs

Function

Function is a block of code executed when it is called. The syntax for defining a function is as below.

def function_name(<arguments):
    statement
    return statement


Example of a simple function which takes no arguments.


Function which takes arguments and returns addition.


Function passing arguments with key.


Default value of argument 

We can set default value for argument, if value is not passed for that argument it takes default value.


Passing arbitrary arguments using *args

If the number of argument function is not fixed we can use arbitrary argument


Passing arbitrary keyword arguments using **kwargs

We can pass arbitrary number of arguments with some values.

Thank you folks. If you like this Python 3 post, please do checkout my other post on  Django with Python 3 series


Most viewed

Ruby on rails part 6 - Blocks , lambda, procs and closure

 Blocks , lambda, procs  and closure Table of content  1. Blocks 2. Lambda 3. Procs 4. Closure Blocks  Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or between brackets {} 
. Blocks can have multiple arguments
. The argument names are defined between two pipe | characters. Blocks are typically used with ‘each’ method which iterates over a list. Syntax of block using {} ['List of items'].each { | block arguments|  block body }  Syntax of block using do-end ['List of items'].each do | block arguments |      # block body end Example of block declared as do-end with each method.   [ 1 , 2 , 3 ].each do |num| puts num end     Output   $ ruby block_with_each.rb 1 2 3 $    Blocks can also be saved in variables or passed as argument to another function.   yield is a Ruby keyword that is used to call a block. When you use the yield keyword, the code inside the block will run. Example of saving a bl