Download presentation
Presentation is loading. Please wait.
Published byMeagan Martin Modified over 9 years ago
1
Decisions in Python Bools and simple if statements
2
Computer logic is Boolean George Boole, 19 th 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
3
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
4
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")
5
How to compare strings 1.Start with the first (leftmost) characters in the two strings 2.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 equal 4.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
6
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
7
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
8
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
9
Bool operators and, or, not
10
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.
11
Truth Tables PQP and QP or Q TTTT TFFT FTFT FFFF Pnot P TF FT
12
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 and c != 5"
13
Precedence of Operators
14
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)
15
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
16
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
17
If / else
18
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
19
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
20
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”)
21
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
22
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
23
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”)
24
“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
25
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:”
26
elif
27
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 own if a > b: print(‘a’) elif a > b+c: print(“c”) else: print(“b”)
28
Semantics of elif When you have an if structure that contains an elif 1.Evaluate the first Boolean expression, Test1 2.If Test1 comes out True, do the statements after the if and skip the rest of the structure 3.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
29
Semantics of elif
30
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.
31
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.
32
Caution – too many conditions People tend to put in conditions which are not required if 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.
33
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”)
34
Boolean functions
35
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.
36
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.
37
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 True elif 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!
38
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 = False if ans == ‘y’ or ans == ‘Y’ : result = True return 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)
39
A Shortcut The previous function can actually be written in much shorter form def 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.
40
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”.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.