SlideShare a Scribd company logo
Functions
function
name
text = input('Enter text: ')
To call a function, write the function name followed by
parenthesis. Arguments are the values passed into
functions. A function returns a value.
parenthes
es
Review
return value assigned to the
variable text
argume
nt
A variable is a name that refers to a value.
Variables are defined with an assignment
statement.
A function is a name that refers to a series of
statements.
Functions are defined with a function
definition.
Why define functions?
● Functions can be used to eliminate
repetitive code
● Functions make code easier to read by
naming a series of statements that form a
specific computation
● Functions make it easier to debug your
code because you can debug each function
independently
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
A function definition specifies the name of a new function
and the series of statements that run when the function is
called.
keyword used to start a
function definition
function name parameters (variable names
that refer to the arguments
passed in)
keyword used to return a value to the function
function
body
indented
4 spaces
the function header
ends in a colon
def get_average(number_one, number_two):
"""Returns the average of number_one and
number_two.
"""
return (number_one + number_two) / 2
Function definition style
Function names should be lowercase words separated by underscores, just
like variable names. Each function should include a docstring immediately
below the function header. This is a multi line comment starts and ends with
three double quotes (""") and should explain what the function does. This
comment should always include a description of the value that the function
returns.
# Define the function print_greeting
def print_greeting():
print('Hello')
# Call the function print_greeting
print_greeting() # This will print 'Hello'
Function with no parameters
# Define the function greet
def greet(name):
print('Hello', name)
# Call the function greet
greet('Roshan') # This will print 'Hello Roshan'
Function definition with one
parameter
# Define the function print_sum
def print_sum(number_one, number_two):
print(number_one + number_two)
# Call the function print_sum
print_sum(3, 5) # This will print 8
Function definition with two
parameters
# Define the function get_sum
def get_sum(number_one, number_two):
return number_one + number_two
# Call the function get_sum
total = get_sum(3, 5)
print(total) # This will print 8
Function definition with two
parameters and a return
statement
function runs
your
program calls
the function
your
program
continues
your program passes
arguments with the
function call
the function returns a
value for the rest of
your program to use
What happens when you call a function?
What happens when you call a function?
1) The arguments passed into the function (if
any) are assigned to the parameters in the
function definition
2) The series of statements in the function
body execute
3) When the function block ends or a return
statement is executed, the function will
return execution to the caller
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
boiling = convert_to_fahrenheit(100)
print(boiling)
The function convert_to_fahrenheit is
defined. Note that the series of statements in
the function body are not executed when the
function is defined.
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
boiling = convert_to_fahrenheit(100)
print(boiling)
The expression on the right side of this
assignment statement is evaluated. This calls
the convert_to_fahrenheit function with the
argument of 100.
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
boiling = convert_to_fahrenheit(100)
print(boiling)
During the function call, the celsius
parameter is assigned the value of the
argument, which in this case is 100.
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
boiling = convert_to_fahrenheit(100)
print(boiling)
The statements in the function body now
execute. This line assigns 100 * 9 / 5 + 32
(which evaluates to 212.0) to the variable
fahrenheit.
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
boiling = convert_to_fahrenheit(100)
print(boiling)
This line is called a return statement. The
syntax is simply return followed by an
expression. This return the value of 212.0
back to the caller. convert_to_fahrenheit(100)
will evaluate to this return value.
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
boiling = convert_to_fahrenheit(100)
print(boiling)
After evaluating convert_to_fahrenheit(100),
the return value of 212.0 will be assigned to
the variable boiling.
def convert_to_fahrenheit(celsius):
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
boiling = convert_to_fahrenheit(100)
print(boiling)
The print function is called with the argument
of 212.0. This will print 212.0 to the screen.
Common issues with defining functions
● The statements in a function definition are not
executed when the function is defined - only when the
function is called.
● The function definition must be written before the first
time the function is called. This is equivalent to trying
to refer to a variable before assigning a value to it.
● The number of arguments passed to a function must
equal the number of parameters in the function
definition.
● Functions and variables cannot have the same name
● The return statement can only be used within the
A return statement is needed to return a value
from a function. A function can only return a
single value (but that value can be a data
structure).
The syntax for a return statement is simply:
return expression
where expression can be any expression.
Return statements can only exist within a function body. A
function body may contain multiple return statements.
During a function call, statements are executed within the
def get_pizza_size_name(inches):
if inches > 20:
return 'Large'
if inches > 15:
return 'Medium'
return 'Small'
Which return statement executes when get_pizza_size_name(22) is called?
Which return statement executes when get_pizza_size_name(18) is called?
Which return statement executes when get_pizza_size_name(10) is called?
Multiple return statements
def contains_odd_number(number_list):
for number in number_list:
if (number % 2) == 1:
return True
return False
Which return statement executes when contains_odd_number([2, 3]) is called?
Which return statement executes when contains_odd_number([22, 2]) is called?
Which return statement executes when contains_odd_number([]) is called?
Multiple return statements
Common return statement issues
● Only one value can be returned from a
function.
● If you need to return a value from a function:
○ Make sure every path in your function
contains a return statement.
○ If the last statement in the function is
reached and it is not a return statement,
None is returned.
def convert_to_seconds(days):
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
return seconds
print(minutes)
Local variables
Traceback (most recent call last):
File "python", line 6, in <module>
NameError: name 'minutes' is not
defined
Parameters and variables created within the
function body are considered local. These
variables can only be accessed within the
function body. Accessing these variables
outside of the function body will result in an
my_age = 20
def set_age(new_age):
my_age = new_age
set_age(50)
print(my_age)
Global variables
20
All variables defined outside of a function body
are considered global. Global variables cannot
be changed within the body of any function.
This will actually create a new local variable named my_age within the function body. The global my_age
variable will remain unchanged.
Variable naming best practices
● When writing a function, do not create a new
variable with the same name as a global
variable. You will see a “Redefining name
from outer score” warning in repl.it.
● You can use the same local variable name or
parameter name in multiple functions. These
names will not conflict.
Tracing Functions
1) The arguments passed into the function (if
any) are assigned to the parameters in the
function definition
2) The series of statements in the function body
execute until a return statement is executed
or the function body ends
3) The function call will evaluate to the return
value
4) Statements in the calling function will
continue to execute
Note that these steps apply for every single
What will this code print?
def get_hopscotch():
game = 'hopscotch'
return game
print(get_hopscotch())
What about this
code?
def get_scotch():
return 'scotch'
def get_hopscotch():
game = 'hop'
game += get_scotch()
return game
print(get_hopscotch())
What about this
code?
def get_hop():
return 'hop'
def get_scotch():
return 'scotch'
def get_hopscotch():
game = get_hop()
game += get_scotch()
return game
print(get_hopscotch())
def get_spooky(number):
return 2 * number
def get_mystery(number):
result = get_spooky(number)
result += get_spooky(number)
return result
print(get_mystery(10))
print(get_mystery(5))
What about this
code?
lunch = ['apple', 'kale', 'banana']
new_lunch = lunch
new_lunch[1] = 'pork'
print(new_lunch)
print(lunch)
['apple', 'pork', 'banana']
['apple', 'pork', 'banana']
How many list values are created here?
lunch ['apple', 'kale', 'banana']
new_lunch
lunch = ['apple', 'kale', 'banana']
new_lunch = lunch
An assignment statement assigns a variable to a
value. Only one list value is created (using the []
operator). new_lunch refers to the same value.
When a list is passed into a function as an
argument, the parameter refers to the same
list value.
lunch = ['apple', 'kale', 'banana']
def change_to_pork(food_list):
food_list[1] = 'pork'
change_to_pork(lunch)
print(lunch) ['apple', 'pork', 'banana']
def double_values(number_list):
"""Doubles all of the values in number_list.
"""
for index in range(len(number_list)):
number_list[index] = number_list[index] * 2
numbers = [3, 5, 8, 2]
double_values(numbers)
print(numbers)
Replacing list values in a function
The double_values function replaces each value in the
list with the doubled value. Notice that the function does
not need to return a value since the original list is
altered in the function.
Using multiple functions to make code more
readable
def contains_at_least_one_vowel(string):
for character in string:
if character in 'aeiou':
return True
return False
def get_strings_with_vowels(string_list):
words_with_vowels = []
for string in string_list:
if contains_at_least_one_vowel(string):
words_with_vowels.append(string)
return words_with_vowels
word_list = ['brklyn', 'crab', 'oyster', 'brkfst']
print(get_strings_with_vowels(word_list))

More Related Content

Similar to Understanding Python Programming Language -Functions (20)

PPT
function_v1fgdfdf5645ythyth6ythythgbg.ppt
RoselinLourd
 
PPT
function_v1.ppt
ssuser823678
 
PPT
function_v1.ppt
ssuser2076d9
 
PPTX
Python programing
hamzagame
 
PPT
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
RoselinLourd
 
PPTX
made it easy: python quick reference for beginners
SumanMadan4
 
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
PPTX
functioninpython-1.pptx
SulekhJangra
 
PPTX
C function
thirumalaikumar3
 
PPT
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
PPT
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
PPTX
Classes function overloading
ankush_kumar
 
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
DOC
Functions
zeeshan841
 
PPTX
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
PPTX
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
PDF
Functions in C++.pdf
LadallaRajKumar
 
PPTX
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
PDF
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
PDF
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
function_v1fgdfdf5645ythyth6ythythgbg.ppt
RoselinLourd
 
function_v1.ppt
ssuser823678
 
function_v1.ppt
ssuser2076d9
 
Python programing
hamzagame
 
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
RoselinLourd
 
made it easy: python quick reference for beginners
SumanMadan4
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
functioninpython-1.pptx
SulekhJangra
 
C function
thirumalaikumar3
 
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Classes function overloading
ankush_kumar
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
Functions
zeeshan841
 
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
Functions in C++.pdf
LadallaRajKumar
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 

Recently uploaded (20)

PPT
deep dive data management sharepoint apps.ppt
novaprofk
 
PDF
apidays Helsinki & North 2025 - REST in Peace? Hunting the Dominant Design fo...
apidays
 
PDF
OPPOTUS - Malaysias on Malaysia 1Q2025.pdf
Oppotus
 
PDF
JavaScript - Good or Bad? Tips for Google Tag Manager
📊 Markus Baersch
 
PDF
WEF_Future_of_Global_Fintech_Second_Edition_2025.pdf
AproximacionAlFuturo
 
PDF
What does good look like - CRAP Brighton 8 July 2025
Jan Kierzyk
 
PPTX
Climate Action.pptx action plan for climate
justfortalabat
 
PDF
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
PDF
Data Chunking Strategies for RAG in 2025.pdf
Tamanna
 
PPTX
Module-5-Measures-of-Central-Tendency-Grouped-Data-1.pptx
lacsonjhoma0407
 
PPTX
Advanced_NLP_with_Transformers_PPT_final 50.pptx
Shiwani Gupta
 
PPT
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
PPTX
apidays Helsinki & North 2025 - APIs at Scale: Designing for Alignment, Trust...
apidays
 
PPTX
apidays Munich 2025 - Building Telco-Aware Apps with Open Gateway APIs, Subhr...
apidays
 
PPTX
apidays Helsinki & North 2025 - Running a Successful API Program: Best Practi...
apidays
 
PPTX
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
PDF
R Cookbook - Processing and Manipulating Geological spatial data with R.pdf
OtnielSimopiaref2
 
PDF
Web Scraping with Google Gemini 2.0 .pdf
Tamanna
 
PPTX
The _Operations_on_Functions_Addition subtruction Multiplication and Division...
mdregaspi24
 
PDF
Merits and Demerits of DBMS over File System & 3-Tier Architecture in DBMS
MD RIZWAN MOLLA
 
deep dive data management sharepoint apps.ppt
novaprofk
 
apidays Helsinki & North 2025 - REST in Peace? Hunting the Dominant Design fo...
apidays
 
OPPOTUS - Malaysias on Malaysia 1Q2025.pdf
Oppotus
 
JavaScript - Good or Bad? Tips for Google Tag Manager
📊 Markus Baersch
 
WEF_Future_of_Global_Fintech_Second_Edition_2025.pdf
AproximacionAlFuturo
 
What does good look like - CRAP Brighton 8 July 2025
Jan Kierzyk
 
Climate Action.pptx action plan for climate
justfortalabat
 
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
Data Chunking Strategies for RAG in 2025.pdf
Tamanna
 
Module-5-Measures-of-Central-Tendency-Grouped-Data-1.pptx
lacsonjhoma0407
 
Advanced_NLP_with_Transformers_PPT_final 50.pptx
Shiwani Gupta
 
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
apidays Helsinki & North 2025 - APIs at Scale: Designing for Alignment, Trust...
apidays
 
apidays Munich 2025 - Building Telco-Aware Apps with Open Gateway APIs, Subhr...
apidays
 
apidays Helsinki & North 2025 - Running a Successful API Program: Best Practi...
apidays
 
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
R Cookbook - Processing and Manipulating Geological spatial data with R.pdf
OtnielSimopiaref2
 
Web Scraping with Google Gemini 2.0 .pdf
Tamanna
 
The _Operations_on_Functions_Addition subtruction Multiplication and Division...
mdregaspi24
 
Merits and Demerits of DBMS over File System & 3-Tier Architecture in DBMS
MD RIZWAN MOLLA
 
Ad

Understanding Python Programming Language -Functions

  • 2. function name text = input('Enter text: ') To call a function, write the function name followed by parenthesis. Arguments are the values passed into functions. A function returns a value. parenthes es Review return value assigned to the variable text argume nt
  • 3. A variable is a name that refers to a value. Variables are defined with an assignment statement. A function is a name that refers to a series of statements. Functions are defined with a function definition.
  • 4. Why define functions? ● Functions can be used to eliminate repetitive code ● Functions make code easier to read by naming a series of statements that form a specific computation ● Functions make it easier to debug your code because you can debug each function independently
  • 5. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit A function definition specifies the name of a new function and the series of statements that run when the function is called. keyword used to start a function definition function name parameters (variable names that refer to the arguments passed in) keyword used to return a value to the function function body indented 4 spaces the function header ends in a colon
  • 6. def get_average(number_one, number_two): """Returns the average of number_one and number_two. """ return (number_one + number_two) / 2 Function definition style Function names should be lowercase words separated by underscores, just like variable names. Each function should include a docstring immediately below the function header. This is a multi line comment starts and ends with three double quotes (""") and should explain what the function does. This comment should always include a description of the value that the function returns.
  • 7. # Define the function print_greeting def print_greeting(): print('Hello') # Call the function print_greeting print_greeting() # This will print 'Hello' Function with no parameters
  • 8. # Define the function greet def greet(name): print('Hello', name) # Call the function greet greet('Roshan') # This will print 'Hello Roshan' Function definition with one parameter
  • 9. # Define the function print_sum def print_sum(number_one, number_two): print(number_one + number_two) # Call the function print_sum print_sum(3, 5) # This will print 8 Function definition with two parameters
  • 10. # Define the function get_sum def get_sum(number_one, number_two): return number_one + number_two # Call the function get_sum total = get_sum(3, 5) print(total) # This will print 8 Function definition with two parameters and a return statement
  • 11. function runs your program calls the function your program continues your program passes arguments with the function call the function returns a value for the rest of your program to use What happens when you call a function?
  • 12. What happens when you call a function? 1) The arguments passed into the function (if any) are assigned to the parameters in the function definition 2) The series of statements in the function body execute 3) When the function block ends or a return statement is executed, the function will return execution to the caller
  • 13. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit boiling = convert_to_fahrenheit(100) print(boiling) The function convert_to_fahrenheit is defined. Note that the series of statements in the function body are not executed when the function is defined.
  • 14. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit boiling = convert_to_fahrenheit(100) print(boiling) The expression on the right side of this assignment statement is evaluated. This calls the convert_to_fahrenheit function with the argument of 100.
  • 15. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit boiling = convert_to_fahrenheit(100) print(boiling) During the function call, the celsius parameter is assigned the value of the argument, which in this case is 100.
  • 16. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit boiling = convert_to_fahrenheit(100) print(boiling) The statements in the function body now execute. This line assigns 100 * 9 / 5 + 32 (which evaluates to 212.0) to the variable fahrenheit.
  • 17. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit boiling = convert_to_fahrenheit(100) print(boiling) This line is called a return statement. The syntax is simply return followed by an expression. This return the value of 212.0 back to the caller. convert_to_fahrenheit(100) will evaluate to this return value.
  • 18. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit boiling = convert_to_fahrenheit(100) print(boiling) After evaluating convert_to_fahrenheit(100), the return value of 212.0 will be assigned to the variable boiling.
  • 19. def convert_to_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit boiling = convert_to_fahrenheit(100) print(boiling) The print function is called with the argument of 212.0. This will print 212.0 to the screen.
  • 20. Common issues with defining functions ● The statements in a function definition are not executed when the function is defined - only when the function is called. ● The function definition must be written before the first time the function is called. This is equivalent to trying to refer to a variable before assigning a value to it. ● The number of arguments passed to a function must equal the number of parameters in the function definition. ● Functions and variables cannot have the same name ● The return statement can only be used within the
  • 21. A return statement is needed to return a value from a function. A function can only return a single value (but that value can be a data structure). The syntax for a return statement is simply: return expression where expression can be any expression. Return statements can only exist within a function body. A function body may contain multiple return statements. During a function call, statements are executed within the
  • 22. def get_pizza_size_name(inches): if inches > 20: return 'Large' if inches > 15: return 'Medium' return 'Small' Which return statement executes when get_pizza_size_name(22) is called? Which return statement executes when get_pizza_size_name(18) is called? Which return statement executes when get_pizza_size_name(10) is called? Multiple return statements
  • 23. def contains_odd_number(number_list): for number in number_list: if (number % 2) == 1: return True return False Which return statement executes when contains_odd_number([2, 3]) is called? Which return statement executes when contains_odd_number([22, 2]) is called? Which return statement executes when contains_odd_number([]) is called? Multiple return statements
  • 24. Common return statement issues ● Only one value can be returned from a function. ● If you need to return a value from a function: ○ Make sure every path in your function contains a return statement. ○ If the last statement in the function is reached and it is not a return statement, None is returned.
  • 25. def convert_to_seconds(days): hours = days * 24 minutes = hours * 60 seconds = minutes * 60 return seconds print(minutes) Local variables Traceback (most recent call last): File "python", line 6, in <module> NameError: name 'minutes' is not defined Parameters and variables created within the function body are considered local. These variables can only be accessed within the function body. Accessing these variables outside of the function body will result in an
  • 26. my_age = 20 def set_age(new_age): my_age = new_age set_age(50) print(my_age) Global variables 20 All variables defined outside of a function body are considered global. Global variables cannot be changed within the body of any function. This will actually create a new local variable named my_age within the function body. The global my_age variable will remain unchanged.
  • 27. Variable naming best practices ● When writing a function, do not create a new variable with the same name as a global variable. You will see a “Redefining name from outer score” warning in repl.it. ● You can use the same local variable name or parameter name in multiple functions. These names will not conflict.
  • 29. 1) The arguments passed into the function (if any) are assigned to the parameters in the function definition 2) The series of statements in the function body execute until a return statement is executed or the function body ends 3) The function call will evaluate to the return value 4) Statements in the calling function will continue to execute Note that these steps apply for every single
  • 30. What will this code print? def get_hopscotch(): game = 'hopscotch' return game print(get_hopscotch())
  • 31. What about this code? def get_scotch(): return 'scotch' def get_hopscotch(): game = 'hop' game += get_scotch() return game print(get_hopscotch())
  • 32. What about this code? def get_hop(): return 'hop' def get_scotch(): return 'scotch' def get_hopscotch(): game = get_hop() game += get_scotch() return game print(get_hopscotch())
  • 33. def get_spooky(number): return 2 * number def get_mystery(number): result = get_spooky(number) result += get_spooky(number) return result print(get_mystery(10)) print(get_mystery(5)) What about this code?
  • 34. lunch = ['apple', 'kale', 'banana'] new_lunch = lunch new_lunch[1] = 'pork' print(new_lunch) print(lunch) ['apple', 'pork', 'banana'] ['apple', 'pork', 'banana'] How many list values are created here?
  • 35. lunch ['apple', 'kale', 'banana'] new_lunch lunch = ['apple', 'kale', 'banana'] new_lunch = lunch An assignment statement assigns a variable to a value. Only one list value is created (using the [] operator). new_lunch refers to the same value.
  • 36. When a list is passed into a function as an argument, the parameter refers to the same list value. lunch = ['apple', 'kale', 'banana'] def change_to_pork(food_list): food_list[1] = 'pork' change_to_pork(lunch) print(lunch) ['apple', 'pork', 'banana']
  • 37. def double_values(number_list): """Doubles all of the values in number_list. """ for index in range(len(number_list)): number_list[index] = number_list[index] * 2 numbers = [3, 5, 8, 2] double_values(numbers) print(numbers) Replacing list values in a function The double_values function replaces each value in the list with the doubled value. Notice that the function does not need to return a value since the original list is altered in the function.
  • 38. Using multiple functions to make code more readable def contains_at_least_one_vowel(string): for character in string: if character in 'aeiou': return True return False def get_strings_with_vowels(string_list): words_with_vowels = [] for string in string_list: if contains_at_least_one_vowel(string): words_with_vowels.append(string) return words_with_vowels word_list = ['brklyn', 'crab', 'oyster', 'brkfst'] print(get_strings_with_vowels(word_list))

