+ All Categories
Home > Documents > Decisions in Python Bools and simple if statements.

Decisions in Python Bools and simple if statements.

Date post: 04-Jan-2016
Category:
Upload: meagan-martin
View: 220 times
Download: 0 times
Share this document with a friend
40
Decisions in Python Bools and simple if statements
Transcript
Page 1: Decisions in Python Bools and simple if statements.

Decisions in PythonBools and simple if statements

Page 2: Decisions in Python Bools and simple if statements.

Computer logic is Boolean

• George Boole, 19th cent. English mathematician, logician• Had the idea to do logic with two values True and False• Computer logic is based on exactly that• Making decisions in a computer is based on two-valued logic, results

are either True or False• Python has two predefined constants (literals): True and False (note,

no quotes)• Several operators will give Boolean results

Page 3: Decisions in Python Bools and simple if statements.

Relational Operators

• Familiar from algebra: >, <, >=, <=, ==, !=• Relational operators give the “relationship” between two things• They can compare many different types, but be careful to compare

things of the same type, ints and floats are ok, ints and strings are not• They compare the two operands and give True or False as a result• Precedence of all of these operators is lower than the arithmetic

operators and all six of them have the same precedence

Page 4: Decisions in Python Bools and simple if statements.

Comparing float values

• because of errors in representation of float numbers, do not compare floats for exact equality• safer to compare for being "close enough“

• if abs(a - 5000) < 0.00001: • print("close enough")

Page 5: Decisions in Python Bools and simple if statements.

How to compare strings

1. Start with the first (leftmost) characters in the two strings2. While they are the same and strings have not run out,

move to the next characters to the right in each string

3. If both strings ran out at the same time, they are equal4. Otherwise if one string is shorter than the other (only one ran out)

and they are identical up to the length of the shorter, the shorter string is the lesser string

5. Otherwise the characters are different, decide based on their ASCII codes – doesn’t matter what the rest of the strings are, this difference is the deciding point

Page 6: Decisions in Python Bools and simple if statements.

Where to use them?

• You can use them to generate Bools and store the results• X_larger = x > y # stores True or False in X_larger• the_same = x == y # stores True or False in the_same

• Most often use the results in an if statement

Page 7: Decisions in Python Bools and simple if statements.

if statement syntax

• statement starts with the word if• immediately followed by some expression which has a Bool value• then a colon• next will be at least one statement indented more than the if

statement, usually several statements

Page 8: Decisions in Python Bools and simple if statements.

if statement semantics

• When an if statement is encountered in execution• First the expression that gives the Boolean value will be evaluated• If the result is True, the statements which are indented after the if will

all be executed• If the result of the expression is False, the statements which are

indented will be skipped• In either case execution continues at the next statement after the if

statement

Page 9: Decisions in Python Bools and simple if statements.

Bool operators and, or, not

Page 10: Decisions in Python Bools and simple if statements.

Boolean operators

• In Python, not, and and or are Boolean or logical operators• Note that is NOT the same as the relational operators• Boolean operators operate ONLY on Bool values and produce Bool values• and and or are used to combine two Bools into one• not is a unary operator, it reverses a Bool to the opposite value• Their priority is lower than the relational operators• Their individual priorities are not followed by and followed by or.• The truth tables on the next slide show how they operate, their

semantics.

Page 11: Decisions in Python Bools and simple if statements.

Truth Tables

P Q P and Q P or Q

T T T T

T F F T

F T F T

F F F F

P not P

T F

F T

Page 12: Decisions in Python Bools and simple if statements.

DeMorgan's Laws

• not (a and b) is equivalent to (not a or not b)• not (a or b) is equivalent to (not a and not b)• Example:• "not (a > 5 and b < 7 or c == 5)" is the same as "a <= 5 or b >= 7 and c

!= 5"

Page 13: Decisions in Python Bools and simple if statements.

Precedence of Operators

Page 14: Decisions in Python Bools and simple if statements.

Examples

• Given that x is 5, y is 9.2, z is 0• x + 5 > y * 3 and y > z works out as

x + 5 > 27.6 and y > z (* done first) 10 > 27.6 and y > z (+ done next)

False and y > z (relationals done left to right)False and True (second relational done)False (result of and)

Page 15: Decisions in Python Bools and simple if statements.

Cautions

