# Lecture 9

## Functions

MCS 260 Fall 2021
Emily Dumas

## Reminders

• Project 1!
• Due Friday 6pm
• Submissions open now
• Autograder enforces project description strictly; use its report to fix minor formatting issues
• Worksheet 4 coming today

We have seen lots of functions: $\texttt{input()}$, $\texttt{print()}$, $\texttt{float()}$, $\texttt{len()}$, $\texttt{enumerate()}$, ...

These are built-in functions, provided by Python. They do useful things, sometimes using data you provide, and sometimes returning a value.

It is also possible to create your own functions.

Syntax for a function definition:


def function_name(param0, param1, ...):
statement
...
statement
return value


The $\texttt{param}i$ are parameters.

Syntax for calling a function:


function_name(arg0, arg1, ...)


The $\texttt{arg}i$ are arguments. The statements in the function body will run with $\texttt{param0=arg0}$, $\texttt{param1=arg1}$, ....

## String methods


s = "Chapter 11"
print(s.lower())   # chapter 11
print(s.upper())   # CHAPTER 11


(We'll discuss more of these soon.)

Example: Write a function input_yes_no() that is like input() but only accepts yes or no.

Make it flexible enough to accept yes, no, y, n, with any capitalization.

Regardless of how user enters their answer, the return value should be either "yes" or "no".


def input_yes_no():
while True:
s = input()    # Read string from keyboard
s = s.lower()  # Make all lower case
if s in ["y","yes"]:
s = "yes"
break
elif s in ["n","no"]:
s = "no"
break
else:
return s


Now we can use this e.g. as:


print("Set all quiz scores to 100?")
if input_yes_no() == "yes":
for i,student in enumerate(roster):
scores[i] = 100.0


A return is not required; a function can perform tasks without returning a value.

A return can appear anywhere in the function body to return to the caller immediately.


def input_yes_no2():
"""
Read yes/no from keyboard, allowing single letter or full
word answers.  Returns one of the strings "yes" or "no".
"""
while True:
s = input()    # Read string from keyboard
s = s.lower()  # Make all lower case
if s in ["y","yes"]:
return "yes"
elif s in ["n","no"]:
return "no"
else:


## Parameters

Parameters allow a function to accept and use data. The syntax is a list of names in parentheses after the function name. Example:


def trim(s, maxlen):
"""Return the initial segment of sequence s,
consisting of at most maxlen items."""
return s[:maxlen]  # Works even if s is short!


Now if we call $\texttt{trim("picnic",3)}$, the body of the function runs with $\texttt{s="picnic"}$ and $\texttt{maxlen=3}$.

These are called positional arguments, as they correspond to parameters by position.

Parameters can be given default values:


"Return the sum of x and addon (defaults to 5)"


When calling a function, arguments can be given positionally, or by name. The latter are keyword arguments.


increase(3)           # result is 8
increase(addon=2,11)  # ERROR: pos. args must be first
increase(addon=2)     # ERROR: arg without default omitted


### Acknowledgement

• Some of today's lecture was based on teaching materials developed for MCS 260 by Jan Verschelde.

### Revision history

• 2021-09-13 Initial publication
• 2021-09-14 Moved unused slides forward to Lecture 10