Built-in functions

What are the built-in functions?

The Python interpreter has a number of functions and types

built into it that are always available. They are listed here in alphabetical order.

You don't need to import them, they are already available in your global scope.

We are going to review 6 built-in functions (more if we have time):

1. len
2. input
3. print
4. open
5. range
6. type

Len

len is another built-in function, it returns the number of element into something


In [56]:
my_name = "Christian"

In [57]:
# 9 letters
len(my_name)


Out[57]:
9

In [58]:
my_list = [1,2,3,4,5]

In [59]:
# elements inside a list
len(my_list)


Out[59]:
5

In [60]:
# elements inside a dictionary
my_dict = {"first": "1", "second": "2"}

In [61]:
len(my_dict)


Out[61]:
2

Input

Input reads a value from you terminal and saves it inside the variable


In [1]:
my_input = input('type your variable: ')


type your variable: 10

In [2]:
my_input


Out[2]:
'10'

Print

Literally it puts somthing in your stdout, and in general it means your terminal/console.

Together with print we introduce a way to format strings.

Let's say that I want to print:


In [64]:
# This is a `way`
print("My name is Christian and I am 29 years old")


My name is Christian and I am 29 years old

In [65]:
# This is another way
my_first_name = "Christian"
my_age = 29
print("My name is", my_first_name, "and I am", my_age, "years old")


My name is Christian and I am 29 years old

In [66]:
# This is the proper way
print(f"My name is {my_first_name} and I am {my_age} years old")


My name is Christian and I am 29 years old

How does it work?

We use f"" notation (can be also f'') and put our variables inside curly brackets.

It works also when you want to create new strings.


In [67]:
sentence = f"My name is {my_first_name} and I am {my_age} years old"

In [68]:
print(sentence)


My name is Christian and I am 29 years old

Open

Open is used when you want to read/write files


In [3]:
my_file = open("text.txt", mode='w+')

In [4]:
# returns the number of characters written
my_file.write("This is my first file\n")


Out[4]:
22

In [5]:
my_file.write("This is the second line\n")


Out[5]:
24

In [6]:
# this is very important!
my_file.close()

In [125]:
# We didn't cover context manager,
# but this is the Pythonic way to work with files
with open("text.txt", mode='w+') as my_file:
    my_file.write("This is my first file\n")
    my_file.write("This is the second line\n")

Range

How want to create a list with the numbers for 0 to 10, with 10 not inclued


In [3]:
my_list = []
number = 0
while number < 10:
    my_list.append(number)
    number += 1

In [4]:
my_list


Out[4]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Can we do this in 1 line?


In [9]:
my_list = list(range(10))

In [10]:
my_list


Out[10]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Range is actually an immutable sequence type and the sequence can be created in this way:

range(start, stop[, step])


In [165]:
# Remember `stop` is not included
list(range(1,6))


Out[165]:
[1, 2, 3, 4, 5]

In [11]:
# You can use step to `jump` between the numbers
list(range(0,11,2))


Out[11]:
[0, 2, 4, 6, 8, 10]

In [12]:
# Remember that range is not a list!
range(10)


Out[12]:
range(0, 10)

Type

Type is our last built-in function for this part, it returns the type of our variable (object)


In [13]:
my_name = "Christian"

In [14]:
type(my_name)


Out[14]:
str

In [15]:
my_list = [1,2,3,4,5]

In [16]:
type(my_list)


Out[16]:
list

In [17]:
my_dict = {"first": "1", "second": "2"}

In [18]:
type(my_dict)


Out[18]:
dict

In [20]:
type(my_dict) is type(my_list)


Out[20]:
False

In [22]:
type(my_list) is type(my_list)


Out[22]:
True

This is very useful when you want to check if 2 variables have the same type, thus the could behave in the same way....

keypoints:

  • "A for loop executes commands once for each value in a collection."
  • "The first line of the for loop must end with a colon, and the body must be indented."
  • "Indentation is always meaningful in Python."
  • "A for loop is made up of a collection, a loop variable, and a body."
  • "Loop variables can be called anything (but it is strongly advised to have a meaningful name to the looping variable)."
  • "The body of a loop can contain many statements."
  • "Use range to iterate over a sequence of numbers."
  • "The Accumulator pattern turns many values into one."

When and how to use the built-in functions

The short answer is always use built-in functions, generally they are:

* faster
* well tested

In [23]:
%%timeit
my_list = []
number = 0
add_to = my_list.append
while number < 1000:
    add_to(number)
    number += 1


110 µs ± 4.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [25]:
%%timeit
my_list = list(range(1000))


19 µs ± 1.62 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

my implementation is ~5 times slower.


In [26]:
my_list = list(range(10000))

In [27]:
%%timeit
number = 0
for element in my_list:
    number += 1


509 µs ± 19.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [30]:
%%timeit
len(my_list)


112 ns ± 1.45 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Again....just use them :)

Challenges: take around 5 to resolve each of the following challenges
# Challenge n.1

print("Print the even numbers between 0 and 20 (20 included)")

for ______ in ______:
    if ______ % 2 == 0:
        print(______)

In [32]:
# Put your code here
# Challenge n.2

print("Save the even numbers between 0 and 20 (20 included)")

for ______ in ______:
    if ______ % 2 == 0:
        with open("my_file.txt", mode="w") as f:
            f.write(______)

In [33]:
# Put your code here
# Challenge n.3

print("Save a list of 100 numbers in a files and then read them and print the odd numbers")

with open("my_file.txt", mode="w") as f:
    for ______ in range(100):
        f.write(______)

______ ______ as ______:
    for ______ in f:
        if ______ % 2 != 0:
            print(______)

In [17]:
# Put your code here
# Challenge n.4

# Check if the num and name are of the same type

num = 10
name = "Christian"

if ______ is ______:
    print("Our variables are of the same type")
else:
    print("Our variables are of a different type")