Open In Colab

7: Built-in Functions#

Python contains a lot of useful built-in functions to know. This allows you to build code faster, without having to develop your own functions for the most basic tasks. In this notebook, I show you the most important ones:

  • Basic functions: abs(), round(), max(), min(), len(), sum(), any(), all()

  • Variable type conversions: int() str(), float(), type()

  • Data structure conversions: list(), tuple()

  • Binary conversions (less useful in machine learning): bin(), oct(), hex()

  • Input()** function

  • Function format() (f-string)

  • Function open()

1. basic function#

Useful in all circumstances !

x = -3.14
print(abs(x)) # absolute value
print(round(x)) # rounding
3.14
-3
list = [-2, 3, 1, 0, -4]

print(min(list)) # minimum
print(max(list)) # maximum
print(len(list)) # length
print(sum(list)) # sum of elements
-4
3
5
-2
list = [False, False, True]

print(any(list)) # is there at least one True element?
print(all(list)) # are all elements True ?
True
False

2. Conversion function#

It can be very useful to convert a variable from one type to another (for example to make calculations). For this, we have the functions int(), str() and float().

The type() function is very useful to inspect the types of our variables

age = '32'
type(age)
str
age = int(age)
type(age)
int
age + 10
42

We can also convert lists into tuples, or Numpy arrays (which we will see later) into lists…

list_1 = [1, 2, 3, 4]
tuple_1 = tuple(list_1) # convert a list to a tuple
type(tuple_1)
tuple

3. The input() function#

This function is very useful to ask the user of the program to enter a value in your program

age = input('how old are you ?')
type(age) # age is a string type. you have to think about converting it if you want to make a calculation with
str

4. The format() function#

this function allows you to insert the value of a variable in a string.

A faster way to use this function is to use the f-string.

x = 25
city = 'Paris'

message = "it's {} degrees at {}".format(x, city)
print(message)
it's 25 degrees at Paris
message = f"it is {x} degrees in { city}."
print(message)
it is 25 degrees in Paris.

5. The open() function#

This function is one of the most useful in Python. It allows you to open any file on your computer and use it in Python. Different modes exist :

  • the ‘r’ mode : read a file from your computer

  • the ‘w’ mode : write a file on your computer

  • the ‘a’ mode : (append) add content to an existing file

f = open('text.txt', 'w') # open a file object f
f.write('hello')
f.close() # we have to close our file once the work is done
f = open('text.txt', 'r')
print(f.read())
f.close() 
hello

In practice, it is more common to write with open() as f to avoid having to close the file once the work is done:

with open('text.txt', 'r') as f:
    print(f.read())
hello

6. Exercise and Solution#

The code below allows to create a file which contains the square numbers from 0 to 19. The exercise is to implement a code that allows to read this file and to write each line in a list.

Note_1 : the function read().splitlines() will be very useful

Note_2 : For a better result, try to use a comprehension list !

# This piece of code allows to write the file 
with open('fichier.txt', 'w') as f:
    for i in range(0, 20):
        f.write(f'{i}: {i**2} \n')
    f.close()
# Write here the code to read the file and save each line in a list.
Hide code cell content
# SOLUTION (not optimal)
with open('fichier.txt','r') as f:
    list = f.read().splitlines()
list
['0: 0 ',
 '1: 1 ',
 '2: 4 ',
 '3: 9 ',
 '4: 16 ',
 '5: 25 ',
 '6: 36 ',
 '7: 49 ',
 '8: 64 ',
 '9: 81 ',
 '10: 100 ',
 '11: 121 ',
 '12: 144 ',
 '13: 169 ',
 '14: 196 ',
 '15: 225 ',
 '16: 256 ',
 '17: 289 ',
 '18: 324 ',
 '19: 361 ']
Hide code cell content
# SOLUTION (Improved)
# A better way is to use a comprehension list!
list = [row.strip() for row in open('fichier.txt','r')]
list
['0: 0',
 '1: 1',
 '2: 4',
 '3: 9',
 '4: 16',
 '5: 25',
 '6: 36',
 '7: 49',
 '8: 64',
 '9: 81',
 '10: 100',
 '11: 121',
 '12: 144',
 '13: 169',
 '14: 196',
 '15: 225',
 '16: 256',
 '17: 289',
 '18: 324',
 '19: 361']