Of course, Python comes with a lot of built-in functions. We used
print() already. Here are few commonly used built-in functions:
range()– It returns an iterable sequence
open()– It opens a file then returns the corresponding file object
sorted()– It sorts a list and returns the sorted list
help()– It invokes the help system built into Python
abs()– Returns the absolute value of a number
The parameter you put in between parenthesis acts like a stop. For example let’s take a look at the following example:
for i in range(5): print(i)
It prints all the numbers from 0 to 5 (but not including 5).
If we use it with 2 parameters then we will have something like is shown below:
for i in range(2,5): print(i)
It starts printing at number 2 and it stops at 4. Number 5 is not printed.
If we use it with 3 parameters then we will have something like is shown below:
for i in range(2,10,3): print(i)
It starts printing with number 2, then prints 5 (which is 2+3 and is less than 10), then prints 8 (which is 5+3 and it is also less than 10). Then it stops printing since the next number would have been 11 and it is out of range.
So, in conclusion, the
range() is a general tool that can be used in a variety of contexts. It is commonly used to generate indexes in a
for loop but you can use it anywhere you need a series of integers.
>>>>>> list(range(5)) [0, 1, 2, 3, 4] >>> list(range(11, 17)) [11, 12, 13, 14, 15, 16] >>> list(range(-3, 3, -1))  >>> list(range(3, -3, -1)) [3, 2, 1, 0, -1, -2] >>> list(range(-3, 3, 1)) [-3, -2, -1, 0, 1, 2]
range() is useful when used within
for loops. It is a simple way to repeat an action a specific number of times.
To print three lines, use
range() to generate the appropriate number of integers.
>>> for i in range(3): ... print(i, ' developer') ... 0 developer 1 developer 2 developer
open() function opens a file. Let’s modify the file
hello.py as shown below:
print('The message with open()')
Open the terminal, go to the directory where the file is and type the following commands:
f = open(“hello.py”) f.read(9)
This is what the terminal outputs:
It reads the first 9 characters. Of course, you can do many more things with the
sorted() function does what the name says, it sorts the items of a list for example.
>>> a = [5,3,4,2,1] >>> print sorted(a) [1, 2, 3, 4, 5] >>>
help() invokes the help system built into Python. Open the terminal and type
python to start Python then type
help(). This is what you get:
abs() function returns the absolute value of a number. The absolute value of a number is its distance on the numbers line from 0.
Open the terminal and type in the following command:
The terminal will return 5 as you can see below.
The are many more built in functions in Python that you can study and experiment with.