Python Functions

Data Science with Python: Functions

Till now we have learned foundational topics of Data Science and basic data types and data structures of Python. Now, we are moving to basic Python functions.

What is a Function?

A function is a group of statements that performs a specific task. Functions make the program more organized and manageable it avoids code repetition and makes the code reusable. Various functions in Python can be learned and implemented easily. Let’s discuss some in-built functions of Python which are important for Data science.

Python In-Built Functions

Many built-in functions in Python are widely used. Basic understanding and implementation of functions are very important to proceed with data science applications.

1. print()

We have used this function in the above examples as well. This function prints the output.

Python Code:

print (“Data Science Horizon”)

Output:
>>> Data Science Horizon

2. abs()

abs() function returns the absolute value of a number. A negative value’s absolute is that value is positive.

Python Code:

print(abs(-9))

Output:
>>> 9

3. min()

Min() function returns the minimum value in a list, tuple, or set.

Python Code:

print(min(3,2,1.5,4))

Output:
>>> 1.5

4. max()

max() function returns the maximum value in a list, tuple, or set.

Python Code:

print(max(23,45,6,10))

Output:
>>> 45

5. len()

Len() function returns the length of any list, tuple, set, or string.

Python Code:

temp = {3,9,5,4,7,8}

print(len(temp))

Output:
>>> 6

6. sorted()

The sorted() function returns a sorted list of the specified iterable object. Sorting can be done in ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

Python Code:

str = (“python”)

print(sorted(str))

Output:
>>>[‘h’, ‘n’, ‘o’, ‘p’, ‘t’, ‘y’]

In the above example, the string is sorted in ascending order.

To sort the values in descending order use the parameter reverse=TRUE, as shown below example:

Python Code:

temp=[1,2,9,0,5,6]

print(sorted(temp, reverse=True))

Output:
>>>[9, 6, 5, 2, 1, 0]

7. format()

The format(value, format) function formats a specified value into a specified format.

Python Code:

print(format(255, ‘x’))    #It formats in hexadecimal.

Output:

>>> ff

To understand the ‘format’ function in detail click here.

‘format’ is used in print functions a lot as shown below:

Python Code:

a,b=3, ‘yes’
print(“a={0} and b={1}”.format(a,b))

Output:
>>>a=3 and b=yes

8. zip()

The zip(*iterables) function returns an iterator of tuples, where one tuple contains n elements from each of the iterables. The length of the tuples is equal to the number of iterables passed to the function.

Python Code:

products = [‘table’, ‘chair’, ‘sofa’, ‘bed’, ‘fan’]# list of products
prices = [500, 200, 2000, 1500, 100]# list of prices
for product, price in zip(products, prices):
          print(‘Product: {}, Price: {}’.format(product, price))
Output:

>>>Product: table, Price: 500
Product: chair, Price: 200
Product: sofa, Price: 2000
Product: bed, Price: 1500
Product: fan, Price: 100

9. map()

The map function can be widely useful when we want to apply a mathematical operation to all the elements of an iterable.

Python Code:

numbers = [1, 2, 3, 4, 5]
print(list(map(lambda x: x * 2, numbers)))#Multiply every iterable of the list with 2

Output:

>>>[2, 4, 6, 8, 10]

10. filter()

filter() function is in a way similar to map() — it also applies a function to some sequence, the difference being that filter() will return only those elements that are evaluated as True.

Python Code:
numbers = [1, 2, 3, 4, 5, 6]print(list(filter(lambda x: x % 2, numbers)))# get odd numbers from the listOutput:

>>>[1, 3, 5]

11. range()

The range(start, stop, step) function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and stops before a specified number.

Python Code:

x = range(3, 10, 2)
for n in x:
print(n)

Output:
>>>3
5
7
9

Second Example Python Code:

print(list(range(0,100,10)))

Output:

>>>[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

12. isinstance()

isinstance() functions take a variable and a class as arguments. Then, it returns True if the variable belongs to the class.

Python Code:

numbers = [1, 2, 3, 4, 5]
print(isinstance(numbers, list))

print(isinstance(numbers, tuple))

Output:

>>>True
>>>False

13. input()

The input([prompt]) function gets raw input from the user, returning it as a string.

Python Code:

name = input(‘Enter your name: ‘)#Input string
print(‘Hello, {}’.format(name))

Output:

>>>Enter your name: Data Science Horizon
>>>Hello, Data Science Horizon

14. open()

The open(file, mode=’r’) function opens a file, specifies the path of the file, and returns a file object. If the file cannot be opened, an OSError is raised.

Python Code:

f = open(‘temp_file.txt’, ‘r’)# open a file in reading mode
content = f.read()
print(content)# Close the file to avoid running out of file handles
f.close()

Output:

>>>Hello!! This is a sample text file.

Conclusion

In this article, we have explained Python functions which are widely used in Machine Learning and Data Science projects with hands-on coding examples. They are building blocks of learning Python and are very important to understand for advanced topics.

Stay Tuned!!

Data Science with Python: Basic Data Structures

Keep learning and keep implementing!!

1 thought on “Data Science with Python: Functions”

Leave a Comment

Your email address will not be published. Required fields are marked *