Q&A
Q: how does snake_case look like a snake? I don’t see it…
A: It may help to know that there’s also camelCase, kebab-case, CapWords (or PascalCase). See image below!
Q: if like ‘False’ is condered a string, wouldnt be this a reserved word? so it would be an error?
A: So “reserved words” have to do with varaible names NOT their values. SoFalse(the boolean) and'False'the string are both valid as values for a variable. However, the booleanFalsecannot be used as a variable name.
Q: Is
'Python'the string or"\'Python'\"?
A: Both are valid strings. The first is a string containing the word Python. The second is a string containing the word Python with quotes around it as part of the string. That’s what the backslashes (escape characters) allow for - to include literal quotation marks in the string.
Q: What is the difference between mutable and immutable?
A: Immutable variables cannot have part of the value changed after defined. Mutable can. (we’ll talk about those soon!)
Q: is there a preference for readability between ‘ and “? I prefer “ just due to it being a little more obvious and typical writing, but idk if ‘ is preferred (bc it’s probably faster to type)
A: There’s no specified preference. My general guidance is pick one and stick with it (however, I am personally terrible at taking this advice. I use both willy nilly with no consistency. Don’t be like me.)
Q: Why won’t you teach us to color fonts, and change sizes :C
A: I’m going to make a Piazza post on this soon. I’m just not going to take class time for it…b/c it’s not actually Python :)
Q: do you accept late work?
A: Yes, for a penalty. Labs up to 2d. Assignments up to 4d. I also am always open to discussing an extension.
Q: What is the purpose of Boolean logic? I understand what it is and how it works, but I’m not sure how it’s useful or when and what context it would appear in
A: We’re going to see this in more meaningful examples very soon, namely in functions!
Q: Do strings have to store multiple words at once in the quotation marks or can it just be one word as long as its a character?
A: It can store multiple words at once.
Q: is anything in quotes a string?
A: Yup!
Q: Im still a bit lost on what code style means.
A: Code style refers to the appearance of your code. Good code style makes your code easier for humans to read, but doesn’t actually affect how the code runs.
Q: How do we check if something is an integer, float, boolean, string again?
A: Withtype()
Q: what happens when we want to compare a value that changes overtime depending on our code, and can be best defined by a variable. Like in our example above, what if the amount of charge we have changes overtime and can be unlimited, but must be above 90 to be work. How would we compare it?
A: Excellent question! With a function - today’s topic!

