L4 Functions SP20 - University Of Illinois · Lecture 4: Functions Craig Zilles (Computer Science)...

Preview:

Citation preview

Lecture 4: Functions

Craig Zilles (Computer Science)

February 16, 2020

https://go.illinois.edu/cs105fa19

CS 105

Are you sitting next to someone to talk to for the clicker

questions?

Today I'm using: pythontutor.com

2

Big Picture (Muddiest Points)

• if the challenge questions are too hard can we leave some of it?

• In general, I'd say that there is no single concept that confuses me most as of right now. I kind of understand why I need to do what I need to do in coding, but I am still foggy as to where each and every little character goes, and what makes something a syntax error and what doesn't.

3

Today1. Warmup

• Negative indices2. Functions

• Indentation / Code Blocks• Parameters and Arguments• Return Values & None

3. Functions in Excel

4. Next week's reading: Booleans & Conditionals

4

Negative Indexing

What is the value of the above expression?

A) 'a'B) 'b'C) 'c'D) 'd'E) 'e'

5

"abcde"[-2]

Sets• When to use:

• You have a collection of similar things• You want to know if something is in the set or not• You want to do set operations (e.g., intersection)

• Finding birthdays shared by two or more people in the class

6

Dictionaries• A mapping type: given a piece of info, find related info

• Key-Value pairs• Keys must be unique, values can be repeated

• What is it used for?• UIN -> student record• Cell phone number -> cell tower (service provider)

7

What type of data collection is this?

{"Craig", "Anant", "Sofia", "Chinny"}

A) DictionaryB) ListC) SetD) StringE) Tuple

8

User-defined Functionsusing recipes in recipes

9

User-defined Functions• Sequences of operations for use elsewhere in program• Function definition says what to do

def <name>():<body>

• Function calls/invocations actually run the function

<name>()

10

User-defined Functions• Sequences of operations for use elsewhere in program• Function definition says what to do

def get_input_and_print():name = input("Your name?\n")print("Hello " + name + "!")

• Function calls/invocations actually run the function

get_input_and_print()

11

Representative Muddiest Points

• The sections on parameters and returns made no sense to me. I don't understand when to indent something, or what to return and when.

• I feel like I do not understand what code block and indentations stand for in Python.

12

Code Blocks• Need a way to tell Python "this statements are related"• Python uses indentation

13

Code Block A

Code Block B(Execution determined by control flow construct)

Control flow construct:

Code Block C(Same indentation as A)

Indentation• In other prog. languages, indentation is just good style• In Python, it is syntactic and semantic

• These three programs are all different• Text is same, white space and behavior is different

14

def test():print('first')print('second')

test()

def test():print('first')

print('second')

test()

def test():print('first')print('second')

test()

What does this program output?

• A) it raises an error

• B)

• C)

• D)

• E)

15

first

firstsecond

secondfirst

firstsecond

def test():print('first')

print('second')

test()

Announcements• We have reading assignments due every Saturday

• Please don't make this a source of drama• Muddiest Points should be about most recent reading

• Tutoring available! cs105-tutor@illinois.edu• Lab this week: Debugging! (and intro. to Colab)

• Quiz 1 this week (Thursday - Saturday)• Taken at home on PrairieLearn• To be done Alone!• Practice exam up soon (but do HW#4 first anyway)

16

How much total time did you spend in the past week on CS 105?• Lecture + Lab = 3 hours• Readings + Preflights + HW + Office hours + Exam0

• Which of these expressions are True for youA) hours_spent < 6 hoursB) 6 hours <= hours_spent < 9 hoursC) 9 hours <= hours_spent < 11 hoursD) 11 hours <= hours_spent < 13 hoursE) hours_spent >= 13 hours

17

Parameters

• Passing parameters is just like an assignment statement• Binds new name to an existing value within the

function• Code inside the function can access value using name• Name disappears when function is over

18

def welcome_message(first, last):

# function body here …

welcome_message("Harry", "Potter")

What value is printed?def do_thing(v1, v2, v3):

a = v2b = v1 + 1print(a * b)

do_thing(3, 2, 0)

A) 0 B) 6 C) 8D) 9 E) any other number

19

What value is printed?def do_thing(var1):

var1 = 2

var1 = 1do_thing(var1)print(var1)

A) 0 B) 1 C) 2D) any other number E) Error occurs

20

What value is printed?def do_thing(var1):

var1.append(4)

var1 = [1, 2, 3]do_thing(var1)print(len(var1))

A) 0 B) 3 C) 4D) any other number E) Error occurs

21

Return Values• If we need a function to produce a value, return will

exit the function, and replace the function call with the returned value

• Function calls can be part of arbitrary expressions

• If there is no return, the function terminates when it reaches the bottom (and returns None)

22

Which assigns x to 5?def f1():

return 5

def f2(): print(5)

def f3(): return print(5)

23

A) x = f1()

B) x = f2()

C) x = f3()

D) All of the above

E) None of theabove

Parameters, Arguments, Return Values

def welcome_message(first, last):

message = "Welcome " + first + " " + last

message += " to CS 105!"

return message

msg = welcome_message("Harry", "Potter")

24

Function Compositiondef f(x):

return 3 * x

What value is returned by f(f(2))?A) 3B) 6C) 9D) 12E) 18

25

None• I don't understand the value of None, and what it means

when you don't have the return statement.• Would there ever be a time that we would need a

function to return the value of "none"?

• Mostly this is important to know because you might do something like this by accident:

x = print("hi there!")

26

Functions vs. Methods• Methods are functions that are part of an object/type• They use dot notation• For example:

my_list = [0, 1, 2, 3]my_list.append(22)

• Functions, in contrast:len(my_list)

27

Functions in Excel• Excel provides many useful "built-in" functions:

• E.g., SUM(), AVERAGE(), MIN()• Take arguments: cells, cell ranges

• Produce return values• Can be part of expressions & assignments

28

What bugs are in the following code?def add_one(x): return x + 1

x = 2x = x + add_one(x)

A) No bugs. The code is fine. B) The function body is not indented. C) We use x as both a parameter and a variable, but we are not allowed to do that D) B and C

29

Next week's reading• Sometimes we want to "conditionally" execute code

• Send email to a student only if they missed Exam 0

• Booleans: a variable type that is either True or False• Relational statements: Boolean from comparing 2 things

• x < 7 • Boolean operators: using multiple relational statements

• x < 7 and z > 2• Conditional blocks: execute code only if condition is true

if x < 7: print('hi')

30

Recommended