Editor's Notes

  • #1: we no longer have to solely be consumers of other people's code. we can create our own functions. - defining a function means we can assign a name to a specific computation - we can call that function within our own code. we can even expose these functions as a library for other programmers to use.
  • #3: A good analogy when thinking about variables vs. functions it that a variable is something while a function does something. The names for variables should be nouns, while the names for functions should be verbs.
  • #4: When your programs become longer and more complex, there will the several computations that will repeat more than once. - in a long computation, there are often steps that you repeat several times. using a function to put these steps in a common location makes your code easier to read. it's also easier to update if those steps change at some point in the future. - code reuse. imagine if nobody ever made a round function? any programmer who ever wanted to round a float would have to write it themselves - avoid duplicated code. the overall program becomes shorter if the common elements are extracted into functions. this process is called factoring a program. - easier to test. we've experience this in this class. the last couple homework assignments included several problems in one file. when you have functions, you can test each individual function instead of the whole program at once. this makes it easier to develop larger, more complex programs. this is especially important across teams of engineers. from now on, we'll be writing code in functions, so each computation is isolated and more easy to test. Can anyone think of some computations we’ve done several times in the same function?
  • #5: Parameters are a special term used to describe the variable names between the parenthesis in the function definition. Note that defining a function is separate from calling a function. After you define a function, nothing happens. The series of statements only executes once we call the function.
  • #6: Official docstring documentation: https://www.python.org/dev/peps/pep-0257/
  • #12: The authors of Python wrote the definitions of the functions that we’ve been calling so far in this class. When we call these functions, the code that they wrote will run, processing the arguments that we passed to the function, and then it will return a value for us to use. We can call functions that are written by other people just by understanding what arguments it can receive and what value it can return. Sometimes we can actually look up the code that runs. Check out the code for random.py here: https://github.com/python/cpython/blob/master/Lib/random.py
  • #13: Python Tutor visualization: https://goo.gl/S4QvVo
  • #14: Python Tutor visualization: https://goo.gl/S4QvVo
  • #15: Python Tutor visualization: https://goo.gl/S4QvVo
  • #16: Python Tutor visualization: https://goo.gl/S4QvVo
  • #17: Python Tutor visualization: https://goo.gl/S4QvVo
  • #18: Python Tutor visualization: https://goo.gl/S4QvVo
  • #19: Python Tutor visualization: https://goo.gl/S4QvVo
  • #22: Note that since function body execution stops when the first return statement is encountered, there is no need to use an elif or else statement. Python Tutor visualization: https://goo.gl/mNCpWZ
  • #23: Python Tutor visualization: https://goo.gl/AG1Mqo
  • #25: Python Tutor visualization: https://goo.gl/9QBFga
  • #26: Python Tutor visualization: https://goo.gl/WLUb6d
  • #28: Last class we talked about returning functions. For this class we’ll trace code across multiple functions.
  • #30: hopscotch PythonTutor visualization: https://goo.gl/PVy74W
  • #31: hopscotch PythonTutor visualization: https://goo.gl/foSqTg
  • #32: hopscotch PythonTutor visualization: https://goo.gl/oHEif7
  • #33: 40 20 Python Tutor visualization: https://goo.gl/sF6P2Z
  • #34: Python Tutor visualization: https://goo.gl/FLZhSx
  • #35: See repl.it notes 28 - Lecture - Functions with Lists for more details.
  • #36: PythonTutor visualization: https://goo.gl/NsWAQb See repl.it notes for this lecture more details.
  • #37: [6, 10, 16, 4] PythonTutor visualization: https://goo.gl/ECfwBe
  • #38: ['crab', 'oyster'] Python Tutor visualization: https://goo.gl/y4gMhh Breaking down programs into multiple functions makes it easier to reason about your program. contains_at_least_one_vowel simply accepts a single string and then returns True or False based on whether there is a vowel in the string. get_strings_with_vowels accepts a list of strings and creates a new list containing only the strings from string_list that contains vowels. Without the contains_at_least_one_vowel function, get_strings_with_vowels would be several lines longer and it would be hard to read exactly how the function behaves by looking at the code. It’s also harder to debug a function that does too many things. contains_at_least_one_vowel can also be much more easily unit tested due to its simplicity. This is how all software is made. Functions calling functions calling functions...each layer of code exposes certain functions to the next layer of code which exposes functions to the next layer of code.