PYTHON 3 – WRITING FUNCTIONS AND OWN MODULE – COMPLETE GUIDE

In this chapter, you will learn how to build custom, or your own, Python functions. After learning how to define and call a simple Python function, you will learn how to define required and keyword argument functions. This chapter covers setting up default function arguments and expecting return statements, which will make your functions useful. You will also learn how to create and consume Python modules.

The chapter will conclude with another coding exercise where you will create your own custom Python function.





Prerequisite for this course

  1. A beginner
  2. python installed System (IDE/Interpreter).
  3. Knowledge of Variables.
  4. knowledge of conditional statements and loops.
  5. A notepad to take notes


Lesson 5 - Working with Functions






What are the functions?

As a beginning programmer, compartmentalization is an important concept that you can apply in your Python programs.

What does compartmentalization mean?
The simplest definition is that it allows you to reuse code somewhere else in the same program, or in another program.


Functions are how you implement compartmentalization in your Python programs. This is especially true in the case of similar procedures everywhere, such as setting up usernames and passwords and searching for the existence of a term, among others.


They make your work more efficient since you do not have to start from scratch. As a result, compartmentalization and functions, speed up the entire development process and generate substantial savings.
Functions are the basic unit of reusable code in Python. So, let's take a look at how they work.

Basic Syntax of writing a function


def--> keyword helloworld() --> Name of function : -->to define end of function
To define a function, use the def keyword. Let’s try it now, by entering the following on the editor window:


def main():
    helloworld()

def helloworld():
    print("Hey you called hello World!!")

##Shows the name of the currrent module   
if __name__ == "__main__": main()

------------------------------

Hey you called hello World!!



For understanding more about the main function you can refer the What does if name == “main”: do?

In the example, we have written a HelloWorld function using the def keyword which prints the statement "Hey you called hello World!!".

These examples are simple.  However, functions in the real world may be more complicated and longer than these. Keep in mind that functions should perform ‘singular’ roles. You should not create a function that performs two different tasks. Otherwise, your functions will become overly complicated and make your programming work more difficult.

If you are advance programmer why don't you share some of the practices to be followed while writing functions in the comment?💓


It would also be great if you share some of your best piece of shortcode that does wonder with execution👇.




mmmm.. This is not returning anything since function should return..ryt ?

Ideally, this is not the right sense of using functions on your large codebase since this remains static and its of less significance. The new Python syntax is the return statement, with the word return followed by an expression. Functions that return values can be used in expressions, just like in math class. When an expression with a function call is evaluated, the function call is effectively replaced temporarily by its returned value. Inside the Python function, the value to be returned is given by the expression in the return statement.


###Updated the same code to return the value
def main():
    x = helloworld()
    print("Returning :",x)

def helloworld():
    return "Hey you called hello World!!"

##Shows the name of the currrent module   
if __name__ == "__main__": main()

-----------------------------

Returning : Hey you called hello World!!

From the provious example we can check instead of directly printing we are now returning the string.

We have discussed defining and calling a simple function. In the next section, you will learn about required argument functions, which are more interesting than the simple function examples we have covered so far.


Passing Arguments

In this section, you will learn more about required argument functions, which send an argument or arguments back to the function. The function call passes the argument back to the function.


If the function does not receive an expected argument back, an error results. Therefore, we refer to this type of function as a required argument function. If the required argument is missing, our program returns an error.


To illustrate, let’s write a function with a single required argument first. We will then write another function with several required arguments.



def main():
    x = helloworld("python")
    print("Returning :",x)

def helloworld(a): # passing the arguments
    return "Hey you called hello World!! " + a

##Shows the name of the currrent module   
if __name__ == "__main__": main()

-----------------------------------

Returning : Hey you called hello World!! python

In our function definition, the required argument, a, is enclosed in a parenthesis.
That is the end of the discussion on required function arguments. We will now look at keyword argument functions.

We will discuss another form of a function that does away with the order of the arguments passed in our function calls.


In the earlier example, we tried passing a single argument which worked perfectly fine. But , what if we passing multiple argument. Do we need to pass that in order? Will it throw an error if not passed sequentially ? What if we want to skip one argument.

In the next section, we are going to answer all those questions asked.


If you are still in the race to complete this reading try answering this question on our comment sections

What will be the O/P? Add answer to our comment section.💭💬

def printLine(text):
print(text, 'is awesome.')

printLine
('Python')


# Passing multiple arguments



def main():
    x = testnum(10,10,10,10)
    print("Sum is  :",x)

