Lecture 4 - Texas A&M Universitycourses.cse.tamu.edu/keyser/engr102/Lecture4.pdf · • step 1 ->...

Post on 24-Jun-2020

0 views 0 download

transcript

Lecture 4Conditionals and Boolean Expressions

What are we going to cover today?

• What is procedural knowledge?

• Boolean expressions

• The if-else and if-elif-else statements

• Examples

Procedural Knowledge

• We differentiate our knowledge of facts from our knowledge of how to do things

• Procedural knowledge

• Where do you see procedural knowledge?

• Instructions• Recipes

• Programming is the act of describing a process for the computer to follow

Expressing Procedural Knowledge

• If the process is identical for all situations, then it can be linear• step 1 -> step 2 -> step 3 -> … -> step N• Most recipes are like this• The sequential steps we’ve been seeing are like this

• But if the process varies depending on the situation, it will have branches like a tree

• step 1 -> step 2 -> step 3 (for some cases)• step 1 -> step 2 -> step 4 (for other cases)• We want to make our program adapt to a variety of use situations

• To create branches in programs, we describe the conditions for each• Conditions are assessed as Boolean (true/false) variables and expressions

Computational Constructs

• After this lesson, we’ll have 2 ways of organizing computation:Sequential Conditional

Boolean Expressions

• To have a conditional, we need a Boolean value• Remember that Booleans are values that can be True or False• But, how can we create a Boolean?

• There are many ways, but the most common are relational operators

Relational Operators

• Allow us to compare two values. We generally have comparisons for• Equality: == [note the two equal signs, instead of one. One is “assignment”!]• Inequality: != [note the !]• Less Than: <• Greater Than: >• Less Than or Equal To: <= [note that =< is not allowed]• Greater Than or Equal To: >= [note that => is not allowed]

• The result of a relational operator is a Boolean value• It can be assigned to a variable or used in an expression

Relational Operators

• For example, we might want to determine if a variable is:• zero (variable1 == 0)• not zero (variable1 != 0)• positive (variable1 > 0)• negative (variable1 < 0)• greater than or equal to zero (variable1 >= 0)• less than or equal to zero (variable1 <= 0)

Example

• If we have variables:• JohnAge : the age of John• JoeAge: the age of Joe

• And we want a Boolean variable:• JohnOlderThanJoe : True if, and only if, John is older than Joe

• How would we set that variable?

Example

• If we have variables:• JohnAge : the age of John• JoeAge: the age of Joe

• And we want a Boolean variable:• JohnOlderThanJoe : True if, and only if, John is older than Joe

• How would we set that variable?• JohnOlderThanJoe = JohnAge > JoeAge

Boolean Operators

• Boolean Operators are operators for 1 or 2 Booleans• The Boolean operators are and, or, and not

• A and B : true if both A and B are true, false otherwise• A or B : true if A is true or B is true (or both are true), false otherwise• not A : “reverses” A, so true if A is false, false if A is true

• Boolean operators can be combined to create almost any logical decision

• There are often many ways to combine Booleans and get the same result• e.g. A and B is equivalent to: not ((not A) or (not B))

• Same is true for larger Boolean/Relational Expressions• ((A > B) and (B < C)) is equivalent to: not ((B>=A) or (B>=C))

Boolean Operators

• Examples:• To test if a variable is between 0 and 100, inclusive

• ((variable1 >= 0) and (variable1 <= 100))• To test if two variables are equal and positive

• ((variable1 == variable2) and (variable1 > 0))• Notice: don’t need to test for variable2 > 0 since we know variable1 must equal variable2

• Alternative versions of the above tests:• not ((variable1 < 0) or (variable1 > 100))• not ((variable1 != variable2) or (variable1 <= 0))

Example

• Given a temperature in Fahrenheit stored in the variable F, set a variable that tells whether water at that temperature is in liquid form or not.

Example

• Given a temperature in Fahrenheit stored in the variable F, set a variable that tells whether water at that temperature is in liquid form or not.

is_liquid = (F >= 32) and (F <= 212)

Order of Operation and Boolean Expressions

• Boolean order of operations• not before and before or

• Relational operators before Boolean operators

• not a == b is evaluated not (a == b) rather than (not a) == b

• You should use parentheses rather than relying on order of operation

• to avoid bugs in your code• to improve comprehensibility

• Reminder of order of operations for assignment operators

Convention Description

( ) Items within parentheses are evaluated first

**Exponentiation operators are evaluated next. The right side of the exponentiation is computed first

* / // % Next to be evaluated are *, /, //, and %.

+ - Finally come + and - with equal precedence.

