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

PPTX
Function in c
PDF
Chapter 1. Functions in C++.pdf
PDF
Chapter_1.__Functions_in_C++[1].pdf
PPTX
PPTX
Functions in Python Programming Language
PPT
functions _
PPTX
Functionincprogram
PPTX
Python Lecture 4
Function in c
Chapter 1. Functions in C++.pdf
Chapter_1.__Functions_in_C++[1].pdf
Functions in Python Programming Language
functions _
Functionincprogram
Python Lecture 4

Similar to Understanding Python Programming Language -Functions (20)

PPT
function_v1fgdfdf5645ythyth6ythythgbg.ppt
PPT
function_v1.ppt
PPT
function_v1.ppt
PPTX
Python programing
PPT
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
PPTX
made it easy: python quick reference for beginners
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPTX
functioninpython-1.pptx
PPTX
C function
PPT
Powerpoint presentation for Python Functions
PPT
functions modules and exceptions handlings.ppt
PPTX
Classes function overloading
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
DOC
Functions
PPTX
JNTUK python programming python unit 3.pptx
PPTX
Python_Unit-1_PPT_Data Types.pptx
PDF
Functions in C++.pdf
PPTX
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
PDF
functionfunctionfunctionfunctionfunction12.pdf
PDF
functionfunctionfunctionfunctionfunction12.pdf
function_v1fgdfdf5645ythyth6ythythgbg.ppt
function_v1.ppt
function_v1.ppt
Python programing
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
made it easy: python quick reference for beginners
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
functioninpython-1.pptx
C function
Powerpoint presentation for Python Functions
functions modules and exceptions handlings.ppt
Classes function overloading
04. WORKING WITH FUNCTIONS-2 (1).pptx
Functions
JNTUK python programming python unit 3.pptx
Python_Unit-1_PPT_Data Types.pptx
Functions in C++.pdf
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
Ad

Recently uploaded (20)

PPTX
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
PPTX
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PDF
Mega Projects Data Mega Projects Data
PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
PDF
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPTX
Database Infoormation System (DBIS).pptx
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PDF
annual-report-2024-2025 original latest.
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PPTX
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
PDF
Clinical guidelines as a resource for EBP(1).pdf
PPTX
Business Ppt On Nestle.pptx huunnnhhgfvu
PPT
Miokarditis (Inflamasi pada Otot Jantung)
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
PPTX
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
PPTX
oil_refinery_comprehensive_20250804084928 (1).pptx
PPT
ISS -ESG Data flows What is ESG and HowHow
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
Mega Projects Data Mega Projects Data
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
IBA_Chapter_11_Slides_Final_Accessible.pptx
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
Galatica Smart Energy Infrastructure Startup Pitch Deck
Database Infoormation System (DBIS).pptx
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
annual-report-2024-2025 original latest.
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
Clinical guidelines as a resource for EBP(1).pdf
Business Ppt On Nestle.pptx huunnnhhgfvu
Miokarditis (Inflamasi pada Otot Jantung)
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
oil_refinery_comprehensive_20250804084928 (1).pptx
ISS -ESG Data flows What is ESG and HowHow
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.