A function is a block of code which helps to break our program into smaller chunks or sub-programs, making it more organized and easily understandable. It runs as and when called and also helps to increase the code reusability.
Create a function
def function_name():
print("Function created")
function_name()
Here,
def
is the keyword used to define a function:
is used to mark the end of function headerprint statement
is the function bodyfunction_name()
is a way of calling the created function
Built-in functions
These are the predefined functions already available in python and can be used directly when required. The following are some built-in functions with their examples.
Input function
It enables us to take user input as a string until it encounters a newline without evaluating its value.
The use of int
and float
in the statement can enable us to accept an integer and floating point number as well.
Eval function
It is used to evaluate the values of a string.
The value returned by a function may be used as an argument for another function in a nested manner. This is called Composition.
Print function
It is used to display the output provided as an argument on its execution.
Here, name
is the function's argument.
In order to display multiple values in a single print statement, we separate the values using commas (,)
. These values will be displayed in the same line.
To display the values in separate lines using a single print statement, we make use of escape sequence such as \n
i.e. newline character
.
Type function
It is used to determine the data type of a value.
Round function
It is used to round up a number upto a specified number of decimal places. The first argument specifies the value to be rounded and the second specifies the number of decimal digits desired after rounding up. If the second argument is missing, then the number is rounded up to an integer.
Max and min functions
They are used to find the maximum and minimum values respectively out of the several values. The operands must be compatible for comparison. The integer and floating point values are compatible for comparison. These functions can also operate on string values.
Pow function
It is used for computing power. The function pow(a,b)
computes a to the power b
.
Functions from math module
In order to make these functions available, we need to import the math module using import math
.
Assert statement
It is used for error checking which responds with an assertion error if the assertion fails to hold the system. For example,
CODE
OUTPUT
##ERROR
Here, when the sum of two sides of the triangle is greater than the third side, the function will execute the assert statement.
Hope you guys are learning and benefiting from my blogs. Stay tuned and do let me know your reviews!!