Python for Informatics – Chapter 4 – Functions

Hello, and welcome to Chapter
4, Functions, in my book Python for Informatics. As always, these slides and
this audio and this video are copyright Creative
Commons attribution. Now, we are to the point–
you know, in Chapter 4, we're sort of well
into the class– so I figure I should
introduce myself a little bit, let you know a little bit. As I said before, I
think in the beginning I'm taping this in
a wonderful building at the University of
Michigan called North Quad. It's a relatively new building. It's got some
residential sections and some academic sections
and some classrooms. And one of the classrooms
that I typically teach in is actually 2255 North Quad. It's a really beautiful
room with great ways for people to interact. And so sometimes I'm teaching,
you know, little tiny Dr. Chuck down here, with a
smile on the face. And sometimes, my students are
taking my classes on campus. And sometimes, students are
watching me through a lecture. And so this building
is really beautiful. And if you ever get a
chance to come to Ann Arbor and take a look at it,
maybe walk through it, it's really quite nice. One of the things
I like about it is that I think
it's really highly inspired by Harry Potter. Of course, Oxford and Cambridge
are the real inspiration for Harry Potter. But our cafeteria, for
example, it kind of looks like the four
tables in Hogwarts. And you can kind of imagine
a snowy owl flying around and a Sorting Hat at the
front sorting people. And so the nickname
for the place is Quad-warts, because
it's North Quad. Quad-warts, that's like
Hogwarts and North Quad kind of jammed together. And of course, given that we
sort of think of ourselves a little bit as Harry Potter,
people when they first come in September, often sort
of decide to sort themselves. And a few years back, when we
first started the building, the students decided that I did
not get to be in Gryffindor. As a matter of fact,
it's probably time for me to show you who I am and
who I've been sorted to be. So the students decided that
I couldn't be in Gryffindor, but I had to be in Slytherin. And that's because of my
name, Charles Severance, and Severus Snape. What's even cooler, of course,
is given that I teach Python, Slytherin's House is a snake. So it makes a lot of sense. They even have this really
fancy Slytherin teacup that I use to drink
tea during lectures. Sometimes, I drink coffee. Sometimes, I drink tea. Wow. This thing itches. So let me just get rid of it. If I had any hair, that
would mess my hair up. So let me get rid of this
for the rest of the lecture. So there I am. OK. Enough of that. Back to Dr. Chuck. So with that sort
of brief interlude, the actual topic of this
lecture is functions. And so storing and
reusing is basically an idea that we will often
have a series of steps that we will want to use
over and over in a program, increasingly complex. The things we'll
use in this lecture are kind of silly,
because I have to keep them short so the
slides don't get too long. But a good example
of the kind of work is maybe I'm going to use
Google's geocoding service. And I'm going to send some
unstructured data back and get a GPS coordinate back. And that's a service
that I want to call. And it would maybe be about
this many lines of code. And I'm going to want to
that all over the place. So do I want to put
this many lines of code 40 places in my program? Or do I want to put
it one place and then call it in the various
places that I need it? And so that's why I call it the
store and the reuse function. So if we take a look at
the simple syntax here, these things are
called functions. In some languages, they're
called subprograms. But we call them
functions in Python. And the keyword that we're
really going to focus on is def, which stands for define. And what happens here is when
Python sees this def keyword, it actually doesn't
run the code. It says, oh, you're
going to make a function. And you're going to
turn on a recorder and start recording this code. So it has a colon
at the end of it. So it has an indented
block afterwards. And so the indented
block becomes recorded. So instead of running
the code, like if we just put print "Hello" and print
find: Fun," it would run it. But instead says, hey,
don't run it right now. Name it, "hello." We give it a name. It's kind like a variable. We choose the name. We've chosen hello
as the name of this. Define it as hello. Have it have these two
lines of Python in it. And we'll use it later. And so that's the
function definition. That's the store phase. It's sort of like it doesn't
really run those lines. It sort of makes
a variable called hello that actually
contains Python code rather than containing 12 or
a string or something like that we've
worked with before. So this is the store part. And then, the reuse part is
we then have extended Python. We now can call our bit of code. So we say, hello–
hello name is what we came up with– parentheses. And then, that says–
remember that code that I put in there
under the name hello? Run it now. And so if I start
looking at that and then it just continues. So let me clear this
and start over again. And so if I watch what Python
does from the beginning as it reads here
and goes, oh, you're defining a function named hello. Great. I will remember, remember. I've got that
remembered for you. Let's continue on. Oh, hello. You want me to run that
stuff that you just got done storing under the name hello. So then, it kind of
goes and runs it. And out comes Hello, Fun. Then after that, it
runs to this print, and then out comes print Zip. Then, we say, you know what,
I want to reuse that again. I stored it once. I can resue it as
many times as I want. And now, hello. And then, these two lines
of code run a second time. So we stored once,
gave them a name, and then ran them
twice in the context of wherever it is we wanted. Now, this is not sort
of a profound reason to use it in this. I'm just trying to give
you the notion that there is a way to store and
name code that then you can retrieve later. That's really what's
going on here. So there's two kinds of
functions inside of Python. And we've actually
been using them almost from the very first lecture. And that is, there
a built-in functions that Python provides to us
like float, raw input, int, those kinds of functions. Those are just part of Python,
but we call them as functions. The difference is
we don't write them. And then, there's
user-defined functions, functions that we
write, functions to create functionality
that we want to make use of like
encapsulating the ability to compute pay for time
and a half for overtime. And so we name these
things, and we treat them as new reserved words
that we've created. They're kind of an extension
to the language as it were. So when we're coming
along, we define a function with the def keyword. The def keyword is
a reserved word. It's one of the many reserved
words back in chapter one that we talked about. And it indicates to Python
the beginning of a function. We define it. And then when we call
it, it's called invoking. It's like we're building
it and then we're invoking. And you can build it
once and then invoke it many, many times. So for example, here's
a built-in function called max that
finds the largest character– the sort
of lexigraphically larger character– in a string. And so it's like, OK, tell
me the maximum character. And so max is not some
code that we've written. But we are invoking
a function here. And we're passing in
an argument to that. So the argument is the stuff
in between the parentheses. So the max function
can find the maximum of many different things. At this moment,
we wanted to find the maximum of that particular
string, the highest character in that particular string. So this is a right-hand side
of an assignment statement too, so that has to be
evaluated to a value. So it goes into the function,
does whatever it thinks the function wants to do. And then, the function
gives us back a value that becomes the value for
max parentheses Hello world. And that value, in this
case, is the letter w. Because the letter w is decided
to be the highest letter, and that's what
max gives us back. And then, we're
done with that, then that w ends up being assigned. The assigned
statement completes. And so you can think of
the function evaluation as happening as part of the
right-hand side expression calculation. There could be a plus
here and other stuff. And it's just at some
point a big expression. And this one, it's a simple
expression with just one function call. Now, if we look at this,
there's some code somewhere. Somebody wrote some code. It's part of Python. You didn't write it. There's a max
function somewhere. And you can think of a
function as having some input. It's kind of like a program. That's why some languages
call these things subprograms. Because they have an input, they
do some kind of useful works– whatever that useful
work happens to be. And then, it produced
some kind of an output. So Hello world is the input,
the string, the arguments, the thing we're passing in. Hello world is what's being
passed into the function. The function is running. And then, something comes
back and is sent back. So it has input,
processing, and output. So that's how a function,
some stored code– whether we wrote it or
not– they work the same when we call functions. So you could think of this as
somewhere inside of the Python library is some code that maybe
has a little def in there. And they named the function max. And it takes a single parameter. And it does some blah, blah,
blah, loopy, blah, blah, blah. A lot of stuff. Whatever max wants to do. Whatever we need max to do
based on the specifications that max is supposed to support. But somewhere there is
code inside of Python that actually represents
the function definition. It's a built-in function,
because it comes with Python and we didn't have to
do anything to add. So some common
built-in functions that we have been
using all along, good examples are the float,
which takes as input anything and returns you a floating
point number version of that; type, which takes a parameter
of a variable or a constant and says, what is the type of
this; float, again converting; type, again; and float. So these are all things that
we've been calling functions all along. And it passes the input
value into the function, the function runs and
then gives us back the return value,
which then participates in the rest of the expression
on the right-hand side. You can think of it's
pausing the calculation on the right-hand side,
calling the function, getting the result
of the function back, and then
continuing the evaluation on the right-hand side, then
coming up with whatever value, and then printing
that value out. Another thing that
we've done, is we've done string conversions. Right, so we've converted
in this case a string to an integer. And that's what type it is. We've converted a
string to an integer. So it converts its argument,
whatever that happens to be, into an integer. So that's just some of the
built in functions that we have talked about so far. Now this becomes
more interesting when we can make our own functions. There goes my tea bag. Right in the middle
of the thing. We take the tea bag out. I think it's — whoa. I'll be right back. OK, there's my tea. So, we want to make
a new function. As we said in the other
example, we use the Def keyword. The Def keyword here, and then
we have some indented bit. We create a name for it. And then have some parentheses. These parentheses will
later tell the inputs that we're going to pass
in but this function has no input so we just go
parentheses parentheses. And then the all
important colon character, which indicates the beginning
of an indented block of Python that then is just the
text of the function. So it's important to remember
that while this is executing, when Python first
looks this it doesn't run these lines of code. It just remembers them and
names them print lyrics. So it doesn't cause
any print out, it just causes Python
to remember them. I've said that a
few too many times. So here is a difficult
problem, I'll let you think about
it for awhile. I want you to kind of mentally
go through and execute this code. Ask what, ask yourself what
the output of this program would produce. How many lines? How many lines of output
will this program produce? So, how many of you said three? How many of you said five? Well, the right answer
is actually three. You see five print statements
two, three, four, five. But to of the print statements
are sitting inside of this. And we never called, we never
invoked the function down here. OK? So this one —
let's clear this — this one prints these
two get skipped, this one prints and
this one prints. So that's why there are
three statements that print. There is, stored,
but we never used a function called print lyrics. And it's got two statements
in it, but we never used it. So the output of this
is hello yo seven. And that's because we
never actually invoked it. We had to say print
lyrics parentheses or whatever to cause
it to call this. OK, that's just to emphasize
that as it looks at it, it does not execute these lines. So once we defined
a function, once we have given it a name, given
it code that is part of it, then we can invoke or call
it as many times as we like. So now our little example works
a little better if we actually call our function. Python really doesn't care if
you don't call your functions. Like, you told me to make one,
I made one, you didn't use it, there you go. But if you look at this one now. So here we go. X equals 5 print hello,
outcomes hello, define. Nothing happens here. Nothing happens here
it's just remembering. OK then it says print go. Then it calls the
function print lyrics, which sort of stops us here. Runs these two lines of code. So out comes that and that. Then it sort of finishes
this and it comes back, x equals x plus 2. Then it prints x. That must mean x is 7,
and so out that comes. And so, again it's on
the first time through — go back go back go back —
on the first time through, it doesn't print. But then when it
hits this, it prints. You could say print
lyrics several more times and it would run this
as many times as it did, and if it needed to as
many times as you want, and it would make
output for you. So you can invoke. This is the definition
— let's clear this — this is the definition,
this is the call or invoke. So we're invoking the function,
we're calling the function, were causing the
function to execute. Here we are just
causing the function to be looked at and defined,
but not actually executed. I hope that's clear. Now, when we pass data into
a function, and functions they don't take data are not
as useful as they could be. There's plenty of
things that do, times that you build a
function it doesn't take data. But the most
interesting functions are the ones that you could
hand them something to work on and they can do their work and
then come back with whatever. So this Max function is
a good example of this. One that's taking an
argument, we call the things in between the parentheses. When we're invoking
the function, we call the things in between
the parentheses arguments. So that's passing
into the function, feeding data into the function. So we put arguments in between. So for example here we
have a little program that, it's a
function named greet. And now we are going
to define this function and we're going to
say, you know what? I would like to
take a parameter. Let's take a parameter. Let's have one
parameter come in. And we need kind of a
placeholder for that parameter so within the function
we're going to use lang. Now this isn't actually
a real variable. It's kind of like a, it's
a placeholder variable. So this first
parameter, whatever it is, when it's called,
is going to be lang. And so if that first
parameter is equal to es we're going to print hola. And if, else if it's equal
to fr we'll print bonjour. And otherwise will print hello. So there's apparently three
languages in the world; Spanish, French, and English. And if it's not Spanish or
French then it must be English. But I have keep
this kind of small so my screen
doesn't get too big. So this is again
just the definition and if you type this into
the interactive thing it gives this dot
dot dot product. And so we now have this
thing called greet. And now we've extended Python to
add our own function to Python. And now we can say greet en. And so it runs this code,
except that en is lang. And so that comes and
then it prints hello. So out comes hello. Now later we can say oh I
would like to do a greeting, but this time I'm
going to pass es as it. So lang becomes, for this
execution, es and then it prints out hola. And then the next
execution lang is fr. So it executes this three
times, but lang is different each time because we passed in
different parameters each time. So that's how we can kind
of right general purpose code inside the
function and then reuse that general purpose
code in different ways. A real powerful
powerful mechanism the makes functions far more useful. Now functions don't necessarily
just have to do stuff. Real powerful
mechanism in a function is what we call a return value. So a function can
take its arguments, do some work we've seen that. And then, it can return a value. And the key to the
return value is when we call the function
like we were calling max, it gives us back some
value like the little w. So here we're going to
make a function called greet that takes no parameters. Don't take parameters. But it has another keyword. It's another reserved
word in Python and whatever we put on
this return statement shows up as the replacement
in this expression. So whatever greet
is, it runs greet, and then the return is
kind of a residual value. So if we say print
greet, Glenn and it says hello, Glenn
because the return value for the greet function
is the string hello. And if we say greet, Sally
it says hello, Sally. And so it runs the code twice;
and the return function, return value has been
put in here instead. And so the hello came
there and hello came there. So we get the two lines. So return is a statement
that both terminates the execution of the function
and defines the value of what will be replaced when the
function call comes back in the line that
function was called from. So, here is a little smarter
version of our greet function. It's very similar, it's
still called greet still. It takes lang as a parameter. And if the language
is the es then it returns the string hola. If the language is French
it returns bonjour. Otherwise it returns hello. So we're not actually
doing the print. If you go back another
slides we are printing but now we're just
returning a string. OK so now I can call
print greet and pass en in so then that runs the
code once with lang equal to en and I get back hello
and then comma blank. Then I call it again
and I pass es in, and then that time it
returns the return value here becomes hola, a string hola. Hola, Sally. And then Michael. I pass in one more time. Lang now is fr, the string
fr, and so it returns bonjour. So the residual
is here is bonjour and so out comes
bonjour, Michael. There's a lot to this, right? Passing stuff in , you have this
kind of placeholder variable, and you have this return that
sort of appears where it was called from. It goes in, does its
work, it comes back, and there's sort of this
residual value that sits here. You don't have to have
a return in a function, but if you want to do
something with a value then you have to have a
return in the function. We call the functions that
produce values fruitful, and the other ones
are called void. So that's a good name for them. So, to review sort
of this arguments parameters and
results, if we look at max, the original
thing where it's looking for the largest,
lexicographically largest letter, it
looks: hello, world is the argument
that's passed in. We have this sort
of formal parameter here called imp, which is
not really variable it just happens to refer to whatever
is the first argument in any particular call. And that does it's little
thing and runs loops and does all these things, and
at some point it returns w. So that the thing that comes
out when the function quits that becomes the
replacement value here is a lowercase w string. And then that is the
w goes over into big. So the return is what
defines what comes back here. Because you think of this
as; it's looking at this, it suspends for the
moment, it runs this code, its holding itself
here running this code and then it comes back to here. OK? And the return value is
what defines coming back. So, of course you can have
more than one parameter and they are in order. So here we have an a and a b. The name of these things
doesn't really matter. They're just relevant inside
of the function definition. So we are going to add
two numbers together by taking a plus b and
then returning the sum. The added variable's just
kind of local to this function and now we can say addtwo(3,5)
and then this will come back as eight and then eight
will get assigned into x, and so that'll print out eight. And so you can have as
many of these as you want, and the order
matters and there's a one to one correspondence. Three goes to a and five goes
to b when the thing is called, and then the return
value again comes back. OK? So, that's sort of arguments. And like I said,
not all functions have to return values. We call them void functions
when they don't return anything. It's totally fine for
that to be the case. So at this point you might be
thinking to yourself, OK great. I still don't quite get
why to use functions. In reality, in the
first 10, 11 chapters of this book other than
using lots of functions, we're not really going to spend
a lot of time making functions. Because most of our programs are
going to kind of be that long. And we're not going to do a
lot of reuse in the program. And there'll be a time when your
programs become complex enough, that you'll be like, oh
thank heaven for functions. I think it's premature to
say you must use functions, even though there are
some exercises that just say hey do this
with a function, just so you kind of get the
understanding of a function. You will find soon enough,
as your programs grow, you'll go like oh I keep
doing the same thing over and over again. Let me pull that
up into a function and pass the parameter
in, have a return value, and away you go. Or you might find that you're
moving from one program to another and you
have this common thing that you want to do so you
make yourself a library that you drag along. And we will do
lots of libraries. The book in the second half does
lots and lots of library stuff doing things like parsing
XML, and this, that, and the other thing. So, don't feel like you
need to use functions on every assignment because
they're a are natural thing when the program
gets big enough. So, just kind of understand
them on a mechanical level, but it'll come to you
at the right time when it's time to start building
your own functions. So in this class we kind
of talked about functions. Just got you started,
talked about parameters, talked about built in functions,
talked about return values, the store and reuse pattern. So, the problems at the end
the chapter for this particular chapter are relatively
straightforward in that — like I said, we don't have
a real strong need to do functions yet in this
class because the programs aren't large enough, but
I just said OK take one of your previous assignments
and refactor the code so that at the top there's
a DEF, compute pay, and you put like the if
and whatever in here. And then later on
you do your code, and then you call compute pay. So you took code
that you already had, you move it up into a
function, and make a function. And I've also online got
sort of a sample of this, because it's a little complex. And so you should be able
to find on Python learn or on the course site; should
be able to find a good example because I really
want to get this. Like I said, there
will come a time when functions will make
the most sense to you. But coming up
next, of course, is chapter five and that's loops. And loops are going
to rock the house. So we really; that's our
fourth major pattern is loops. And I'm looking forward to it. So we'll see you at
the next lecture.


  1. Poptropica 2002 said:

    Skip to 3:25

    June 27, 2019
  2. George Nikou said:

    Teaching is a skill and you definitely got it and then some. Subbed.

    June 27, 2019
  3. Herr Skyy said:

    You are amazing! ♥

    June 27, 2019
  4. ThePowerchimp said:

    You've explained in 28 minutes what my lecturer took a week to explain and I still understood your style better! Thanks a million!

    June 27, 2019
  5. Eskimo said:

    Thanks Professor Snape =D

    June 27, 2019
  6. Hussein Altaeyb said:

    So interesting ^_^

    June 27, 2019
  7. Subhash Kalluri said:

    I could not find chapter 5 in the videos. Could you help me please?

    June 27, 2019
  8. mazvita guvi said:

    you are the best explainer in the whole world, and you are funny too, and make things easy to understand.

    June 27, 2019
  9. Tian Zhang said:

    Thank you Prof. Snake, oh no, I mean Dr.Severance for making this course funny and easy understanding!!

    June 27, 2019
  10. Mohamed Mohamed said:

    Does anyone know why this is not working I know it is not full proof. ie 168 hours in a week etc. But, I thought it should at least work.

    def computepay(hr,rt):
    if hr > 40:
    num = ((40*rt)+((hr-40)*rt*1.5))
    return num
    elif hr > 0 and hr <= 40:
    return hr * rt
    return 0

    hours = raw_input('Enter Hours:')
    Rate = raw_input('Enter Rate:')
    pay = computepay(hours,Rate)
    print('Pay:'+ str(pay))

    June 27, 2019
  11. H Olagoke said:

    Thank you Prof. Severance for making this programming easy to understand. I enjoyed your lectures.

    June 27, 2019
  12. mrpaupie said:

    Thank you for posting this! It's going to help me get through Fundamentals of Programming.

    June 27, 2019
  13. aniruddh shrivastava said:

    Sir please write with dark color over green,,it will be more visible.

    June 27, 2019
  14. kyesha nason said:

    lol he is an awesome teacher with a great personality. We need more professors like him in school. I have been taking his python class online and he has made it so much fun to learn. I love programming again because of him. I took a C++ class at Michigan State and hated it. The teacher was a bore and just made everything much more confusing with her teaching methods.

    June 27, 2019
  15. JackBullenskie said:

    Haven't even gotten to the teaching portion yet, an I already love this.  You seem like a pretty awesome teacher! I've been learning Python, and it's great to have some mellow comic relief. 

    June 27, 2019
  16. Emil Emil said:

    Wow, I went through so many videos and no one explain better than you ! thank you for your video, im looking forward for chapter 5

    June 27, 2019
  17. Caihao Cui said:

    I really like the Harry Potter part, LOL

    June 27, 2019
  18. Adam Thomas said:

    Great video which has helped me more than you can imagine. Thanks Chuck!!

    June 27, 2019
  19. sanshinron said:

    Why does type(10) function outputs <type 'int'>, but when I want to use in a comparative statement I have to only use int? For example, type(10) == int is true.
    Is there a reason why type(10) returns this weird string, instead of just int?

    June 27, 2019
  20. T Millar said:

    awesome lectures btw

    June 27, 2019
  21. T Millar said:

    for exercise 4.7 i couldn't figure out how to define "Bad score", if the input was a string?

    June 27, 2019
  22. XHalcyonX said:

    Wow. So much better than my university lecturer whom I am completely unable to understand. So logical, so helpful and very easy to understand. Thank you so much. I finally understand functions. This is great. Will recommend to all my friends. 

    June 27, 2019
  23. santiago vazquez said:

    Gracias Profe soy de ecuador….

    June 27, 2019
  24. Luis Alfonso Ch. Abbadie said:

    Thank you teacher! ;P

    June 27, 2019
  25. Chuck Severance said:

    I just updated the description to include a link to my playlist.

    June 27, 2019
  26. Luis Alfonso Ch. Abbadie said:

    Really cool, thanks a lot! But what happened to the chapter 5… why there's no video?

    June 27, 2019
  27. Daniel Escudero said:

    Thank you very very much, this is infinitely useful for me. Thanks.

    June 27, 2019

Leave a Reply

Your email address will not be published. Required fields are marked *