def testnum(a,b,c,d):
    return a+b+c+d
##Shows the name of the currrent module   
if __name__ == "__main__": main()


--------------------------
Sum is  : 40


In the above example, it can be seen that we passed  4 args (a,b,c,d) with values as 10 to each one and its returning the sum of all the arguments.


def main():
    x = testnum(10,10,10)
    print("Sum is  :",x)

def testnum(a,b,c,d):
    return a+b+c+d
##Shows the name of the currrent module   
if __name__ == "__main__": main()



---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-d26f776251ba> in <module>
      6     return a+b+c+d
      7 ##Shows the name of the currrent module
----> 8 if __name__ == "__main__": main()

<ipython-input-5-d26f776251ba> in main()
      1 def main():
----> 2     x = testnum(10,10,10)
      3     print("Sum is  :",x)
      4
      5 def testnum(a,b,c,d):

TypeError: testnum() missing 1 required positional argument: 'd'


We emphasized that function arguments must be passed in the same order they are defined. Otherwise, an error or errors may result.

This type of function does away with that requirement. To overome this we can check the default function arguments. Consider the example below.



def employeeInformation(name, ssn, position):

    print("Name:", name)

    print("Ssn:", ssn)

    print("Position:", position)

    return
employeeInformation(name="Mark", ssn="000-00-000", position="founder")


--------------------------------
Name: Mark
Ssn: 000-00-000
Position: founder



As expected, the function call passes the arguments back to the function, and the function displays the arguments as output

If we only pass arguments for the name and position parameters, we will get an error.  This is because the function is also expecting an argument for the ssn parameter.

We can avoid this limitation by setting default arguments for our parameters.

How do we define default arguments? Let’s edit our program to illustrate.

Let’s edit our function definition by inserting default values for the function parameters.




def employeeInformation(name="Mark Lassoff", ssn="000-00-000", position=""):
    print("Name:", name)

    print("Ssn:", ssn)

    print("Position:", position)

    return
employeeInformation(name="Mark", ssn="000-00-000")

---------------------------

Name: Mark
Ssn: 000-00-000
Position:


The program, therefore, runs without any error, even if we do not pass any arguments to it via the function call.

Creating and consuming modules in python

We have only used built-in Python modules, such as the date, time and calendar methods. In this section, you will learn how to create and use your own custom Python modules.



def greetEnglish():

    return "Greetings!"

def greetSpanish():

    return "Buenos Dias"

def greetFrench():

    return "Bon Jour"

def greetHebrew():

    return "Shalom"





We will save the file as testmodule.py. You need to save modules in the same directory where all your other Python files are saved. Otherwise, you will encounter an error when you try to use the module in your programs.


Let’s open another editor window and enter the following:


import testmodule
print(testmodule.greetEnglish())
print (testmodule.greetFrench())

We have now learned how to create and consume our own custom module. Earlier in this chapter, you learned how to create and consume your own custom functions.

You have also learned how to create the required argument and keyword argument functions.

You have also learned how to set up default arguments for your functions, and how to use the return statement for your function calls. It’s now time for your coding exercise.



All the hardwork put to read should be worth if its practiced.

Practice Time!🙌


The formula to convert Celsius to Fahrenheit is as follows:

Fahrenheit = Celsius * 1.8 + 32

Example: 32 = 0 * 1.8 + 32

Example: 212 = 100 * 1.8 + 32
-------------------------------------------------------
The formula to convert Fahrenheit to Celsius is:
Celsius = (Fahrenheit – 32) / 1.8

Example: 100 = (212-32) / 1.8


  • Considering the equations above, write a function called fToC that returns the temperature in Celsius when it gets passed the temperature in Fahrenheit. The function call would look like this: celsTemp = fToC(fahrTemp).
  • Considering the equations above, write a function called cToF that returns the temperature in Fahrenheit when it gets passed the temperature in Celsius. The function call would look like this: fahrTemp = cToF(celsTemp)
  • Write a function that will convert either Celsius to Fahrenheit or vice-versa. The function should receive two parameters. The first parameter is the temperature to convert. The second parameter a Boolean indicating whether the value sent is Celsius or Fahrenheit. 
  • Test your functions to make sure that they all work. This can be done by writing function calls to them and ensuring they return the expected values.



Please try and share the gist link with us. Will you ?

Happy coding!😅


Hey I'm Venkat
Developer, Blogger, Thinker and Data scientist. nintyzeros [at] gmail.com I love the Data and Problem - An Indian Lives in US .If you have any question do reach me out via below social media


EmoticonEmoticon