1. What is a function in Python?
In Python, a function is a group of structured statements whose purpose is to perform a specific task when called. A function is used to call a single code from multiple places in a program. It is also called method or procedure. Python provides many built-in functions like print(), input(), compile(), exec(), etc. but it also gives the possibility to create your own functions.
The notion of function is very important in computer science. They allow a problem to be broken down into sub-problems, which can themselves be broken down into sub-tasks. This design of the programs allows better readability of the code. In addition, the functions are reusable in several places of the program or even in several different programs provided that we have taken the trouble to gather them within modules.
We will first see the user defined functions and then we will deal with the original functions, i.e. those that you will develop yourself in order to deal with the particular problem that you have to solve.
You can choose any name for the function you are creating, with the exception of reserved language keywords, and on the condition that you do not use any special or accented characters (the underscore “_” character is allowed) . As is the case for variable names, we use lowercase by convention, especially at the beginning of the name.
There are 3 types of functions in python:
- built-in functions in python
- user-defined functions
- lumbda functions
2. User defined function
The syntax of a user-defined function is declared using the keyword def followed by the name of the function
def function_name (parameters): Instructions...
Example: function that returns the product of two numbers
def product(x,y): return x*y print(product(5,7))# display '35'
Example (function without parameters)
def hello(): print("Hello World") # call the function hello() # displays: "Hello World"
3. Built-in functions in Python
3.1 About built-in functions
We know as mentioned above that there are three types of functions, namely user-defined functions in Python, lambda functions in Python, and built-in functions in Python. In this paragraph, we are going to learn everything there is to know about built-in functions in Python.
The Python interpreter has various predefined functions that are easily usable. We don't need to define these functions to use them; we can call them directly. These functions are called built-in functions.
In previous tutorials in this Python course, we have used various built-in functions. The very basic built-in function that we have used in almost every tutorial is the print() function which is used to display a given object.
3.2 List of the main built-in functions in Python
- Python abs(): It returns the absolute value of a number and the returned value is always positive.
- Python all(): It returns true when all items in an iterable evaluate to true or there are no items in an iterable. It returns false if an item evaluates to false.
- Python any(): It checks if an element of an iterable is true. Unlike all():, it returns false if there are no items in the iterable.
- Python ascii(): This method returns a string containing a printable representation.
- Python bin(): This Python built-in function is used to convert an integer to a binary string.
- Python bool(): This Python built-in function is used to convert a value to boolean.
- Python bytearray(): This built-in python function returns an array of the given byte size.
- Python bytes(): This Python built-in function returns an immutable bytes object.
- Python callable(): This Python built-in function is used to check if the object is callable.
- Python chr(): This built-in python function returns a character (a string): from an integer.
- Python classmethod(): This built-in python function returns the class method for a given function.
- Python compile(): This built-in python function returns a Python code object.
- Python complex(): This Python built-in function is used to create a complex number.
- Python delattr(): This Python built-in function is used to remove an attribute from an object.
- Python dict(): This built-in function is used to create a Python dictionary.
- Python dir(): This built-in python function tries to return attributes of an object.
- Python divmod(): This built-in python function returns a tuple of quotient and remainder.
- Python enumerate(): This built-in python function returns an enumerate object.
- Python eval(): This built-in python function executes Python code in a program
- Python exec(): This built-in python function is used to execute a dynamically created program.
- Python filter(): This Python built-in function is used to construct an iterator from the elements that are true.
- Python float(): This Python built-in function is used to return the floating point number from a number or string.
- Python format(): This built-in python function returns the formatted representation of a value.
- Python frozenset(): This built-in python function returns an immutable frozenset object.
- Python getattr(): This built-in python function returns the value of an object's named attribute.
- Python globals(): This built-in python function returns the dictionary of a current global symbol table.
- Python hasattr(): This built-in python function returns a value that indicates whether an object has a named attribute.
- Python hash(): This built-in python function returns the hash value of an object.
- Python help(): This built-in python function Invokes the built-in help system
- Python hex(): This Python built-in function is used to convert an integer to its hexadecimal form.
- Python id(): This built-in python function returns the id of an object.
- Python input(): This built-in python function usually reads and returns a line of string.
- Python int(): This built-in python function returns an integer from a number or a string.
- Python isinstance(): This function checks if an object is an instance of a class.
- Python issubclass(): This checks if an object is a subclass of a class.
- Python iter(): This function returns an iterator for an object.
- Python len(): This function returns the length of an object.
- Python list(): This function is used to create a Python list.
- Python locals(): This function returns the dictionary of a current local symbol table
- Python map(): This function applies functions and returns a list.
- Python max(): This function returns the largest element.
- Python memoryview(): This function returns the memory view of an argument.
- Python min(): This function returns the smallest element.
- Python next(): This function retrieves the next element of an iterator.
- Python object(): This function creates a featureless object.
- Python oct(): This function converts an integer to its octal form.
- Python open(): This function returns a file object.
- Python ord(): This function returns a Unicode point for a Unicode character.
- Python pow(): This function evaluates and returns x to the y power.
- Python print(): It is used to print a given object.
- Python property(): This function returns a property attribute.
- Python range(): This function returns the sequence of integers between start and stop.
- Python repr(): This function returns the printable representation of an object.
- Python reversed(): This function returns the reversed iterator of a sequence.
- Python round(): This function rounds a floating point number to n digits.
- Python set(): This function returns a Python set.
- Python setattr(): This function sets the value of an attribute of an object.
- Python slice(): It is used to create slice object specified by range() function.
- Python sorted(): This function returns the sorted list of a given iterable.
- Python staticmethod(): This function creates a static method from a function.
- Python str(): This function returns an informal representation of an object.
- Python sum(): This function is used to add items from an Iterable.
- Python super(): This function allows us to refer to the parent class as 'super'.
- Python tuple(): This function creates a tuple in python.
- Python type(): This function returns the type of object.
- Python vars(): This function returns the __dict__ attribute of a class.
- Python zip(): This function returns an iterator of tuples.
- Python __import__(): This function is an advanced function called by 'import'.
4.Lumbda function
4.1 About lumbda function
In Python, an anonymous function is a function defined without a name. While normal functions are defined using the def keyword in Python, a lumbda function is an anonymous function and is defined using the lambda keyword.
4.2 Syntax of a Lambda function
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used anywhere function objects are required.
Example Lambda function in python
Here is an example of a lambda function that doubles the input value.
# example of using lambda functions double = lambdax:x*2 print(double(10)) # dusplay: '20'
Younes Derfoufi
www.my-courses.net