Functions#
Q&A
Q: is there an order of operations for % and //?
A: They are treated equal to division
Q: What is the difference between False and Error?
A: False is what Python would return if the code ran. Error is what python would display if the code could not run. For example, if indentation is incorrect, you’ll get an error - python can’t interpret it. However, if you ran the code10 > 20
, python knows what to do there…it will execute, it just happens to beFalse
.
Q: Does the operator replace the assignment symbol (=)? Like should I put: sword_charge = 90 <= OR sword_charge <= 90
A: No. The comparison operator does not replace the assignment oeprator.
Q: Will we need to know about identity and chaining operators?
A: No on identity operators. Chaining operators is what we started to do by combining different operators into a single statement….so yes, but not the arbitrary examples demonstrated in the book….just that it is conceptually possible to combine them.
Q: For “and” statements when the left side is True and the right side is False [as in print(“hi”) and False], why is the left hand side still returned? Why aren’t they both False because of the “and” operator?
A: Ah…so anytime python encountersprint()
python is going to print the output (thus why you see hi printed). However…if you remove theFalse
.
Q: Is everything on the textbook going to be things we need to know for exams?
A: Not necessarily. The videos - those are all fair game. However, if something is in the textbook and we never do any practice problems on it or discuss it in class (i.e. identity operators), you will not be tested on it during an exam. Everything on the exam will be things you did at least one practice problem on (and typically many practice problems).
Q: how do you type out a modulus operator/ how do I get it?
A: Shift + 5 on your keyboard
Q: Im still confused if the placement of the true matters in an or operator
A: It does not. If either the left OR the right side isTrue
, it will evaluate asTrue
.
Course Announcements
Due This Week:
CL1 due Friday
Pre-course assessments (two surveys) due Sunday
Notes:
PrairieLearn vs PrairieTest
PrairieLearn: system where you complete quizzes, labs, assignments, etc.
PrairieTest: where you sign up for exams; link now on Canvas homepage (practice exam reminder)
Course Website vs. Textbook
Course website: lecture notes, schedule, and links to textbook/prairielearn
Course textbook: for pre-class reading/videos (and additional practice)
Oral Exams: sign up for first oral exam (during lab; sign up for one slot during weeks 3-6; link also on Canvas homepage)
Discuss Gemini in Colab
Functions#
defining a function
def
return
default values
keyword vs. positional arguments
executing a function
parameters
Vocab#
Define/create/make a function: To set up and write the instructions for a function.
Execute/call/use a function: To actually use the pre-defined function.
Input/parameter/argument: A variable defined by the user that is put/passed in between the parantheses
()
that comes after the function name.Output: The variable that is
return
ed to the user after the function is executed.
Functions#
Modular Programming#
Copy + Pasting the same/similar bit of code is to be avoided.
Functions are one way to avoid this.
Loops are another! (we’ll get to these soon…)
Functions for Modular Programming#
Functions allow us to flexibly re-use pieces of code
Each function is independent of every other function, and other pieces of code
Functions are the building blocks of programs, and can be flexibly combined and executed in specified orders
This allows us to build up arbitrarily complex, well-organized programs
# you've seen functions before
# here we use the type() function
my_var = 3
type(my_var)
# the function print() doesn't depend on type()
# but they can both be used on the same variable
print(my_var)
Function Example I#
When you use def
, you are defining a function.
You are metaphorically writing the instructions for how to make the cheeseburger.
# define a function: double_value
# Notice that the parameter `num` is not explicitly defined with an =
# This is because it will be defined later by the user when they execute the function.
def double_value(num):
# do some operation
doubled = num + num
# return output from function
return doubled
# excecute a function by calling the function's name
# and defining the parameter within the parentheses
double_value(num=2)
# equivalent function call
# Here the parameter `num` is defined without
# explicitly specifying the name of the parameter
double_value(2)
Function Properties#
Functions are defined using
def
followed by the name of the function, parentheses()
, parameters within the parentheses, and then:
after the parentheses, which opens a code-block that comprises the functionRunning code with a
def
block defines the function (but does not execute it)
Functions are executed with the name of the function and parentheses -
()
withoutdef
and:
This is when the code inside a function is actually run
Inside a function, there is code that performs operations on the available variables
Functions use the special operator
return
to exit the function, passing out any specified variables
When you use a function, you can assign the output (whatever is
return
ed) to a variable
Activity: Functions I#
Complete the questions in this Google Form (https://forms.gle/MfiKe5gPW9AeZ1PP6) and then click submit.
How would the following code evaluate?
def remainder(number, divider=2):
r = number % divider
return r
ans_1 = remainder(12, 5)
ans_2 = remainder(2, 2)
print(ans_1 + ans_2)
Write a function
greet
that takes the parametername
. Inside the function, concatenate ‘Hello’, the person’s name, and ‘Good Day!”. Assign this tooutput
and returnoutput
. Paste your code below.
## YOUR CODE HERE
def greet(name):
output = 'Hello ' + name + '. Good Day!'
return output
def greet(name):
output = 'Hello ' + 'name' + '. Good Day!'
return output
## TEST YOUR CODE HERE
greet('COGS 18 Students')
Let’s also discuss how you may use ChatGPT for this question…
Q&A
Q: Am I able to get help with other coding questions in ED not related to COGS18 specifically?
A: You can definitely ask. We won’t prioritize these…so may take a bit longer to get a response, but we’ll do our best!
Q: how long do functions remain define or ‘effective” for in a notebook?
A: Only so long as that notebook is open. Once the notebook is closed, the next time you open it you would need to re-run the code where the function is defined before being able to use it. We’ll soon learn about creating modules to avoid this issue…so we can easily “import” functions into notebooks for use…without having to define them in the notebook where we use them. But, that’s a few weeks out.
Q: Does spacing matter, because I would write the function and it still would not not run?
A: Yes! Specifically, indentation matters. Spacing between lines is allowed but not required.
Q: In the example from activity 1, how come we had to define name=’Shannon’ instead of using just ‘Shannon’? I remember being able to put 6 instead of num=6 in other functions.
A: This has to do with the operations being carried out inside the function. In the function I was trying to concatenate strings…so the input had to be a string. In the other functions we were carrying out mathematical operations, so they could be integers.
Q: Once the function is run and the value is returned to some output variable, does that output variable keep that value until the function is used again with some other output?
A: That variable will keep the value until another value is assigned to it. So, if you hadoutput_1 = my_function(5)
and thenoutput_2 = my_function(2)
…output_1 and output_2 would each have different values. If you then said output_1 = ‘Shannon’…well, then you would store the string ‘Shannon’ inoutput_1
Q: How do you know what to name the function?
A: Well, often in this class, I’ll tell you what to name the function. But, on your own, the best function names are verbs (action words) that summarize what the function accomplishes.
Q: What does the type function do that the print function does not?
A:type
tells you the type of the variable;
Q: What is the difference between return and print? I am kind of confused 🫠
A:return
is a special keyword for use inside a function definition. If you want to get output from a function, usereturn
.
Q: Is there anywhere we can get simple functions to practice reading/interpreting before the oral quiz?
A: The functions from the notes (i.e.double_value
), Google Forms (i.e.greet
,convert_to_f
) and first assignment (the calculator questions) are a few good examples! to help practice. We’ll also do an activity today in class.
Q: How can I practice reading and understanding code?
A: A good way is to work through examples used in class. Then, you could use ChatGPT, provide those examples and ask it to provide similar examples (for example, functions using only variables and operators) but without any explanation as to what they do so you can think about them…and then you could ask it to explain to make sure your understanding matched.
Course Announcements
Due this week:
VQ5 due Wed (is now available)
CL2 due Fri
A1 due Sun
Notes:
Sign up for written exams (prairietest) and oral exams (taken in lab)
For oral (and written) exams, please treat like other exams…don’t discuss with those who haven’t yet taken it
Pre-course assessment surveys are open for one more day. Please complete TODAY if you haven’t already.
Activity: Functions II#
Now that we worked through that first example together…complete the question in this Google Form (https://forms.gle/uJTMjnv8zDSBMJJC7) and then click submit.
Write a function
convert_to_f
that will convert a temperature in Celsius to Fahrenheit, returning the temperature in Fahrenheit.
Note: A temperature in Celsius will be multiplied by 9/5 and then 32 will be added to that quantity to convert to Fahrenheit.
## YOUR CODE HERE
def convert_to_f(temp_c):
temp_f = temp_c * 9/5 + 32
return temp_f
20 * 9/5 + 32
68.0
## TEST YOUR CODE HERE
convert_to_f(temp_c=10)
50.0
Default Values#
# Create a function, that has a default values for a parameter
def exponentiate(number, exponent=2):
return number ** exponent
# Use the function, using default value
exponentiate(3)
9
# Call the function, over-riding default value with something else
# python assumes values are in order of parameters specified in definition
exponentiate(2, 3)
8
# you can always state this explicitly
exponentiate(number=2, exponent=3)
8
Positional vs. Keyword Arguments#
# Positional arguments use the position to infer which argument each value relates to
exponentiate(2, 3)
# Keyword arguments are explicitly named as to which argument each value relates to
exponentiate(number=2, exponent=3)
# DON'T DO THIS; IT CONFUSES US HUMANS
exponentiate(exponent=3, number=2)
8
# Note: once you have a keyword argument, you can't have other positional arguments afterwards
# this cell will produce an error
exponentiate(number=2, 3)
Cell In[13], line 3
exponentiate(number=2, 3)
^
SyntaxError: positional argument follows keyword argument
Code Style: Functions#
Function names should be snake_case
Function names should describe task accomplished by function
Separate out logical sections within a function with new lines
Arguments should be separated by a comma and a space
Default values do NOT need a space around the
=
Functions: Good Code Style#
def remainder(number, divider=2):
r = number % divider
return r
Functions: Code Style to Avoid#
# could be improved by adding empty lines to separate out logical chunks
def remainder(number,divider=2): # needs space after comma
r=number%divider # needs spacing around operators
return r
Activity: Functions III (Code Describing - Paired)#
Pair up with one other individual.
Decide who will be Person A and who will be Person B
On your own, read through the code provided, thinking about what it’s accomplishing.
For each person: without letting your partner see the code AND without describing the code word for word, explain what the code accomplishes and the logic within the code.
Have the other person try to write code that accomplishes what the other partner described. Test out the code if you have enough time.
Discuss similarities/differences in the code described and the code written and any misunderstandings that you had in this process.
## YOUR CODE HERE
def introduce_self(name, year, major):
out_string = 'Hi, my name is ' + name + '. I am a ' + year + ' studying ' + major + '.'
return out_string
## TEST YOUR CODE HERE
# positional arguments
introduce_self('Shannon', '25th year', 'cogsci')
# keyword arguments
introduce_self(name='Shannon', year='25th year', major='cogsci')
'Hi, my name is Shannon. I am a 25th year studying cogsci.'
def is_even(num):
even = num % 2 == 0
return even
# positional argument
is_even(11)
# keyword argument
is_even(num=7)
False
Summary#
how to define a function
how to execute a function
default values
position vs. keyword arguments
code style