How To Define Your Own Functions In Python

There are many built-in functions in python programming that you cannot tell or get to know all these functions even though you can try learning them all but the most important this is that, you can create your own functions in python environment to perform whatever task you want your computer to perform for you.

There are plenty of built in functions some of which are as follows:

print() function: this function is used to output all the actions python performs behind the scenes.

e.g   print('Bestbrain') will output the string Bestbrain


 abs() function: this function also returns the absolute value of every real number you type inside it as an argument

e.g  abs(-1234)  will output 1234

input() function : this function also helps a user to input a keyword 

e.g sat = input('enter your name here :\n')
this code when run will output the message inside the input function and wait till the user input his or her name. i.e. ' enter your name: '

int() function: this function changes any real number into integer. Mind you, strings which consist of letters cannot be converted to integer.

e.g. int(234.456) will give 234 as output
      int('Bra Brainy') you give you an error

round() function : this function all rounds a value to the number of decimal places specified

e.g. round(23.567,2) will be 23.57 and round(345.678,0)  will output 346 0 and 2 are the decimal places specified.

Knowing all these functions, its about time we also learn how to create our own functions.
The following steps must be followed

  • first and foremost, the def keyword must come first followed by the function name 

  • That is if the function name is may calculate, then our function that we create will be

  •  def calculate():     we bring the two brackets after the function name to make it complete.
You can then assign an argument to your function like  def calculate(x,y):

After defining your function then you assign whatever your function must do under the function with proper indentation

e.g def Calculate_area(x,y):
                        return x*y

You then call your function and assign the proper variable to it for it to work for you. e.g.
 def Calculate_area(x,y):
                        return x*y
Calculate_area(4,6) 
and the output will be 24



No comments:

Post a Comment