• In most languages the expression 5 < y < 10 does not mean what you would think. In Python it does – it is True if y is between 5 and 10. It is the same as saying 5 < y and y < 10• The expression x == 5 or 6 does NOT mean what you would think. In

fact it is considered always True in Python. Why? 6 after the or operator is considered a separate value – it is NOT compared to the x. The or operator needs a Bool value there, so it forces (“coerces”) the 6 value to be True (anything not zero is True). And from the truth table for or, you can see that anything or True is True! To have the interpreter see it correctly, you write it as x == 5 or x == 6

Page 16: Decisions in Python Bools and simple if statements.

Always True or Always False

• You can easily write expressions which are always True or always False. This is an error. The interpreter will not tell you about them.• Always True: x > 5 or x < 8• Always False: y > 10 and y < 0• Always True: y != 10 or y != 5

Page 17: Decisions in Python Bools and simple if statements.

If / else

Page 18: Decisions in Python Bools and simple if statements.

A two-way branch

• Many times you need to test for a condition and do actions BOTH if it is True or if it is False• This is where the if/else statement becomes useful

Page 19: Decisions in Python Bools and simple if statements.

Syntax of if/else

• First part is an if statement with condition and colon• Then the statements which will be done if the condition is True,

indented as usual• Then the keyword else and a colon, lined up under the if statement• Then the statements which will be done if the condition is False,

indented as the other one is

Page 20: Decisions in Python Bools and simple if statements.

Example

• The two branches cannot be empty, they can be as small as one statement but they have to have something in each• if x > 0:

print(“ok”)else:

print(“sorry”)

Page 21: Decisions in Python Bools and simple if statements.

Semantics of if/else

• The condition at the if line is always executed, as with a plain if statement• If the condition is True, the statements indented under the if line are

executed• If the condition is False, the statements indented under the else line

are executed• Exactly one of the two branches will be executed on any particular

run of the program

Page 22: Decisions in Python Bools and simple if statements.

Alignment of else with if

• You do not have to have an else with every if statement. • BUT if you have an else: you must have an if to go with it. You cannot

start a statement with else!• The indentation determines which if that an else goes with

Page 23: Decisions in Python Bools and simple if statements.

Do these do the same thing?

if x > y:if y > 25:

print(“a”)else:

print(“b”)

if x > y:if y > 25:

print(“a”)else:

print(“b”)

Page 24: Decisions in Python Bools and simple if statements.

“Factoring out”

• If a statement appears in both branches, at the same point in execution, then ‘factor it out’ and put it just one time either before or after the if/else statement• if y + z > x:

print(“ok”)t = 1

else:print(“ok”)t = 2

• The print(“ok”) statement can be done before the if statement starts

Page 25: Decisions in Python Bools and simple if statements.

Shortcut for Booleans

• If you are writing an if statement to test a Boolean variable, you can write the condition as a ‘short cut’• if bool_var == True: can be written as just if bool_var:• Remember that the if statement needs a Boolean value at that point

and the bool_var is assumed to contain one, so comparing it to True is not necessary• If you needed the opposite test, you can write

“if not bool_var:”

Page 26: Decisions in Python Bools and simple if statements.

elif

Page 27: Decisions in Python Bools and simple if statements.

A new keyword elif

• A contraction of “else if”• Used to tie two if statements (or more) together into one structure• Syntax – elif, followed by a bool expression, ended with colon• elif will always be part of an if statement – cannot stand on its ownif a > b:

print(‘a’)elif a > b+c:

print(“c”)else:

print(“b”)

Page 28: Decisions in Python Bools and simple if statements.

Semantics of elif

• When you have an if structure that contains an elif1. Evaluate the first Boolean expression, Test12. If Test1 comes out True, do the statements after the if and skip the rest of the

structure3. If Test1 comes out False, go to the elif and do the Boolean expression there (Test2).

If Test2 is True, do the statements after the elif line, then skip the rest of the structure. If Test2 is False, go to the next elif or else statement and do the Boolean expression there.

4. If all the tests are False, eventually all the tests in the structure will be done. If the structure ends with a plain “else”, the statements after the else will be executed. If it ends with an elif, the statements are skipped.

5. Execution always picks up on the next statement after the if structure

Page 29: Decisions in Python Bools and simple if statements.

Semantics of elif

Page 30: Decisions in Python Bools and simple if statements.

A chain of decisions

• Sometimes you have a series of possible values for a variable• You could write the tests as separate if statements

if x == “A”:print(“do A stuff”)

