l5 conditionals sp20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else:...

35
Lecture 5: Booleans and Conditionals Craig Zilles (Computer Science) February 23, 2020 https://go.illinois.edu/cs105sp19 CS 105

Upload: others

Post on 12-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Lecture 5: Booleans and Conditionals

Craig Zilles (Computer Science)

February 23, 2020

https://go.illinois.edu/cs105sp19

CS 105

Page 2: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Today

1. Booleans2. Simple conditionals

• if, else, elif3. Boolean Expressions and Operators

• Relational operators: ==, !=, <, >, <=, >=• Boolean operators: and, or, not

4. More on Functions5. Short circuiting6. Nesting

2

Page 3: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Booleans• I don't understand what Booleans are and how to use

them, why they're used, etc.

• They are just another type (like int, string, float)• There are two Boolean values: True, False

• Used for making decisions:• Do something or don't do something

3

Page 4: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Boolean Expressions• Expressions that evaluate to True or False

(1 + 6) < (2 + 5)

• A) True• B) False• C) Raises an error

4

Page 5: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

if statements(conditionally execute code blocks)

x = 1if x < 7:

print(x)print(7)

5

What does this code print?a) 1b) 7c) 1

7a) Something elseb) An error occurs

Page 6: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Indentation"I am confused when to use indentation"

"I was a bit confused on code blocks. Is hitting the tab key equivilent to hitting the space bar 3 or 4 times? Does it matter which one you use?"

"What happens if you mix tabs and spaces in your code?"

6

Page 7: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

if/else statements

x = 2if x > 8:

x = x - 2print(x)

else:print(8)

7

What does this code print?a) 0b) 8c) 0

8a) Something elseb) An error occurs

Page 8: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

if/elif/else statementsx = 1if x < 8:

print('less than 8')elif x > 20:

print('greater than 20')else:

print('from 8 to 20')

Include as many elifs as you want, between if and else

8

Page 9: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Relational and membership operators

• Why is there both == and =? What's the difference between the two? When do you use ==, and =?

9

Page 10: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Suppose young is a variable with a Boolean value

why doesif young == true:not work whenif young:does?

10

Page 11: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Relational Ops on non-numbers• Why lower case letters are greater than upper case

letters?

• People often normalize case before comparisons

thing1.lower() < thing2.lower()

11

Page 12: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Truthy and Falsy• Python will convert non-Boolean types to Booleans

if "hello":• You can force conversion using bool() function.• All values are truthy (convert to True) except:

12

Falsy

valu

es

Page 13: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

What gets printed?grade = 98 if (grade >= 90):

print(“You got an A!”) if (grade >= 80):

print(“You got a B!”) else:

print(“You got something else”)

13

A) You got an A!B) You got a B!C) You got something elseD) More than one of the above

Page 14: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

What gets printed?grade = 98 if (grade >= 90):

print(“You got an A!”) if (grade >= 80 and grade < 90):

print(“You got a B!”) else:

print(“You got something else”)

14

A) You got an A!B) You got a B!C) You got something elseD) More than one of the above

Page 15: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Boolean operators• Why is x==3 or 4 always True? I am still confused

with this concept.

• "If you've finished your homework and done your chores then you can go out."

• Binary operators: and or• Unary operator: not

• Operate on Booleans (or coerce to Booleans)

15

Page 16: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Precedence• I'm still confused about the sequence of the operations

when it has both Boolean operators and other kinds of operators.

• Order of evaluation is confusing. When I was comparing 'and' or 'or' to a symbol, it is hard to tell which one ishould evaluate first.

• Relational operators evaluate before Boolean ops.• and evaluates before orx == 7 and y == 3 or x > 12 and y < -12• Avoid relying on operator precedence; use parentheses

16

Page 17: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

x==3 or 4

17

Page 18: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Announcements• Lab this week: Practice with Functions!!!

