Methods
● Built-in objects in Python have a variety of
methods you can use!
● Examples of such methods are lst.append(),
lst.insert(), str.title() etc…
Functions
● Creating clean repeatable code is a key part of
becoming an effective programmer.
● Functions allow us to create blocks of code that
can be easily executed many times, without
needing to constantly rewrite the entire block of
code.
● Functions will be a huge leap forward in your
capabilities as a Python programmer.
● This means that the problems you are able to solve
can also be a lot harder!
● It is very important to get practice combining
everything you’ve learned so far (control flow,
loops, etc.) with functions to become an effective
programmer.
Functions
Difficulty of
Problems You
Can Solve
Loops and
Logic
Basic Data
Types
Progress in Python
def Keyword
● Creating a function requires a very specific syntax,
including the def keyword, correct indentation, and
proper structure.
● Let’s get an overview of a Python function
structure.
def name_of_function():
Keyword telling Python
this is a function.
def name_of_function():
You decide on the function
name.
def name_of_function():
Snake casing is all lowercase with
underscores between words
def name_of_function():
Parenthesis at the end. Later on we can
pass in arguments/parameters into the
function.
def name_of_function():
A colon indicates an upcoming
indented block. Everything indented is
then “inside” the function
def name_of_function():
’’’
Docstring explains function.
’’’
Optional: Multi-line string to describe
function.
def name_of_function():
’’’
Docstring explains function.
’’’
Note: Everything inside the
function is indented
def name_of_function():
’’’
Docstring explains function.
’’’
print(“Hello”)
Code then goes inside the
function.
def name_of_function():
’’’
Docstring explains function.
’’’
print(“Hello”)
Function can then be
executed/called to see the
result.
>> name_of_function()
>> Hello
def name_of_function():
’’’
Docstring explains function.
’’’
print(“Hello”)
>> name_of_function()
Resulting Output
>> Hello
def name_of_function(name):
’’’
Docstring explains function.
’’’
print(“Hello ”+name)
>> name_of_function(“Jose”) Functions can accept
arguments to be passed by
>> Hello Jose the user.
def name_of_function(name):
’’’
Docstring explains function.
’’’
print(“Hello ”+name)
>> name_of_function(“Jose”) Functions can accept
arguments to be passed by
>> Hello Jose the user.
● Typically we use the return keyword to send back
the result of the function, instead of just printing it
out.
● return allows us to assign the output of the
function to a new variable.
def add_function(num1,num2):
return num1+num2
>> result = add_function(1,2) Return allows to save the
result to a variable.
>>
>> print(result)
>> 3
def add_function(num1,num2):
return num1+num2
>> result = add_function(1,2) Most functions will use
return. Rarely will a
>> function only print()
>> print(result)
>> 3