Functions and Strings
In this tutorial we shall discuss about functions and strings. Topics we covered in the last tutorial:
- Iteration
- Range
- List comprehension
Function :
A Function is a set of instructions ( code ) that is either defined by the computer or defined by the user ( we will learn how to define a function ), which can be used multiple types.
- the print is a function defined by the computer, which means display the data.
- for is a function defined for iteration
Define a function:
To define a function a keyword is used known as “def”, which starts defining a function.
Syntax:
def function_name( parameters ) statement
Let us define a function which takes two integers, strings as inputs and returns the addition of two numbers.
Here the code at last gets an error, because three parameters are given as input to the function, where as only two parameters were defined.
Documention String:
Python is a very vast language, where thousands of functions and libraries are stored, a user cannot know everything about all the functions. Jupyter notebook provides a feature where the programmer can know the function parameters and about it.
How to write DOC string , when we define a code:
We will use “”” before string and “”” after string to store them in documentation of the function we defined.
map():
This function takes two parameters, the first parameter is a function and the second parameter is a sequence of which all elements should be parameters to the function.
map( function_name, sequence )
Let us do few coding examples in jupyter notebook.
lambda:
It is also known as anonymous function and is plays a very key role when we wanted to define our own function but will be using only once.
Syntax:
Func_name = lambda parameter: logical expression
filter():
This function is used to filter a sequence based on a function, and mostly in filter we will be assigning lambda functions mostly.
Syntax:
filter( lambda parameter:logic , sequence)
E.g: We will be taking a sequence from 1 to 30 numbers and will filter all the odd numbers.
Tuple unpacking:
This case arises when tuples are embedded in a list, then in the normal way we can access tuples and elements of tuples, but second method (tuple unpacking is better )
Normal method:
Tuple unpacking:
with this, we are completed with python crash course for data science and machine learning.
Visit the complete sections of data science
.