Docsity

4. Modules and Functions | Cornell CS, Summaries of Pre-Calculus

Partial preview of the text

Download 4. Modules and Functions | Cornell CS and more Summaries Pre-Calculus in PDF only on Docsity!

4. Modules and Functions

Topics: Modules Using import Using functions from math A first look at defining functions

The Usual Idea of a Function

sqrt

A factory that has inputs and builds outputs.

The Process of Implementation To implement a function is to package a computational idea in a way that others can use it. We use the example of square root to illustrate this.

It Starts with an Insight

The act of computing the square root of a number x is equivalent to building a square whose area is x. If you can build that square and measure its side, then you have sqrt(x).

Observation

If the square and rectangle have area x, then

we see that the sqrt(x) is in between L and W.

Recipe for an Improved L

L

x/L

L = (L+x/L)/

x/L

L

Take the average of the length and width

Repeat and Package

x L

L = x L = (L+x/L)/ L = (L+x/L)/ L = (L+x/L)/ L = (L+x/L)/ L = (L+x/L)/ How do we make something like in Python? We talk about “built in” functions first.

Talking About Functions

A function has a name and arguments. m = max(x,y) name arguments We say that max(x,y) is a function call.

Calling Functions

a = 5 b = 7 m = max(ab,ba) diff = abs(ab – ba) In a function call, arguments can be expressions. Thus, the value of the expression ab – ba is passed as an argument to abs.

Functions in Mathematics vs Functions in Python So far our examples look like the kind of functions that we learn about in math. “In comes one or more numbers and out comes a number.” However, the concept is more general in computing as we will see throughout the course.

The Built-In Function len

A function can have a string argument. >>> s = ‘ abcde ’

n = len(s) print n 5 “In comes a string and out comes its length (as an int)”

Functions and Type

Sometimes a function only accepts arguments of a certain type. E.g., you cannot pass an int value to the function len:

x = 10 n = len(x) TypeError: Object of the type int

has no len()

Type-Conversion Functions

Three important built-in functions convert types: int, float, and str.

a = float(22)/float(7) a

b = int(100a) b 314 c = '100pi = ' + str(b) c '100*pi = 314'

Some Obvious Functions are not in the “Core” Python Library!

x = 9 y = sqrt(x) NameError : name ‘ sqrt ’ not defined How can we address this issue?