Calling Functions and Importing Modules¶

CS 65: Introduction to Computer Science I¶

Abstraction: Big idea in computer science¶

You don't have to know how to farm to be a chef - they work at different levels of abstraction in food production.

In computer science, you build bigger, more complex things by using the building blocks others (or you) have provided.

Abstraction examples we've already seen¶

We've already used several built-in functions in this class: print(), input(), type(), int(), float(), str()

  • A function is an abstraction tool
  • We don't have to understand how they work in order to use them
In [1]:
name = input("Enter your name ")
print("Hello",name)
Enter your name Eric
Hello Eric

input("Enter your name ") and print("Hello",name) are function calls

Anything you put in the parentheses, like "Enter your name ", "Hello", and name are arguments which are passed to the function

Functions do/execute/compute something based on the arguments

Functions that aren't built-in¶

One of the things that makes Python such a great language is that there are many functions you can use that aren't built in.

They're written by other programmers and made available to you.

In order to use them, you need an import statement.

Something you import this way is called a module.

When running a function from a module, you usually use the dot notation.

In [2]:
import random
print( random.randint(1,100) )
27

In random.randint(1,100), random is the name of the module and randint is the name of the function we want to use from that module. 1 and 100 are arguments we pass to the function that tell it what range of numbers we want our random number to be in.

In [3]:
import datetime
print( datetime.datetime.now() )
2021-09-09 11:58:57.022626

Notice that this uses two dots - in this case, the pattern is modulename.typename.functionname becaise the datetime modules contains many different types, and those types each support different functions.

Different modules are set up to be used in slightly different ways.

How do you know how to use a module?

Find the documentation for it on the web!

https://docs.python.org/3/library/datetime.html

In [4]:
from IPython.display import IFrame
IFrame('https://docs.python.org/3/library/datetime.html',width=900,height=450)
Out[4]:
In [5]:
from IPython.display import IFrame
IFrame('https://docs.python.org/3/library/random.html',width=900,height=450)
Out[5]:

Modules can provide new functions and new types¶

In [6]:
type(datetime)
Out[6]:
module
In [7]:
type(datetime.datetime)
Out[7]:
type
In [8]:
current = datetime.datetime.now()
type(current)
Out[8]:
datetime.datetime