Logo

Functions

A function is a decided to name sequence of statements that computes something. When you describe a function, you clearly state its name as well as the order of its statements.

We've already seen one function call instance:

 

The function's name is type. The expression enclosed in parentheses is referred to as the function's argument. The type of the argument is the result of this function.

A function is commonly said to "take" an argument and "return" a result. The outcome is also known as the return value.

We also have type casting included which involves using functions as int(),str() etc to convert one data type values to other.

 

However while running int('Hello') error is produced due to ValueError: invalid literal for int(): Hello

 

Math functions

Python has a math module which has mathematical functions. A module usually is a file containing a collection of related functions.

 

>>> import math

Figure 4.1. demonstration of Importing math library.

The above statement generates a module object called math. Upon displaying module object, you get the following information about it:

 

The module object contains the module's functions and variables.

To use one of the functions, enter the name of the module followed by the name of the function, separated by a dot (also known as a period). This is known as dot notation.

 

For instance, find the sine of radians. The variable name radians implies that sin as well as the other trigonometric functions (cos, tan, etc.) accept radian arguments.

Divide by 180 as well as multiply by to convert degrees to radians:

 

Composition

One of most important functions of programming languages is one‘s ability to take small basic components and compose them.

A function's argument, for example, can be any kind of expression, such as arithmetic operators:

 

The composition of expression also has to follow a specific order and any expression on left is a syntax mistake (we will see exceptions to this rule later).

 

Adding new functions

A function definition stipulates the title of a new function as well as the sequence of statements that will be executed when the function is invoked.

Here's an illustration:

 

The keyword 'def' indicates this is a function definition. The function's name is print lyrics.

The same rules apply to function names as they do to variable names: letters, numbers, and underscores are permitted, but the first character cannot be a number.

A keyword cannot be used as the name of a function, and a variable and a function with the same name should be avoided.

The absence of parentheses after the function name indicates that it does not accept any arguments.

The first line of the function is referred to as the header, and the remaining lines are referred to as the body.

The header must be followed by a colon, and the body must be indented.

Indentation is always four spaces by convention. The body may contain an unlimited number of statements.

 

Indentation

Figure 4.2. All user defined function must have indention.

 

Definitions and uses

Putting the code blocks from the preceding part together, the entire program looks like this:

 

Definitiona

Figure 4.3. We can call user-defined functions by calling them.

 

There are two function definitions in this program: print lyrics and repeat lyrics.

Function definitions are executed in the same way as other statements, but the result is the creation of function objects.

The statements within the function are not executed until the function is invoked, and the function definition produces no output.

Before you can run a function, you must first create it. In those other words, the function definition must be executed before the function is invoked.

 

Flow of execution

 The program's execution always starts with the first statement.

Statements are executed one at a time, from top to bottom.

Function definitions have no effect on the program's execution flow, but keep in mind that statements inside the function are not executed until the function is called.

A function call is similar to an excursion in the execution flow.

Instead of proceeding to the next statement, the flow leaps to the function's body, runs the statements there, and afterwards returns to pick up where it left off.

 

Parameters and arguments

Some of the functions we've seen so far have required arguments.

 When you call math.sin, for example, you pass a number as an argument.

Some functions accept multiple arguments: math.pow accepts two, the base and the exponent.

 

parameters1            parameters

Figure 4.4. 'print_twice' function takes name as argument and prints it twice.

 

Here the function is 'print_twice' as mentioned here. This function assigns the argument to a parameter named name.

When the function is called, it prints the value assigned to name twice as output.

The same composition rules apply to programmer-defined functions as they do to built-in functions.

 

Here the argument is evaluated before the function is called as seen from above execution.

 

Variables and parameters are local

When you create a variable inside a function, it is local, meaning it lives only within the function.

 

The variable cat is destroyed when function printing twice finishes execution. When we try to print it, we receive the following error:

NameError: name 'cat' is not defined

 

Stack diagrams

A stack diagram might be handy for keeping track of which variables can be used where. Stack diagrams, like state diagrams, indicate the value of each variable as well as the function to which each variable belongs.

A frame is used to represent each function. A frame is a box that contains the arguments and variables of a function as well as the name of the function.

The frames are stacked to show which function called which function, and so on. In our example, the function 'print_twice' was called by the function 'printing_twice', which was called by __main__.

__main__ is a special name for the topmost frame in this case. Upon creating a variable outside a functon it belongs to __main__.

 A traceback is a collection of functions. It shows you the software file the error occurred in, as well as which line and functions were active at the moment.

 

Traceback

Figure 4.5. There are mainly 3 different types of errors : 1.)Syntax errors 2.)Execeptions 3.) Logical errors

 

It also displays the error-causing line of code. The order of the functions in the traceback corresponds to the stack diagram's frame order. 

Our name error trace back would look like :

 

Traceback

Figure 4.6. Error trace back usually looks something like this.

 

Fruitful functions and void functions

Fruitful functions are functions that return outcomes in the form of math functions. While void functions are functions that perform an action but do not return a value, such as print twice.

 

You nearly always want to do something with the result when you call a productive function.

If you call a productive function by itself in a script, the return value is lost permanently.

This script computes the square root of 5, however it isn't particularly useful because it doesn't store or display the result.

 

Sqrt

Figure 4.7. Math library usually comes with other inbuilt functions as sqaure root.

 

There is no return value for void functions, therefore they may display something on the screen or have some other effect. You obtain a special value called None if you assign the result to a variable.

The value None is not the same as the string 'None'. It is a special value that has its own type:

 

None

Figure 4.8. demonstration of data type of 'None'.

 

Why use Functions ?

Use Case of functions are essential as it allows to break a larger complex program imto smaller and more easily manageable parts.

Some of the advantages are listed below :

  • When you create a new function, you can name a group of statements, making your software easier to read and debug.

  • Functions can reduce the size of a program by removing redundant code. If you need to make a modification later, you just have to do it once.

  • Breaking down a large program into functions allows you to debug each component individually before putting them together into a workable whole.

  • Many programs benefit from well-designed functionalities. You can reuse one once you've written and debugged it.

 


________________________________________________________________________________________________________________________________
Footer
________________________________________________________________________________________________________________________________

Copyright © 2022-2023. Anoop Johny. All Rights Reserved.