Methods and Functions

Methods:

Methods are built-in functions that are built on objects. Examples: append, add, pop, split etc,.

Python Standard Library

Functions:

Functions are nothing but the reusable block of code.

In python, name of the function should be in lower case.

Example

def name_of_function():
  '''
  Docstring explains function.
  '''
  print ("Hello!")

>> name_of_function()
>> Hello!

With parameters

Example

def name_of_function(name):
  print ("Hello " + name)

>> name_of_function("Bhavya")
>> Hello Bhavya
  • return keyword will be used to send back the output of the function instead of printing it.

For example: In some cases, we need to assign the output of the function to a variable instead of printing it out, then we use return keyword to return the output of the function.

Example

def sub_function(x, y):
  return x - y

>> result = sub_function(10,2):
>> result
>> 7

Return the boolean values

some functions will be defined to return the boolean value.

Example

# Find out if the word 'dog' is in string
def dog_check(mystring):
    if 'dog' in mystring:
        return True
    else:
        return False

>> dog_check('my dog ran away')
>> True
>>
>> dog_check('Dog ran away')
>> False

def dog_check(mystring):
    if 'dog' in mystring.lower():
        return True
    else:
        return False
>>
>> dog_check('Dog ran away')
>> False

The function can also be defined in such a way that it just returns a boolean value based on the condition given

Example

def dog_check(mystring):
    return 'dog' in mystring.lower() 

>> dog_check('my dog ran away')
>> True