• Exam 1 this week from Thursday - Sunday• Do you have a CBTF reservation?• Cumulative through HW5 (i.e., lots of overlap w/Quiz1)• Practice exam 1 out Tuesday morning (do HW 5 first)

• Quiz 1: mean = 88%, median = 92%• Tutoring encouraged if you got 65% or less

18

Page 19: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Functions Review: Parameters, Arguments, Return Values

def welcome_message(first, last):

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

message += " to CS 105!"

return message

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

19

Page 20: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

What does test(7) return?def test(num):

if num > 0:return True

return False

A) TrueB) FalseC) first True and then FalseD) the tuple (True, False)E) an error occurs

20

Page 21: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Function Compositiondef f(x):

return 3 * x

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

21

Page 22: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

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!")

22

Page 23: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

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)

23

Page 24: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

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) Both B and C

24

Page 25: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Short Circuiting• i am confused about the concept of short circuit

• Python is lazy (which is a good thing if you understand it)• It won't evaluate Boolean expressions it doesn't need to

True or anything() is TrueFalse and anything() is False

• Python won't evaluate the anything() part• Can use this to avoid running code that would get errors

(len(my_str) > 10) and (my_str[10] == 'a')

25

Page 26: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

What does this program output?

• A) it raises an error

• B)

• C)

• D)

• E) it prints nothing, but raises no errors

26

hello

there

hellothere

print('hello') and print('there')

Page 27: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Conditionals

• I don't understand how each of the components of the chapter can be used in real world cases. A thing I like to do to help me better grasp the concepts, is imagine them happening in this world. So giving me more mundane scenarios of where we would be using these things would help a lot.

27

Page 28: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Shape of "decision tree": if w/o elseAsked my TA to send email to all students in the class that didn't take Exam 0.• Step 1: make a set of all students that took Exam 0• Step 2: check each student in class if in the set

if student in exam0_takers:send_email(student)

28

Page 29: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Shape of "decision tree": if w/elseCompany sends recruiting invitations to students with Python in their resume, sends 'nack' email to others

if 'python' in resume.lower():send_invitation(student)

else:send_polite_decline(student)

29

Page 30: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Choosing between many alternativesFinal exam location based on first letter of netid:

[a-j] Loomis 100[k-o] DCL 1320[p-z] English 214

first_char = netid.lower()[0]if first_char <= 'j':

location = 'Loomis 100'elif first_char <= o:

location = 'DCL 1320'else:

location = 'English 214'

30

Page 31: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Multi-way branches in general?If you were choosing between 6 possibilities, what is the fewest elif statements you coud have:

A) 1B) 2C) 3D) 4E) 5

31

Page 32: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Nesting• CS likes composition; indent + indent = nesting

32

Page 33: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

NestingWhen to use elif and when to use else? I think there should be only 1 else in the whole program but I saw:

if sales_type == 2:if sales_bonus < 5:sales_bonus = 10

else:sales_bonus = sales_bonus + 2

else:sales_bonus = sales_bonus + 1

Can I change the first 'else' into elif?33

Page 34: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Next week's reading• Sometimes we want to execute code multiple times

• Send email to each student with their exam score

• For loop: do something to each element of a collectionfor val in ['good', '105', 'class']:

print(val)• Range function: generate lists of numbers

range(6) # -> [0, 1, 2, 3, 4, 5]• While loop: not as important as for loop• Loop nesting: put a loop inside another loop• break & continue: give more control of loops

34

Page 35: L5 Conditionals SP20 - pages.github-dev.cs.illinois.edu · else: sales_bonus= sales_bonus+ 2 else: sales_bonus= sales_bonus+ 1 Can I change the first 'else' into elif? 33. Next week's

Test often to minimize debugging time

• Write at most a few lines of code before testing!• If you made a mistake, the problem must be in those

few lines

• Biggest novice mistake: write a lot of code before testing any of it

• When it doesn’t work, it takes a long time to find the bug

35