




















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Who wants to think about how to compute square roots in a calculation that involves other more challenging things? r = (sqrt(250+110*sqrt(5))/20)*E ...
Typology: Summaries
1 / 60
This page cannot be seen from the preview
Don't miss anything!





















































Topics: Modules Using import Using functions from math A first look at defining functions
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.
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).
If the square and rectangle have area x, then
Take the average of the length and width
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.
A function has a name and arguments. m = max(x,y) name arguments We say that max(x,y) is a function call.
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.
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)”
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()
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?