left-to-rightIf more than one operator of equal precedence could be evaluated, evaluation occurs left to right.

Example

• What would be the output of the following code?

a = 10

b = 10

c = 20

d = ((a>b) and (b<=c)) or (not((((c<=a+b) and (a==10)) or ((b==10) and c!=10))))

print(d)

Example

• What would be the output of the following code?

a = 10

b = 10

c = 20

d = ((a>b) and (b<=c)) or (not((((c<=a+b) and (a==10)) or ((b==10) and c!=10))))

print(d)

OutputFalse

Example

• Why?a = 10

b = 10

c = 20

d = ((a>b) and (b<=c)) or (not((((c<=a+b) and (a==10)) or ((b==10) and (c!=10)))))

(False and True ) or (not((( True and True ) or ( True and True ))))

( False ) or (not(( True or True )))

( False ) or (not( True ))

( False ) or ( False )

False

The if statement

• The “if” statement lets us create branches in our code• This is also called a conditional, since it sets a condition describing how

program flow should work.

• Format of a statement:if <condition>:

<things to do>

The if statement

• The “if” statement lets us create branches in our code• This is also called a conditional, since it sets a condition describing how

program flow should work.

• Format of a statement:if <condition>:

<things to do>

Start with the keyword if

The if statement

• The “if” statement lets us create branches in our code• This is also called a conditional, since it sets a condition describing how

program flow should work.

• Format of a statement:if <condition>:

<things to do>Next is the condition: a Boolean literal, variable, or expression

The if statement

• The “if” statement lets us create branches in our code• This is also called a conditional, since it sets a condition describing how

program flow should work.

• Format of a statement:if <condition>:

<things to do>There is a colon at the end of the line

The if statement

• The “if” statement lets us create branches in our code• This is also called a conditional, since it sets a condition describing how

program flow should work.

• Format of a statement:if <condition>:

<things to do>

Then the following line(s) are indented.It is common practice to indent 4 spaces.

The if statement

• The “if” statement lets us create branches in our code• This is also called a conditional, since it sets a condition describing how

program flow should work.

• Format of a statement:if <condition>:

<things to do>

Finally are the commands to actually perform, if and only if the condition is true

Indenting

• It is important to indent the code that should happen if (and only if) the condition is true.

• The indentation should be consistent through the program, and must be the same for every line in the conditional “block”

• 4 spaces is common• Often, the editor in your IDE will do this for you automatically.

• Note: unlike most other programming languages, the indentation is required in Python.

Example (1)

if True:print("Howdy")

print("World")

OutputHowdyWorld

Example (2)

if False:print("Howdy")

print("World")

OutputWorld

Notice that only the indented portion is subject to the conditional.

Example (3)

if True:print("One")

print("Two")if False:

print("Three")print("Four")

print("Five")

OutputOneTwoFive

Notice that more than one line can be part of the conditional

Example (4)

Temperature = 100is_hot = (Temperature > 85)if is_hot:

print("It's hot")if not is_hot:

print("It's not hot")

OutputIt's hot

The condition can be a Boolean variable

Temperature = 100if Temperature > 85:

print("It's hot")if Temperature <= 85:

print("It's not hot")

Example (5)

OutputIt's hot

The condition can be a Boolean expression

The if-else and if-elif-else statements

• When there are two possibilitiesif (boolean-expression):

do this when expression is trueelse:

do this when expression is false

• When there are more than two alternative paths

if (boolean-expression1):do this when expression1 is true

elif (boolean-expression2):do this if expression1 is false but

expression 2 is trueelif (boolean-expression3):

…else:

do this if all above expressions are false

The FIRST Boolean expression that is true will be the only one followed:

Examples

walking_speed = 3biking_speed = 10if walking:

speed = walking_speedelse:

speed = biking_speedtime-taken = distance / speed

if major == "CSCE":office = 'HRBB 302'

elif major == "ECEN":office = 'WEB 301'

elif major == "MEEN":office = 'MEOB 100'

else:office = 'unknown'

If how_many is 3?

If how_many is 8?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

If how_many is 3?

If how_many is 8?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

Output

Test the first condition

If how_many is 3?

If how_many is 8?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

OutputTest the second condition

First condition was false, so skip indentation

If how_many is 3?

If how_many is 8?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

OutputSecond condition was false, so skip indentation

Test the third condition

If how_many is 3?

If how_many is 8?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

Output

Third condition was true, so go to indented section

If how_many is 3?

If how_many is 8?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

OutputFew

This line was executed, so there was output.

Execution continues from after the rest of the if-elif-else statement

If how_many is 3?

If how_many is 8?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

OutputFew

OutputSeveral

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

What input can produce “None” for an output?

