Basics of functions

Basics of functions

Lesson Details:
June 29, 2020

I: Introduction

A: Function plays a vital role in program. It is a block of statements written as a single unit, which performs some specific task on some input and gives some output.

B: In this article we will discuss about programming language.

C: We will also discuss about connecting function to an object.

D: Python is a great language with a focus on readability and a simple syntax.

II: Body

A: Basics of functions

B: A function is a block of statements that performs a specific task.

C: To make a function, create a new file called This file’s code may look like this:

def squareit(n): if n == 0: print("Can't square zero!") return else: print("The square of", n, "is", n*n) squareit(2) 1 2 3 4 5 6 7 8 def squareit ( n ) : if n == 0 : print ( "Can't square zero!" ) return else : print ( "The square of" , n , "is" , n * n ) squareit ( 2 )

D: As you can see, the def statement starts our function definition. Next comes the name of the function, which in this example is “squareit”. On the next line, we have our first indented block of statements. Here we check whether the value passed to the function is 0; if it is, we simply print an error message and return (so the function returns without doing any calculations). If it isn’t 0, we print the result of calculating the square of the number. Note that we don’t use parentheses or semicolons for this line; everything after the colon (“:”) is treated as part of the same line.

E: The second indented block contains all of the code that gets executed when the function is called. In this example, we only pass one argument to the function; however, you can pass multiple arguments by separating each value with a comma. You can also pass no arguments at all by simply leaving empty parentheses. Now you can run your function by typing “python” at your terminal. Remember to include the “.py” extension so that Python knows to execute it as a Python program!

F: You should see that it printed out “The square of 2 is 4”! Now let’s fix this function so that it works correctly when given 0 as an argument. The first step is to change our if statement so that it looks like this:

def squareit(n): if n == 0: print("Can't square zero!") else: print("The square of", n, "is", n*n) 1 2 3 4 5 def squareit ( n ) : if n == 0 : print ( "Can't square zero!" ) else : print ( "The square of" , n , "is" , n * n )

G: As you can see, I’ve made two changes here. First, I removed the colon from the end of the first line; this means that instead of treating it as part of the function definition itself, Python will treat it as part of the if statement. Second, I added an else statement to check for when no number has been passed to the function. In this case, rather than printing an error message, we simply re-print the body of our function, but with no error message at all! This way, we get to keep our output from before while still avoiding an error when no number is passed to the function. You can run this new version by typing “python” again at your terminal! This time you should see that nothing prints when 0 is passed to your function, but your original output will still show up when a nonzero number is passed in. You’ll notice that in both cases, Python automatically calls the return statement in order to exit the topmost code block when it reaches the closing curly brace on its own! Remember, in Python everything is done using blocks of code grouped together by indentation, so there are no curly braces needed in most cases! Also note that you can run a function in an interactive interpreter in exactly the same way by typing “help(functionname)” in IPython or “python -i” in a normal Python interpreter! Just be sure to add the “.py” extension if you want Python to run it as a script rather than importing it into an interactive interpreter session!

H: Now let’s move on to another kind of function called a class function. Unlike simple functions which do not retain any state between calls, class functions operate on state stored within their objects and therefore remember and operate on values between calls! Let’s take a look at how we might use class functions in our calculator example from earlier:

class Calculator: def __init__(self): self._num = 0 self._result = None def _run(self): self._run() def add(self, num1=0, num2=0): self._run() self._result = self._result + num1 + num2 def multiply(self, num1=0, num2=0): self._run() self._result = self._result * num1 * num2 def divide(self, num1=0, num2=0): self._run() self._result = self._result / num1 / num2 def _run(self): if self._result == 0: print("Error!", "Division by zero") return else: print("Result:", self._result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Calculator : def __init__ ( self ) : self . _num = 0 self . _result = None def _run ( self ) : self . _run ( ) def add ( self , num1 = 0 , num2 = 0 ) : self . _run ( ) self . _result = self . _result + num1 + num2 def multiply ( self , num1 = 0 , num2 = 0 ) : self . _run ( ) self . _result = self . _result * num1 * num2 def divide ( self , num1 = 0 , num2 = 0 ) : self . _run ( ) self . _result = self . _result / num1 / num2 def _run ( self ) : if self . _result == 0 : print ( "Error!" , "Division by zero" ) return else : print ( "Result:" , self . _result )

I: This example shows how to write a simple class method for dealing with arithmetic operators in Python 3. To create a class method in Python 3, you must use “method_name = staticmethod(function_name)” where method_name becomes the name of the method and function_name becomes its actual implementation! To see how this works in practice, let’s go over each line individually:

J: Line 1 begins with “class Calculator” which defines our calculator class itself; everything afterwards until line 19 defines methods which are available for any instances of this class! These methods can be called simply by typing “calculator(arguments)” where arguments represents zero or more arguments which are passed to the methods whenever they are called! Line 2 begins with “def __init__(self), which just defines our constructor for creating instance of calculator class! Lines 3-4 declare two variables ‘self._num’ and ‘self._result’ for storing current number and final result respectively! Line 5 declares method ‘_run()’ which does arithmetic operations on given numbers internally! Line 6 declares private method ‘add()’ which adds two numbers passed as arguments while lines 7-8 declares private method ‘multiply()’ which multiplies two numbers passed as arguments while lines 9-10 declares private method ‘divide()’ which divides two numbers passed as arguments! Line 11-14 declares public method ‘_run()’ which displays result on screen after performing calculation! Line 15 has keyword ‘class’ followed by name of class ‘Calculator’ followed by colon(:) and further followed by list of method definitions enclosed within curly braces { }! Line 16 declares public

Course content