Source: https://allisonhorst.com/everything-else
Functions#
Course Announcements
Due Dates:
CL1 due Friday
VQ4 due Mon
VQ5 due Wed
Reminders:
Sign up for Piazza for Q&A (For important course announcements, I use Canvas)
Pre-course Survey Summary (N=688) NOTE: This is not in your notes b/c I just added it right before class
72% have never programmed before
80% not confident in any course objectives
73% anxious for the course
Future:
Psychologist/Therapist (18%), Doctor/PA/Nurse (14%), Researcher/Scientist (7%), Creative/Artist (7%),
~11% gave non-career response (happy, rich, employed)
Hobbies:
hang out with friends/family (24%), sports (23%), beach/outdoors/hiking (22%), reading (16%), music (15%), art/drawing (15%), gym/working out (14%), baking/cooking (13%)
more unique, but N>=2: Crochet/knitting, crafting, journaling, sweing, photography, puzzles, running a startup, ceramics/pottery, henna, politics, water polo, fencing, figure skating, flower arranging, rollerskaing, karaoke
Functions#
defining a function
defreturndefault 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
returned 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)
int
# the function print() doesn't depend on type()
# but they can both be used on the same variable
print(my_var)
3
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)
4
# equivalent function call
# Here the parameter `num` is defined without
# explicitly specifying the name of the parameter
double_value(2)
4
Function Properties#
Functions are defined using
deffollowed 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
defblock defines the function (but does not execute it)
Functions are executed with the name of the function and parentheses -
()withoutdefand: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
returnto exit the function, passing out any specified variables
When you use a function, you can assign the output (whatever is
returned) to a variable
Activity: Functions I#
Complete the questions in this Google Form (https://forms.gle/bMJf3eejmsoYmwrz7) and then click submit.
How would the following code evaluate?
def remainder(number, divider):
r = number % divider
return r
ans_1 = remainder(12, 5)
ans_2 = remainder(2, 2)
print(ans_1 + ans_2)
Write a function
greetthat takes the parametername. Inside the function, concatenate ‘Hello’, the person’s name, and ‘Good Day!”. Assign this tooutputand returnoutput. Paste your code below.
def remainder(number, divider):
r = number % divider
return r
ans_1 = remainder(12, 5)
ans_2 = remainder(2, 2)
print(ans_1 + ans_2)
2
# explaining what we're doing when assigning
# output from function to a variable
# copied from above
ans_1 = remainder(12, 5)
print(ans_1)
2
Write a function greet that takes the parameter name. Inside the function, concatenate ‘Hello’, the person’s name, and ‘Good Day!’. Assign this to output and return output. Paste your code below.
## YOUR FUNCTION HERE
def greet(name):
output = 'Hello ' + name + ' Good Day!'
return output
# can test in same cell
# must not be indented inside the function definition
greet('Shannon')
'Hello Shannon Good Day!'
# can include a "number"; must be as a string
greet("3")
'Hello 3 Good Day!'
# if you do not specify a string (no quotes)
# python assumes there is a variable called Students
# and tries to add its value
greet(Students)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[12], line 4
1 # if you do not specify a string (no quotes)
2 # python assumes there is a variable called Students
3 # and tries to add its value
----> 4 greet(Students)
NameError: name 'Students' is not defined
# pick either single or double quotes
# be consistent (unlike me)
greet(name="Students")
'Hello Students Good Day!'
# single and double quotes are the same
greet(name='Students')
'Hello Students Good Day!'
# ideal to test with multiple values
greet("Kayden")
'Hello Kayden Good Day!'
Common Student Errors:
Hard-coding names inside function rather than using parameter
Including string literal
'name'(rather than using variable)
What to be clear on:
how a parameter is used/referenced within a function
the difference between a variable and a value
difference between defining and exeucting (actually using) a function
# Hard-coding names inside function rather than using parameter
def greet(name):
# name = 'Shannon' # example of hard-coding; will always use 'Shannon' if this code is not commented out
output = 'Hello ' + name + ' Good Day!'
return output
greet('COGS 18 Students')
'Hello Shannon Good Day!'
#Including string literal 'name' (rather than using variable)
def greet(name):
output = 'Hello ' + 'name' + ' Good Day!'
return output
greet('Shannon')
'Hello name Good Day!'
Let’s also discuss how you may use ChatGPT for this question…
if you have code but it has a bug; can ask ChatGPT to explain the bug while specifying not to fix it
if you get code that works but you don’t fully understand why, can ask for an explanation of parts or all of the code

Course Announcements
Due Dates:
VQ5 due Wed
CL2 due Friday
A1 due Sunday
Note:
Canvas-PrairieLearn Grades Syncing
My Wed OH are remote this week only (Canvas updated)
Activity: Functions II#
Now that we worked through that first example together…complete the question in this Google Form (https://forms.gle/CQ4JqmSY5MRrmSH88) and then click submit.
Write a function
convert_to_fthat 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 FUNCTION HERE
def convert_to_f(temp_c):
temp_f = temp_c * 9/5 + 32
return temp_f
## EXECUTE HERE
convert_to_f(20)
68.0
20 * 9/5 + 32
68.0
convert_to_f(40)
104.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
# if you wanted to only be able to raise to the power 2
def exponentiate(number):
return number ** 2
def exponentiate(number):
exponent = 2
return number ** exponent
# what if...you include exponent and then define exponent inside the function
# DON'T EVER DO THIS; IF YOU HAVE A PARAMETER, DON'T REDEFINE IT INSIDE YOUR FUNCTION
# IT WILL OVERWRITE THE PARAMETER AND ALWAYS USE THE VALUE DEFINED INSIDE THE FUNCTION
def exponentiate(number, exponent):
exponent = 2
return number ** exponent
exponentiate(3, 1000)
9
Positional vs. Keyword Arguments#
# Positional arguments use the position to infer which argument each value relates to
exponentiate(2, 3)
8
# Keyword arguments are explicitly named as to which argument each value relates to
exponentiate(number=2, exponent=3)
8
# 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[37], 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 FUNCTION HERE
def introduce_self(name, year, major):
out_string = 'Hi, my name is ' + name + '. I am a ' + year + ' studying ' + major + '.'
return out_string
## EXECUTE YOUR FUNCTION HERE
# positional arguments
introduce_self('Shannon', 'senior', 'Cognitive Science')
'Hi, my name is Shannon. I am a senior studying Cognitive Science.'
# keyword arguments
introduce_self(name='Shannon', year='senior', major='Cognitive Science')
'Hi, my name is Shannon. I am a senior studying Cognitive Science.'
def is_even(num):
even = num % 2 == 0
return even
6 % 2
0
0 == 0
True
100 % 2
0
5 % 2
1
1 == 0
False
#positional
is_even(6)
True
#keyword
is_even(num=6)
True
# what if function to determine if a number is odd?
def is_odd(num):
# sometimes works (consider negative) >=; >=1;
# will work for all nums: !=
odd = num % 2 != 0
return odd
Summary#
how to define a function
how to execute a function
default values
position vs. keyword arguments
code style