What will the following code produce?

if how_many == 1:print("Single")

elif how_many == 2:print("Couple")

elif how_many < 5:print("Few")

elif how_many < 10:print("Several")

elif how_many >= 10:print("Lots")

else:print("None")

What input can produce “None” for an output?

Nothing! The elif cases handle all the situations, so there is never a chance to encounter the else clause.

If we wanted to handle an input of 0, we would need to modify the (how_many < 10) condition.

Nested Branches

• Complex condition statements can become hard to understand

• And hard to maintain• We can nest condition

statements • Place an if/if-else/if-elif-else

statement inside of a conditional block

• The new statement is “nested” inside the first one

• Remember to be consistent with indentation – it is required by Python

if (animal == 'bird'):if (animal_name == 'penguin'):

moves_by= 'walking'else

moves_by = 'flying'elif (animal == 'fish'):

moves_by = 'swimming'elif (animal == 'snake'):

moves_by = 'slithering'else:

moves_by = 'walking'

Why would we nest conditions?

• To better match our understanding of the problem• Helps the programmer reflect the logic of the situation better• We don’t always know all of the various options at the time of the first condition

• e.g. we might get input based on the first condition, then need another condition to respond to the input

• To make the code easier to comprehend• Long, complex Boolean expressions can be hard to comprehend• Nested statements can make the logic easier to follow

• We will see other examples of nesting in the future

When should we use each type?

• Use if-elif-else:• When you have multiple “cases” of the same type• Generally, the conditionals in the if-elif statements should be very similar to

one another• Use nested statements:

• When you have a clear “order” of checks: checking A then B• When a single conditional would appear too complicated

• Use separate if statements:• When your conditions are checking different concepts• Or, when you potentially have things matching more than one condition, and

want to deal with both

Example Problem Taken from Your Own Life

• One of the most important skills engineering students need is to be able to effectively allocate their time to their studies.

• What questions do we want to answer?• How effective are many short, a middle number of medium-length, or a few

long study sessions?• How might other aspects of us affect the outcome?

• What characteristics effect the outcome?• The length of study sessions• The number of study sessions• How tired, stressed, hungry, etc. you are

Start by just considering study session length

• We can model how much a student learns in a study session if we have a model of how the student’s capture of knowledge changes through the session.

• We can think of this using the following graph.

• The number of concepts/skills learned in a session is the area under the curve.

Time since start of study session

Rate ofLearning 1. We might assume a constant learning rate

3. And, maybe when we get fatigued we learn worse

2. But perhaps there is a warm-upperiod where we remember whatwe had learned before

Conditionals and Boolean Expressions• Consider computing the number of concepts learned in a study session of a given

length using a learning rate model that involves a warm-up period

• We could implement this as a single line of code, but it would not be very comprehensible

• So, we will create variables to store intermediate values needed in the computation

• For example: warmup_slope = (0.2 – 0.1) / 15

Time since start of study session (minutes)

Rate ofLearning(conceptsper minute)

15

0.1

0.2

observed-learning-rate [observation]

Example of if-else• To compute the learned concepts, we need

different paths if the length of the session is less than 15 minutes

if (session_length < 15):warmup_slope = ((0.2 - 0.1) / 15)end_learning_rate = 0.1 + (warmup_slope * session_length)concepts_learned = session_length *

((0.1 + end_learning_rate) / 2)else:

avg_warmup_learning-rate = (0.1 + 0.2) / 2concepts_learned = 15 * avg-warmup_learning_rate +

((session_length – 15) * 0.2)

Time since start of study session (minutes)

Rate ofLearning(conceptsper minute)

15

0.1

0.2

We are computing the areaunder the above function.

Example of if-elif-else• Now we need three different computations

if (session_length < 15):warmup_slope = ((0.2 - 0.1) / 15)end-learning-rate = 0.1 + (warmup_slope * session_length)concepts_learned = session_length *

((0.1 + end_learning_rate) / 2)elif (session_length <= 30):

avg_warmup_learning_rate = (0.1 + 0.2) / 2concepts_learned = 15 * avg_warmup_learning_rate +

((session_length – 15) * 0.2)else:

avg_warmup_learning_rate = (0.1 + 0.2) / 2cooldown_slope = (0.0 – 0.2) / (120 – 30)end_learning_rate = 0.2 – (cooldown_slope *

(session_length – 30))concepts_learned = 15 * avg_warmup_learning_rate +

(30 – 15) * 0.2 + (session_length – 30) * ((0.2 + end_learning_rate) / 2)

Time since start of study session (minutes)

Rate ofLearning(conceptsper minute)

15

0.1

0.2

30 120