if x == “C”:print(“do C stuff”)

if x == “K”:print(“do K stuff”)

• But this is pretty inefficient. Every test has to be done every time, regardless of which value is in x. And people make the mistake of putting an else on only the LAST if, to “catch everything else”. It does not do that. That else goes only with the last if, not with all the if’s.

Page 31: Decisions in Python Bools and simple if statements.

Chaining if’s together

• You can combine several if statements into one statement using elif• if x == “A”:

print(“do A stuff”) elif x == “C”:

print(“do C stuff”) elif x == “K”:

print(“do K stuff”)• This is more efficient because the tests are executed only until one is found to be True.

That branch’s statements are done and then the entire structure is exited. No more tests are done.

• This is also more flexible. If you choose to put a last “else:” at the end, to “catch everything else”, it does exactly that.

Page 32: Decisions in Python Bools and simple if statements.

Caution – too many conditions

• People tend to put in conditions which are not requiredif x > 50:

print(“big”)elif x <= 50: # this test is NOT required

# if this elif is executed, you KNOW x must be less than# or equal to 50, you do not have to test for it# A reason it is not good code: what if you make a mistake # on second condition and leave out a branch?

Example: elif x < 50: # what happened to x == 50?• Summary: If your situation only has two mutually exclusive cases, use a plain if/else,

not an if/elif.

Page 33: Decisions in Python Bools and simple if statements.

If you don’t use elif

• You do not HAVE to use elif. It is possible to write the structure as nested if statements, but the indentations required will cause the code to be clumsy to read. elif is aligned directly under the original if• Example: these two pieces of code are equivalent

if x > 5: print(“big”)else: if x > 0: print(“medium”) else: print(“small”)

if x > 5: print(“big”)elif x > 0: print(“medium”)else: print(“small”)

Page 34: Decisions in Python Bools and simple if statements.

Boolean functions

Page 35: Decisions in Python Bools and simple if statements.

A Boolean function

• This is a function which returns a bool result (True or False). The function can certainly work with any type of data as parameter or local variable, but the result is bool.• It’s a good idea to name a bool function with a name that asks a

question “is_Error” or “within_range”. Then the return value makes “sense” – if is_Error returns True, you would think there WAS an error.• There is almost always an if statement in a Boolean function because

the function can have two different results, True or False.

Page 36: Decisions in Python Bools and simple if statements.

Use ONE Return statement

• Remember the rule of structured programming which says every control structure has one entrance and one exit. A function is a control structure. • It is tempting to write a Bool function in a form like: def fun1 (x):

if x > 0:return True

else:return False

Please do NOT! There are two exits to this function.

Page 37: Decisions in Python Bools and simple if statements.

Why are two returns a bad thing?

• A common mistake in a function like this is to neglect one (or more) of the possible paths through the function, which means that it is possible to execute the function so that None is returned, not True or False! This is definitely a bug. • Example:

def yes_no (ans):if ans == ‘y’ or ans == ‘Y’:

return Trueelif ans == ‘N’ or ans == ‘n’:

return False

• What if the parameter had a value that was not one of ‘y’, ’Y’,’ n’, ’N’? The function would return None!

Page 38: Decisions in Python Bools and simple if statements.

How to fix this?

• Just use an extra variable to hold the return value until the function is ready to return, then use that variable

def yes_no(ans):result = Falseif ans == ‘y’ or ans == ‘Y’ :

result = Truereturn result

If result did not get an initial value, the return statement will cause a crash, because of “name not defined”, which tells you that you have an error right there. Of course you can fix it by giving result an initial value of True (or False, depending on your specifications)

Page 39: Decisions in Python Bools and simple if statements.

A Shortcut

• The previous function can actually be written in much shorter formdef yes_no (ans):

return ans == ‘y’ or ans ==‘Y’

The expression in the return statement must be evaluated before it can return. The relational operators and logical operator will combine to give a bool value – if the parameter had a ‘y’ in it, you get a True – anything else gives a False.

Page 40: Decisions in Python Bools and simple if statements.

Calling Boolean functions – another shortcut• When you call a Boolean function, you call it as part of another

statement (since it returns a value).• The value it returns is a Boolean value, True or False.• If you are calling the function as part of an if statement, for example,

you can call it this way:if is_error(p1):

print(“something error”)is_error(p1) is replaced by a Boolean value when it returns, so you do not have to compare it to something else, like “== True”.


Recommended