17:Modules
Modules
Divide and conquer is the most widely used technique in problem solving (political problems too). It is possible that our problem contains many small problems. Modularity enables us to write such programs which are more complex and seem difficult to solve in a single go.
- Modules is a general term used in programs.
- When our program is more complex than we can distribute it in different modules.
- Every module performs its operation and returns a result that can be used for the next operation.
- Modules can be called functions or methods.
- Next, we use the word “function” for modules.
Library Functions
- Library functions mean these functions are already built-in and we don’t need to build ourselves during programming.
- Library functions reduce the programming time and complexity.
- For example, the print is the most commonly used function.
- In fact, print sends a request to the operating system and provides it data that will be shown on screen.
- The operating system receives the request and data and ready the display devices to show.
- All this request and data sending mechanism is written inside print.
- It means that we don’t need to write the request methodology in our program every time.
- Similarly, the input function is another example.
- This function displays a data (string) on screen and asks the keyboard to enter the data.
- When the user presses the enter key, the input data reaches our variable.
- The input function first sends a request to the operating system to display the string on the screen and OS ready the display device for it.
- After successful completion of display, another request is sent to OS for keyboard availability.
- When the user starts typing, the function waits for the enter key. As the user presses the enter key, the function stops taking more data and sends an end request to the OS for the keyboard.
- For every library function, a library must call for it.
- We call the library by its name.
- In Python, for calling a library we use import keyword
- Sometimes, some libraries that use Python interpreter call them automatically, such as builtins.
- The print and input functions are part of builtins so we don’t need to explicitly import it.
- But the other libraries are required to import every time.
- For example, cos is a common trigonometric operation which is required to perform on angles.
- For using tan function on some angle, we are required to import math.
import mathx = math.cos (45)
Code 1: Using import to Call a Library
- When we call an imported function then we are also required to use the library name with it for consumption.
- Consuming a function in our program is called calling.
- In Python, we can use smart naming for libraries using as keyword.
import math as mtx = mt.cos (45)
Code 2: Shorten Name with the Help of as
- We use it as a keyword and write a small name (math => mt).
- All the time we are required to use this library in our program; we use short names rather than full names.
- It reduces typing efforts because in program, it may be required to use this word multiple times.
- Math is a small name but many library names are very long such as matplotlib, so we have to make it smart.
- To reduce the typing efforts for the library, we can also import only required functions from a library.
from math import cosx = cos (45)
Code 3: Importing Function from a Library
- This time we import cos from math library. We don’t need to write the library name with cos function as it is required in code 1 and 2.
- But this method is also restricted to use only this function. if required to use some other function like tan the we are again required to import it or import the full library.
- We can also import more than one function from a library in a single line.
from math import cos, tan
Code 4: Importing more Functions in a Single Line
- For good programming, you should know more and more libraries and their methods.
- The libraries made the python most popular because python may have the largest number of libraries for data engineering and machine learning in comparison to any other language.
Components of Functions
- Every function has four components.
- Name
- List of Parameters
- Body
- Return value
- The name of the function is the label.
- cos, tan, print, input, int, float, str. These are names of functions.
- If you are creating your own function which is often required in programming then you have to decide the name by yourself.
- Parameter (s) are the inputs that we provide to a function. Functions use these values inside to perform operations.
- When we call a function, the value of the parameter sends a copy of values.
- For example, in code 3, we pass the value 45 in parameter. The function cos generates a copy of value 45 and uses this copy for its internal calculation.
- Like print (“Hello World!”). The string is input parameter “Hello World!”.
- Here is the only single parameter but there may be more parameters.
- For example, print (“aa”, 1, 3.2). The time print function uses 3 parameters.
- It is also possible that no parameters are required to call a function.
- The body is the actual area which is written to perform an algorithm.
- When a function performs its operation then it may require to return some results that can be used in some further operation.
- For example, cos function returns the cos ratio. Similarly, the int function converts the parameter into integer and return.
- For a function, we must have the understanding of input parameters and return value
Custom Functions
- If you can define how many functions in your program are required to write, you are a good programmer.
- If our program is required to write one or more programs then first, we define them and then call.
- Example 1: we have to write a program that has a list of products and we want to print such products whose price is more than 200.
- It is also required to print the product names for less than 100 price.
products = [  [1, "Laptop", 999.99],    [2, "Smart phone", 499.99],  [3, "Tablet", 299.99],  [4, "Smart watch", 199.99],  [5, "Head phones", 89.99]]
Code 5: A List of Products
- We have two problems to solve. Find products with prices more than 200 and less than 100.
- We can see that Laptop, Smart phone and Tablet have prices more than 200.
- Similarly, Head phones less than 100.
- As we know that we have to write two different modules.
- Consider the first module (finding products with prices more than 200).
- List of all products as input.
- Create an empty list.
- Loop through the items.
- In each iteration, check the item price.
- If the price is more than 200 then append to the empty list.
- After completion, the iterations return the new list.
def getProductsMoreThan200(products):Â Â selected_products = []Â Â for product in products:Â Â Â Â if product[2] > 200:Â Â Â Â Â Â selected_products.append(product)Â Â return selected_products
Code 6: Creating a Function get Products for Higher Price Products
- Put this code in line 1 of the program.
- The def keyword will indicate the interpreter that next lines are a function.
- The def is the shorter form of define, which means a function is going to be defined.
- getProductsMoreThan100 is the name of the function. This is a little bit long but self-explaining.
- products is the input of the function.
- when we complete the for loop and exit to it, we return the selected_products, which is the return variable.
- When a function occurs return keywork, it immediately returns from the function.
- If some variable or value is written in front of it, then the value also returns.
- It is also possible that no value or variable defined for return then function returns nothing.
- Now we have a second problem. Pseudocode for this as follows
- Write def as keyword, write the name which should be self-explaining and write the input parameters in parenthesis.
- The solution of this problem looks much similar to the previous one and we just have to change the if condition.
- By writing similar code, we only made a necessary change.
def getProductsLessThan100(products):Â Â selected_products = []Â Â for product in products:Â Â Â Â if product[2] < 100:Â Â Â Â Â Â selected_products.append (product)Â Â return selected_products
Code 7: Selecting the Product with Lower Price
- Put this code after the ending code 6.
- Put this code below to code 7.
products = [  [1, "Laptop", 999.99],    [2, "Smartphone", 499.99],  [3, "Tablet", 299.99],  [4, "Smartwatch", 199.99],  [5, "Headphones", 89.99]]costly_products = getProductsMoreThan200 (products)affordable_products = getProductsLessThan100 (products)print (f"Costly Products (more than $200):{costly_products}")print (f"Affordable Products (less than $100):{affordable_products}")
Code 8: Calling code of both Functions
- Consider that execution scheme.
- When the interpreter starts execution and if it encounters a def, it leaves it.
- If more than one def has been defined in the program then all the code will not execute.
- The code which out of the functions, executes first like code 8.
- During this independent code, its encounter with function calling (line 23).
- Now the code in function will execute line by line which was initially left.
- After execution of all the code, it returns selected_products.
- This return value is assigned to costly_products.
- When all the lines in function executes and return the value its comeback to line 24.
- Here it will again face another function and it will start executing a second function.
- Again, all lines executed in getProductsLessThan100 and list of selected products return to affordable_products.
- On line 25 and 26, we print the output.
- In Python, it is possible to return multiple values from a function. No other language provides this facility. In code 9 we return two values but if we require more than 2 values, we can do it.
- The returning values should be separated by comma.
return value1, value2
Code 9: Returning Multiple Values from a Function
- We can use default parameters as input.
- There is a possibility where parameters may be sent.
def greet (name = "Guest"):Â Â print (f"Welcome, {name}!")greet ("Ali")greet ()
Code 10: Default Parameters
- In the above example, we defined a function name greet which says Welcome to new comer.
- In the parameters list of the function, we defined a variable name and assigned it a value “Guest” and printed the name of comer with welcome.
- On line 4, we call the greet function with “Ali”. This string (Ali) will copy in name variable and later prints the welcome message with the provided name
- It means that when the name parameter receives the value from the call, it will not use the value assigned to it. It leaves the string “Guest” and uses the string which it received.
- On line 5, we call the greet function without any parameter. This time no copy of data will pass to the variable name. Now the variable uses its value which is already assigned.
Figure 1: Output of Calling a Function with Parameter and without Parameter








