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))
Ad

Recommended

Function in c
Function in c
Raj Tandukar
 
Chapter 1. Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
Function in c
Function in c
CGC Technical campus,Mohali
 
functions _
functions _
SwatiHans10
 
Functionincprogram
Functionincprogram
Sampath Kumar
 
Python Lecture 4
Python Lecture 4
Inzamam Baig
 
function_v1fgdfdf5645ythyth6ythythgbg.ppt
function_v1fgdfdf5645ythyth6ythythgbg.ppt
RoselinLourd
 
function_v1.ppt
function_v1.ppt
ssuser823678
 
function_v1.ppt
function_v1.ppt
ssuser2076d9
 
Python programing
Python programing
hamzagame
 
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
RoselinLourd
 
made it easy: python quick reference for beginners
made it easy: python quick reference for beginners
SumanMadan4
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
functioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
C function
C function
thirumalaikumar3
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Classes function overloading
Classes function overloading
ankush_kumar
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
Functions
Functions
zeeshan841
 
JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
Functions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
Power BI API Connectors - Best Practices for Scalable Data Connections
Power BI API Connectors - Best Practices for Scalable Data Connections
Vidicorp Ltd
 
Section Three - Project colemanite production China
Section Three - Project colemanite production China
VavaniaM
 

More Related Content

Similar to Understanding Python Programming Language -Functions (20)

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

Recently uploaded (20)

Power BI API Connectors - Best Practices for Scalable Data Connections
Power BI API Connectors - Best Practices for Scalable Data Connections
Vidicorp Ltd
 
Section Three - Project colemanite production China
Section Three - Project colemanite production China
VavaniaM
 
最新版美国威斯康星大学拉克罗斯分校毕业证(UW–L毕业证书)原版定制
最新版美国威斯康星大学拉克罗斯分校毕业证(UW–L毕业证书)原版定制
Taqyea
 
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
payalmistryb
 
Untitled presentation xcvxcvxcvxcvx.pptx
Untitled presentation xcvxcvxcvxcvx.pptx
jonathan4241
 
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
bhavaniteacher99
 
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
OlhaTatokhina1
 
REGRESSION DIAGNOSTIC I: MULTICOLLINEARITY
REGRESSION DIAGNOSTIC I: MULTICOLLINEARITY
Ameya Patekar
 
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays
 
Attendance Presentation Project Excel.pptx
Attendance Presentation Project Excel.pptx
s2025266191
 
What is FinOps as a Service and why is it Trending?
What is FinOps as a Service and why is it Trending?
Amnic
 
Measurecamp Copenhagen - Consent Context
Measurecamp Copenhagen - Consent Context
Human37
 
Data Warehousing and Analytics IFI Techsolutions .pptx
Data Warehousing and Analytics IFI Techsolutions .pptx
IFI Techsolutions
 
最新版西班牙莱里达大学毕业证(UdL毕业证书)原版定制
最新版西班牙莱里达大学毕业证(UdL毕业证书)原版定制
Taqyea
 
Verweven van EM Legacy en OTL-data bij AWV
Verweven van EM Legacy en OTL-data bij AWV
jacoba18
 
Hypothesis Testing Training Material.pdf
Hypothesis Testing Training Material.pdf
AbdirahmanAli51
 
unit- 5 Biostatistics and Research Methodology.pdf
unit- 5 Biostatistics and Research Methodology.pdf
KRUTIKA CHANNE
 
Managed Cloud services - Opsio Cloud Man
Managed Cloud services - Opsio Cloud Man
Opsio Cloud
 
FME Beyond Data Processing: Creating a Dartboard Accuracy App
FME Beyond Data Processing: Creating a Dartboard Accuracy App
jacoba18
 
apidays New York 2025 - The Future of Small Business Lending with Open Bankin...
apidays New York 2025 - The Future of Small Business Lending with Open Bankin...
apidays
 
Power BI API Connectors - Best Practices for Scalable Data Connections
Power BI API Connectors - Best Practices for Scalable Data Connections
Vidicorp Ltd
 
Section Three - Project colemanite production China
Section Three - Project colemanite production China
VavaniaM
 
最新版美国威斯康星大学拉克罗斯分校毕业证(UW–L毕业证书)原版定制
最新版美国威斯康星大学拉克罗斯分校毕业证(UW–L毕业证书)原版定制
Taqyea
 
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
payalmistryb
 
Untitled presentation xcvxcvxcvxcvx.pptx
Untitled presentation xcvxcvxcvxcvx.pptx
jonathan4241
 
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
bhavaniteacher99
 
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
MEDIA_LITERACY_INDEX_OF_EDUCATORS_ENG.pdf
OlhaTatokhina1
 
REGRESSION DIAGNOSTIC I: MULTICOLLINEARITY
REGRESSION DIAGNOSTIC I: MULTICOLLINEARITY
Ameya Patekar
 
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays Singapore 2025 - What exactly are AI Agents by Aki Ranin (Earthshots ...
apidays
 
Attendance Presentation Project Excel.pptx
Attendance Presentation Project Excel.pptx
s2025266191
 
What is FinOps as a Service and why is it Trending?
What is FinOps as a Service and why is it Trending?
Amnic
 
Measurecamp Copenhagen - Consent Context
Measurecamp Copenhagen - Consent Context
Human37
 
Data Warehousing and Analytics IFI Techsolutions .pptx
Data Warehousing and Analytics IFI Techsolutions .pptx
IFI Techsolutions
 
最新版西班牙莱里达大学毕业证(UdL毕业证书)原版定制
最新版西班牙莱里达大学毕业证(UdL毕业证书)原版定制
Taqyea
 
Verweven van EM Legacy en OTL-data bij AWV
Verweven van EM Legacy en OTL-data bij AWV
jacoba18
 
Hypothesis Testing Training Material.pdf
Hypothesis Testing Training Material.pdf
AbdirahmanAli51
 
unit- 5 Biostatistics and Research Methodology.pdf
unit- 5 Biostatistics and Research Methodology.pdf
KRUTIKA CHANNE
 
Managed Cloud services - Opsio Cloud Man
Managed Cloud services - Opsio Cloud Man
Opsio Cloud
 
FME Beyond Data Processing: Creating a Dartboard Accuracy App
FME Beyond Data Processing: Creating a Dartboard Accuracy App
jacoba18
 
apidays New York 2025 - The Future of Small Business Lending with Open Bankin...
apidays New York 2025 - The Future of Small Business Lending with Open Bankin...
apidays
 
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.