1 of 34

CSE 160 Section 3

Functions!

2 of 34

Logistics

  • Coding practice 2 due Sunday Oct 12
  • Written Check In 2 due Friday Oct 10
  • HW1 due Friday Oct 10
    • Submitting on Gradescope
    • Wait for autograder!

3 of 34

Lecture Review: If/ Else Statements

4 of 34

If/ Else Structure

  • Checks that condition is True/False, and executing code based on that condition

is_raining = True

is_sprinkling = False

if is_raining:

print(“Bring an umbrella”)

elif is_sprinkling:

print(“Bring a raincoat”)

else:

print(“Bring sunglasses”)

Output:

Bring an umbrella

5 of 34

Boolean Zen

  • Minimize the use of if statements where possible!
    • More readable
    • Easier to debug

num = 0

def is_num_2(num):

if num == 2:

return True

else:

return False

num = 0

def is_num_2(num):

return num == 2

Without boolean zen:

With boolean zen:

6 of 34

Lecture Review: Nested Loops

7 of 34

Nested Loops

  • A for loop within the body of another for loop

Example:

for i in [0, 1, 2, 3]:

for j in [0, 1, 2]:

print(i)

8 of 34

Nested Loops

  • Nested loop structure
    • Outer loop
    • Inner loop

for i in [0, 1, 2, 3]:

for j in [0, 1, 2]:

print(i)

  • Variable names i and j should be different for clarity

9 of 34

Nested Loops

  • Lets see what this outputs!

Example:

for i in [0, 1, 2, 3]:

for j in [0, 1, 2]:

print(i)

PythonTutor

10 of 34

Lecture Review: Functions

11 of 34

Functions: an overview

  • A function is a block of code which only runs when it is called.
  • You can pass data, known as parameters, into a function.
  • A function can return data as a result (but it doesn’t have to)

12 of 34

Why do we use functions?

  • Don’t Repeat Yourself (DRY)
    • If you’re doing the same thing over and over again, it might be easier to make it into a function
  • Abstractions
    • It’s easier to call a function (like sqrt() or sum()) than writing all the code
    • It’s easier to reason about your program when you break it down into smaller chunks

13 of 34

Function Syntax

# Writing a function

def func_name(parameter1,...):

function body

return value

# To call that function:

func_name(parameter1,...)

def

word needed to define a function

func_name

a name you give the function

parameter1,

a list of parameters you pass in a function. (Optional)

function body

the code inside the function

return

tells the function to return value back to the caller. (Optional)

14 of 34

Functions run only when called

  • What would be the output of this program?

def winter():

x = “Happy Winter!”

print(x)

Output:

def fall():

x = “Happy Fall!”

print(x)

fall()

Output:

Happy Fall!

15 of 34

Functions run only when called

  • What would be the output of this program?

def winter():

x = “Happy Winter!”

print(x)

Output:

def fall():

x = “Happy Fall!”

print(x)

fall()

Output:

Happy Fall!

Include parentheses in function call

16 of 34

Parameters

  • We can pass a function a value to work with, called a “parameter”

def print_twice(x):

print(x)

print(x)

print_twice(“Hi!”)

Output:

Hi!

Hi!

17 of 34

Return Value

This function does have a return value, what will this print?

def two_times_seven():

x = 2 * 7

return x

print(two_times_seven())

Output:

14

18 of 34

Return Value

This function does have a return value, what will this print?

def two_times_seven():

x = 2 * 7

return x

print(two_times_seven())

Output:

14

You must have a return statement if you want your function call to have access to x in two_times_seven()! Otherwise, it will return None

19 of 34

Return vs Print in Functions

Function with a return

Function with a print statement

Output: ?

Can you see the difference?

def add(a, b):

return a + b

def add_print(a, b):

print(a + b)

20 of 34

Function with a Return

Function with a return

def add(a, b):

return a + b

  • When you call add(a, b):
    • Nothing will show up unless you print the result
    • It only returns a value, it doesn't display it.

  • You need to print to see the output:
    • print(add(1,2))

print(add(1,2))

Output:

3

21 of 34

Function with a Print

Function with a print statement

print(add_print(1,2))

Output:

3

None

def add_print(a, b):

print(a + b)

  • On the other hand, add_print(a, b) will immediately print the result when called:
    • add_print(1,2)

  • But it doesn't return anything, so if you try:
    • print(add_print(1,2))
    • Gives you None because it does not return anything

22 of 34

Docstrings

  • You should comment your functions so others (and yourself) can understand what they do without having to read through the code. You should include:
    • What are the inputs? What types should they be?
    • What does it do (does it print something?)
    • What does it return?

def abs(x):

‘’’Takes in a number (x), and returns its absolute value’’’

if x < 0:

return x * -1

else:

return x

23 of 34

Mod Operator Overview

24 of 34

Mod

Modulo operator, denoted as %, is a mathematical operation that calculates the remainder when one number is divided by another.

  • 2 % 5

  • 3 % 7

  • 5 % 2

  • 8 % 3

  • 20 % 5

25 of 34

Mod

  • 2 % 5 = 2

  • 3 % 7 = 3

  • 5 % 2 = 1

  • 8 % 3 = 2

  • 20 % 5 = 0

26 of 34

Mod

What is the output of the following code?

for i in range(5):

print(i % 3)

27 of 34

Mod

What is the output of the following code?

for i in range(5):

print(i % 3)

Answer:

0

1

2

0

1

28 of 34

Section Handout Problems

29 of 34

Problem 1

Write a function avg_age(ages) that calculates and returns the average of a list of ages. You are not allowed to use Python’s built in sum() function. Your function should take the list ages as a parameter and return the average. For example, given ages = [20, 21, 22], avg_age(ages) should return 21.

30 of 34

Problem 2

Given a list of students’ names (student_lst), write a function max_height(student_lst) that returns the maximum height in inches. Assume a function get_height(student) is given to you, and will return the height (in inches) of any student when given a student name.

For example: get_height(“Nicholas”) will return 75.

a) Implement the function max_height(student_lst)

b) What is the return type of max_height(student_lst)?

c) Suppose you printed the max height instead of returning it. What would be the return

type of max_height(student_lst)

PythonTutor

31 of 34

Problem 5

Write a function called among_us(crewmates, imposter), where given a list of crewmates and the names of an imposter, returns True if the name of that imposter is in the list of crewmates. Do not use the Python keyword “in” unless it is part of the for-loop. For example, among_us([“cyan”, “yellow”, “pink”], “pink”) returns True.

PythonTutor

32 of 34

Additional Problems

33 of 34

Problem 3

Write a function count_letters(word_list, target) that counts the number of times a target letter appears in a list of strings and returns it. For example, given word_list = [“this”, “is”, “a”, “list”] and target = “s”, count_letters(word_list, target) should return 3.

PythonTutor

34 of 34

Problem 4

Write a function called budget_saver(cost, budget) that takes the price of a product and a budget. The function should return “too expensive” if the price is more than the budget, “great deal” if the price is less than the budget, and “okay” if the cost and budget are equal.

For example, budget_saver(250, 100) returns “too expensive”.

Python Tutor