Python Tutorial for Beginners 8: Functions
Summary
TLDRThis educational video script teaches the basics of functions in Python. It explains how functions are defined with the 'def' keyword, can have parameters, and may return values. The script covers the benefits of reusing code with functions, the importance of keeping code DRY (Don't Repeat Yourself), and the concept of function arguments and default values. It also touches on unpacking arguments using * and **, and ends with an example tying together the concepts using Python's standard library.
Takeaways
- 📚 Functions in programming are blocks of code designed to perform a specific task.
- 🔑 The 'def' keyword in Python is used to define a function, which groups together instructions.
- 👤 Functions can have parameters, which are inputs that you can pass to the function when calling it.
- 🔍 The 'pass' keyword can be used as a placeholder within a function when you don't want it to perform any action yet.
- 💡 To execute a function in Python, you must include parentheses after the function name.
- 🔄 Functions help to avoid code repetition by allowing you to reuse the same block of code multiple times.
- 🔀 The concept of 'DRY' (Don't Repeat Yourself) is emphasized by using functions to keep code concise.
- 🔔 Functions can return values, which means they can output data after performing an operation.
- 🔀 Functions can be used to process data and then return the processed data to the caller.
- 📝 Docstrings are used to document what a function does and are placed right after the function definition.
Q & A
What is the purpose of using the 'def' keyword in Python?
-The 'def' keyword in Python is used to define a function, which is a block of organized, reusable code that is used to perform a single, related action.
How do you create a function in Python without any parameters?
-You create a function without any parameters by using the 'def' keyword followed by the function name and empty parentheses: `def functionName():`.
What does the 'pass' keyword do in a Python function?
-The 'pass' keyword in a Python function is a null operation that does nothing. It is used when a statement is required syntactically but no action is needed.
How do you execute a function in Python?
-You execute a function in Python by calling its name followed by parentheses: `functionName()`.
What is the benefit of using functions to reuse code?
-Using functions to reuse code allows you to make changes in one place instead of multiple places throughout your program, reducing the chance of errors and making your code more maintainable.
What does the acronym DRY stand for in programming?
-DRY stands for 'Don't Repeat Yourself', a principle in software development aimed at reducing repetition of software patterns.
How can you make a function return a value in Python?
-You can make a function return a value in Python by using the 'return' keyword followed by the value you want to return: `return someValue`.
What is the significance of the 'None' value when a function does not return anything?
-If a Python function does not explicitly return a value, it defaults to returning 'None', which is a built-in constant that represents the absence of a value or a null value.
How do you pass arguments to a function in Python?
-You pass arguments to a function in Python by specifying them within parentheses after the function name when calling the function: `functionName(arg1, arg2, ...)`.
What is the difference between positional and keyword arguments in Python functions?
-Positional arguments are passed to a function in the order they are defined, without needing to specify the parameter name. Keyword arguments are passed by naming the parameter followed by the value.
How can you accept a variable number of arguments in a Python function?
-You can accept a variable number of positional arguments using *args and a variable number of keyword arguments using **kwargs in the function definition.
What is the purpose of using * and ** in function calls in Python?
-In function calls, * is used to unpack iterables into positional arguments, and ** is used to unpack dictionaries into keyword arguments.
Outlines
📚 Introduction to Functions
This paragraph introduces the concept of functions as a way to package instructions to perform a specific task. It explains how to create a function using the 'def' keyword and how to execute it with parentheses. The importance of functions is highlighted by showing how they can be used to avoid repeating code, using a 'hello' function as an example. The paragraph also discusses the use of the 'pass' keyword as a placeholder for future code and the significance of parentheses in executing functions. The concept of functions returning values is introduced, and the idea of reusability and DRY (Don't Repeat Yourself) programming is emphasized.
🔄 Functions and Reusability
The second paragraph delves deeper into the benefits of functions, particularly in reusing code. It demonstrates how changing text in multiple locations can be cumbersome without functions. The paragraph shows how to update a function to include a print statement and how running the function multiple times can replace repeated code. The concept of 'return' is introduced, explaining how functions can operate on data and pass results to other parts of a program. The idea of treating the return value as data is also discussed, along with an example of chaining methods to a function's return value.
📝 Passing Arguments to Functions
This paragraph explains how to pass arguments to functions, starting with defining parameters within the function's parentheses. It uses a 'greeting' parameter to customize the function's output. The paragraph differentiates between required and optional arguments, using a 'name' parameter with a default value as an example. The concept of function scope is briefly mentioned, emphasizing that variables within a function do not affect those outside. The importance of maintaining the order of required and optional arguments when calling functions is also highlighted.
🌟 Advanced Function Arguments
The fourth paragraph covers more advanced topics related to function arguments, such as using *args and **kwargs to accept a variable number of arguments. It demonstrates how these can be used to pass an arbitrary number of positional or keyword arguments to a function. The paragraph also explains how to unpack sequences or dictionaries when passing arguments to a function using the * and ** operators. An example using a 'student_info' function illustrates these concepts, showing how arguments are handled within the function and the importance of adhering to naming conventions for clarity.
🔍 Tying It All Together
The final paragraph ties together the concepts learned in the video series by examining code from the Python standard library. It discusses a 'month_days' list and a function 'is_leap' that determines if a year is a leap year. The paragraph explains the use of docstrings to document functions and the logic behind leap year calculation. It also presents a 'days_in_month' function that returns the number of days in a given month, considering leap years. The paragraph concludes with a walkthrough of how these functions operate together and how they determine their return values based on the arguments passed.
Mindmap
Keywords
💡Function
💡Def
💡Pass
💡Return
💡DRY (Don’t Repeat Yourself)
💡Parameters
💡Positional and Keyword Arguments
💡Scope
💡Star (*) and Double Star (**)
💡Standard Library
Highlights
Introduction to functions in programming
Definition of a function using the 'def' keyword
Explanation of function parameters
Use of the 'pass' keyword in functions
Executing a function vs. referencing it
Adding code to a function to perform actions
Benefits of functions for code reusability
The DRY principle (Don't Repeat Yourself)
Returning values from functions
Understanding function inputs and outputs
Chaining function return values with methods
Passing arguments to functions
Creating parameters with default values
Required vs. optional arguments in functions
Using *args and **kwargs for arbitrary arguments
Unpacking sequences and dictionaries in function calls
Applying function concepts to Python's standard library
Example of determining leap years with functions
Example of calculating days in a month
Explanation of docstrings in functions
Walkthrough of function execution with arguments
Summary and conclusion of the tutorial
Transcripts
hey there how's it going everybody in
this video we'll be learning about
functions now functions are basically
some instructions packaged together that
perform a specific task so let's create
our first function and see why these are
so beneficial Now to create a function
we'll use the defa keyword which I
believe stands for definition and let's
just make a simple function here to get
started I'll call this hello Funk now we
have parentheses there because that is
where our parameters will go when we add
those in but we don't have any
parameters just yet so that will be
empty for now now it is possible to
write a function and not have any code
in it but we can't leave it completely
blank uh but if we want to fill this
function in later then we can use this
pass keyword and basically that pass
keyword is saying that we don't want to
do anything with this for now but it
won't throw any errors for leaving it
blank so if we want to run our function
then we can just say hello Funk and put
in these parentheses and we need to add
those parentheses after the function in
order to execute it if we don't have
those parentheses there then it'll be
equal to the function itself um so let's
actually see what that looks like so I'm
going to print out that hello function
without the parentheses in place uh
which means that we're not executing the
function so let me run that and we can
see when we printed that out that it
prints out that this is a function in a
certain location in memory but it didn't
execute the function so to execute it
then we add in these parentheses so now
if I run this then now it just gives us
none because we're not doing anything
with this function yet and it doesn't
have a return value so let's go ahead
and put some code into our function so
first we'll just put in a print
statement and we'll just print out some
text that says hello function with an
exclamation point and now that we're
actually running that print statement
from within the function we don't need
to print out that executed function we
can just execute that function and it
should run that print statement so we'll
run that so we can see that we executed
our function here it came within our
function and ran our print statement now
one benefit of functions is that they
allow us to reuse code without repeating
ourselves so let's say for example that
we had to print out some text in several
locations throughout our program so it
might look something like this so let me
copy this and I'll comment out our uh
function execution for now and I'm just
going to paste this in about four times
so now if we run this then as we expect
it prints out our four messages now
imagine our boss came to us and told us
that uh the text was a little bit off
and that we didn't want to have an
exclamation point at the end of the
string well the way that we have it now
we'd have to come in here and change all
of those manually so I'd come in and
change all these man messages to have a
period instead now that was only four
changes to make there but in some instan
that can be in hundreds of locations in
multiple different files so that's the
first benefit of functions it allows us
to put code with a specific purpose into
a single location so instead of printing
those four statements uh what we can
instead do is run our function four
times so I will remove that and
uncomment our function and we're going
to execute this four different times so
now if we run that then we can see that
it ran our function four times and
executed our print statement four
different times but now if our boss came
to us and asked us to remove that
exclamation point then it doesn't matter
if this is spread out over a 100
different lines or 100 different
locations we can just update it in this
one spot so I can change this to a
period and now if we run this then we
can see that those changes are seen
everywhere that the function is called
now this is called keeping your code dry
which stands for don't repeat yourself
it's a common mistake for people new to
programming to repeat the same things
throughout their code when really they
could either put their code into certain
variables or functions so that it's in a
single location so we saw earlier that
since we aren't returning anything from
our function uh it was actually equal to
none so what does it mean for uh our
function to return something now this is
where functions become really powerful
because it allows us to operate on some
data and then pass the result to
whatever called our function so instead
of of printing this string hello
function within here let's instead
return this okay so what does this mean
exactly this means that when we execute
our function it's actually going to be
equal to our return value so these
executed functions here are actually
equal to the string hello function so
right now if we run this then it doesn't
give us any results because it's just a
string that we're not doing anything
with but if instead we print this so me
print that executed function and if we
run that then we can see that it prints
out our string so basically think of a
function as a machine that takes input
and produces a result when you execute a
function you can think of it almost like
a black box you don't need to know
exactly how it's doing what it's doing
you're mainly concerned about the input
and the return value so in this simple
example here we don't have any input and
we can see that the return value is a
string
um now don't get me wrong it's useful to
know what a function is doing but when
you're first getting started don't get
caught up on understanding every detail
of what every function does just focus
on the input and what's returned so for
example when we call the Len function on
a string so if I print out Len of this
string test if I run this then as we saw
in a previous video this just returns an
integer that is the number of of
characters in our string so we have no
idea what the code that produces that
result looks like but we do know that we
passed in a string and that it returned
this integer and we'll see why here in a
bit why looking at functions in this way
will help you become better when working
with python because we can treat the
return value just like the data type
that it is and understanding this will
allow you to chain together some
functionality so we know our hello
function returns a string so we can
treat that executed function just like a
string so if we remember back to our
string Methods remember that we can
uppercase a string with uper so really
we can take this executed function and
just chain uper onto the end of it so
now if we run this now we can see that
our executed function returned the
string hello function and then we were
able to use the string method upper on
that returned value to uppercase the
string um okay so now let's look at how
we can pass arguments to our function
and real quick I'm going to remove that
uper method so to be able to pass
arguments to our function we'll need to
create some parameters here within our
parentheses so let's say that we wanted
to customize the greeting that our
function returns so let's create a uh a
parameter called greeting and now within
our function we'll return a string where
we use that greeting instead of of our
uh hello text that we had before so now
I'll just pass this in with a DOT format
so now before we run this we have to
pass in that greeting argument when we
execute our function if we don't then
we'll get an error so actually let's go
ahead and run this and see this error so
we can see that when we ran that it says
that hello Funk is missing one required
positional argument greeting so let's
pass in that greeting argument to our
hello function and to do that we can
just pass it in directly here when we
call our function so I'm just going to
pass in uh high as our string so now if
we run this then we can see that when we
passed in that string High into our
function that it set that greeing
variable equal to the string high and
then returned the string High function
now this greeding variable doesn't
affect any variables outside of the
function its scope is only local to
theun function which is nice because we
don't have to worry about it affecting
anything we don't want it to affect so
and if you want to learn more about
python scope then I do have a detailed
video going in depth as to how that
works exactly and I'll leave a link to
that video in the description section
below okay so right now this greeting
parameter is a required argument and
that is because it doesn't have a
default value now if we had a default
value then it would just fall back to
the default value whenever we didn't
pass that argument in so let's see an
example of this so let's say that we
also want to be able to pass a name to
our hello function and it'll return a
greeting and the name so we can add that
to our parameters by putting in a comma
here and saying that we also want to
accept this name parameter but let's say
that if no name is passed in then we
want to have a default value of U so we
can just say name is equal to U and now
let's add that to our return string so
I'll put in a comma space and then
another placeholder and we'll pass in
that name so what this is going to do is
it'll return a greeting and a name
separated by a comma and a space so if
we run this then we can see that even
though we didn't pass in a value for the
name argument when we executed this
function it didn't throw an error and
instead Ed the default value that we
specified as U but if we want to pass in
a value then it will use that value
instead so when we execute this function
if I was to say name is equal to and
we'll say Corey and run that then now we
can see that printed out the greeting
with the name that we passed in um now
your required positional arguments have
to come before your keyword arguments
now if you try to create a function with
those out of order then it's going to
give you an error now this is a little
more advanced topic topic that tripped a
lot of people up but at some point
you'll probably run across a function in
Python uh that looks something like this
so I'll say def student info and you
might see something where you see this
star args and star star quars and so let
me just go ahead and within this new
function here I will print out args and
I'll also print out quars so let's not
really worry about this function name
for now it's the arguments that I want
to focus on so seeing this star args and
star star quars can seem confusing at
first but basically all it's doing is
allowing us to accept an arbitrary
number of positional or keyword
arguments so for example let's say that
this student info function takes
positional arguments that represent the
classes that the student is taking plus
the keyword arguments passed in will be
random information about the student so
so you can see in both of those examples
we don't know how many of these
positional or keyword arguments there
will be and that's why we use star args
and star star quars and the names don't
have to be args and quars but that's a
convention that you'll see a lot so it's
always good to stick with convention so
that people can understand your code so
let's call this function with some
random values so I'm going to say
student info and first we want to pass
in some positional arguments of the
classes that they're taking so we'll say
math and art and now for our keyword
arguments we'll pass in some random
information about the student so we'll
say name is equal to John and age is
equal to 22 so now if we run this then
we can see that when we printed the args
it's actually a tupal with all of our
positional arguments and our quars are a
dictionary with all of our keyword
values so once you have that tupal and
that dictionary then you'll be able to
do whatever you want with that
information now sometimes you might see
a function call with arguments using the
star or double star now when it's used
in that context it will actually unpack
a sequence or dictionary and pass those
values into the function individually so
to see what I mean let's make a list in
a dictionary of everything that we just
passed into our function and just to
clear up some room here I'm going to go
ahead and delete the hello function that
we started off with so now I'm going to
create a list called courses and I'm
going to set this equal to math and art
that we passed in before and instead of
a tupal I'm going to make that a list so
now for the student info I'm going to
create a dictionary called info and set
that equal to those values so now let me
get rid of our positional and keyword
arguments here so let's say that we
wanted to pass all of these courses in
as our positional arguments and the info
dictionary as our keyword arguments so
if we just pass these in as is and I
passed in courses and info now if we run
this then we can see that this might not
be exactly what we thought instead of
passing the values in individually and
instead passed in the complete list and
the complete dictionary as positional
arguments so if we use the single star
in front of our list and the double star
in front of our dictionary then it will
actually unpack these values and pass
them in individually so basically it
will be the equivalent to our previous
execution uh where we pass them in
individually so to see what I mean let's
add a star in front of this courses to
unpack those values and a star star in
front of our dictionary to unpack those
keyword values so now if we run this and
we can see that we got what we had
before um we can see that when our
function prints args it's the values
from our list that we unpacked and our
quars is equal to the dictionary values
that we unpacked now I know that's a
little confusing especially to you know
get the idea that whenever you're
passing these in that it unpacks the
values and within here it's for
accepting an arbitrary number of
positional or keyword values but uh it's
a little more advanced of a topic and I
know it's confusing but hopefully it
makes some sense and you'll be able to
better understand understand what's
going on if you ever run into something
like that okay so lastly I wanted to run
through an example that ties together
everything we've learned so far in this
series of videos so I have some code
here in my Snippets file that I'm going
to grab real quick and paste into the
file that we've been working with so now
let me lower this output a little bit so
that we can see everything here now
these are actually a couple of functions
that I grabbed in the python standard
Library I modified them very slightly
but it's basically the same and I wanted
to show that even though we've only gone
over the fundamentals we're already able
to look at some code from within the
standard Library itself and understand
what's going on so at the top here we
have a list called month days and this
has the number of days in each month now
the first index here is just a
placeholder that's not going to get used
um we're only going to be accessing
indexes one through 12 since those are
the months and then we have a function
here called is Leap which determines if
a year is a leap year it takes a single
argument that is the year that it's
checking and we can see that there's
this string um after the function
definition with three quotes and this is
called a dock string and dock strings
help document what a function or a class
is supposed to do so it's a good
practice anytime you write a function to
write a doc string that goes along with
it explaining what that function is
supposed to do now this part here can
seem a little intimidating but it's not
important that you understand how a leap
year is calculated there's not a lot of
people who know that off the top of
their head um but for various reasons
this is how a leap year is calculated
and it's not important but you could
probably figure out what this uh
conditional is doing so we're saying
that if the year is divisible by four
and uh it's not divisible by 100 or it's
divisible by 400 so like I was saying
there's a lot of different reasons why
uh leap years are determined this way
and if you don't know that that's
completely fine but this function here
is going to return true if a year is a
leap year and false if it's a non-leap
year and down here we have a days and
month function that takes a year and a
month as arguments and it'll return the
number of days in that month so if we
look at how this function works we can
see that it first checks if a month is
between one and 12 and if it's not then
it returns that it's an invalid month
and then it checks if the month that
we're working with is the second month
which would mean that it's February and
is a leap year using our function up
here at the top then it returns 29 if
both of those are true and lastly if it
makes it to the end without having
returned anything yet then it will index
into our month days and list up here at
the top and return the value of our
month so let's just run through this one
time and see how these functions work so
outside of both of the functions we're
going to go ahead and first use this is
Leap Year function so we'll say is Leap
2017 so if we run this then it returns
false so we ran this function is Leap
passed in 2017 as our value and it went
through this complicated conditional
here and determined that that was false
but if we type in 2020 here and run that
then we can see that it returns true
that 2020 is a leap year but now let's
try our days and month function which is
going to be a little bit longer of a
walkthrough so we'll say days and month
and we'll pass in a year so it takes a
year first we'll pass in a year of 2017
and we'll pass in a month of two which
is February now since 2017 is not a leap
year then this second month which is
February should only have 28 days so if
we run this then we can see that we got
28 so let's walk through exactly what
happened just so we're sure that we
understand so we executed our days and
month function with our arguments of
2017 for the year and two for the month
so it comes in uh to our days and month
function and it sets this year variable
equal to 2017 and this month variable
equal to two so let's comment those here
just to keep track of them through our
walkthr so I'll put a comment for year
as 2017 and a comment for month as two
so first it checks if our month is not
between 1 and 12 our month is two so it
is in that range so it doesn't meet this
conditional and since it doesn't meet
that conditional then we just continue
on so our next conditional asks if the
month is equal to two and is a leap year
so our month is equal to two but this is
Leap function runs through its code with
the year 200 17 and returns false so
since is Leap is false and we're using
an and operator then the whole
conditional evaluates to false so we
move on and lastly it accesses the month
days list at this month index and
remember that our month is equal to two
so it's accessing the second index and
if we look up here to our month day list
and go to our second index so 0 one two
then we can see that that's equal to 28
so it should be returning 28 here and
finally when we printed out that result
28 is what we got as our result now I
know that was kind of a long walkthrough
but I thought it might be useful to see
how these things actually work together
and how do you go about determining what
a function should return based on the
arguments that you pass in okay so I
think that is going to do it for this
video I hope that now you have a clear
understanding of how functions work how
we return values and the different ways
that we can pass arguments in the next
video we'll be learning how to import
modules and also learn about some of the
useful modules that come in the standard
library but if anyone has any questions
about what we covered in this video then
feel free to ask in the comment section
below and I'll do my best to answer
those and if you enjoy these tutorials
and would like to support them then
there are several ways you can do that
the easiest way is to Simply like the
video and give it a thumbs up and also
it's a huge help to share these videos
with anyone who you think would find
them useful and if you have the means
you can contribute through patreon and
there's a link to that page in the
description section below be sure to
subscribe for future videos and thank
you all for watching
Посмотреть больше похожих видео
Functions | Godot GDScript Tutorial | Ep 13
Go (Golang) Tutorial #9 - Using Functions
First-Class and Higher-Order Functions | JavaScript 🔥 | Lecture 121
Functions in Karel - Python
FIRST CLASS FUNCTIONS 🔥ft. Anonymous Functions | Namaste JavaScript Ep. 13
42. OCR A Level (H046-H446) SLR8 - 1.2 Introduction to programming part 3 procedures & functions
5.0 / 5 (0 votes)