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. So False (the boolean) and 'False' the string are both valid as values for a variable. However, the boolean False cannot 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: With type()

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!

Image includes a snake at top left with upper snake coming out of its mouth (all caps with underscores between words), a kebab showing kebab-case in the middle, a snake showing snake_case at bottom left, and a camel at right demonstrating camelCase

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)

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 returned to the user after the function is executed.

Functions#

A function is a re-usable piece of code that performs operations on a specified set of variables, and returns the result.

cheeseburger

Modular Programming#

Modular programming is an approach to programming that focuses on building programs from independent modules ('pieces').

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 function

    • Running code with a def block defines the function (but does not execute it)

  • Functions are executed with the name of the function and parentheses - () without def 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 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=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 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 
## TEST YOUR CODE HERE

Let’s also discuss how you may use ChatGPT for this question…

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_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 FUNCTION HERE 
## EXECUTE HERE

Default Values#

Function parameters can also take default values. This makes some parameters optional, as they take a default value if not otherwise specified.
# 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)
# Call the function, over-riding default value with something else
# python assumes values are in order of parameters specified in definition
exponentiate(2, 3)
# you can always state this explicitly
exponentiate(number=2, exponent=3)

Positional vs. Keyword Arguments#

Arguments to a function can be indicated by either position or keyword.
# 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)
# 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)

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

  1. Pair up with one other individual.

  2. Decide who will be Person A and who will be Person B

  3. Open up the correct Google Form: Person A; Person B

  4. On your own, read through the code provided, thinking about what it’s accomplishing.

  5. 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.

  6. Have the other person try to write code that accomplishes what the other partner described. Test out the code if you have enough time.

  7. Discuss similarities/differences in the code described and the code written and any misunderstandings that you had in this process.

## YOUR FUNCTION HERE
## EXECUTE YOUR FUNCTION HERE

Summary#

  • how to define a function

  • how to execute a function

  • default values

  • position vs. keyword arguments

  • code style