Decisions in Python Bools and simple if statements.

Slides:



Advertisements
Similar presentations
Python Programming Language
Advertisements

Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Introduction to Computers and Programming Lecture 6 Professor: Evan Korth New York University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
CS 117 Spring 2002 Decision Making Hanly Chapter 3 Friedman-Koffman Chapter 4.
The If/Else Statement, Boolean Flags, and Menus Page 180
Chapter 4 Making Decisions
Decision Making George Mason University. Today’s topics 2 Review of Chapter 2: Decision Making Go over exercises Decision making in Python.
Decisions in Python elif. A new keyword elif A contraction of “else if” Used to tie two if statements (or more) together into one structure Syntax – elif,
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Logic Gates Circuits to manipulate 0’s and 1’s. 0’s and 1’s used for numbers Also to make decisions within the computer. In that context, 1 corresponds.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
CS0004: Introduction to Programming Relational Operators, Logical Operators, and If Statements.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
Decision Structures and Boolean Logic
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
CPS120: Introduction to Computer Science Decision Making in Programs.
Controlling Execution Dong Shao, Nanjing Unviersity.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
TK 1914 : C++ Programming Control Structures I (Selection)
22/11/ Selection If selection construct.
Decision Making CMSC 201. Overview Today we will learn about: Boolean expressions Decision making.
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Decisions in Python Boolean functions. A Boolean function This is a function which returns a bool result (True or False). The function can certainly work.
Decision Statements, Short- Circuit Evaluation, Errors.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
Today… Operators, Cont. Operator Precedence Conditional Statement Syntax. Winter 2016CISC101 - Prof. McLeod1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
CS 115 Lecture 8 Conditionals, if statements Taken from notes by Dr. Neil Moore.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Control Structures I Chapter 3
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
CS 115 Lecture Conditionals and if statements
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Bool operators and, or, not
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Debugging and Random Numbers
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
CMSC201 Computer Science I for Majors Lecture 03 – Operators
Topics The if Statement The if-else Statement Comparing Strings
And now for something completely different . . .
Conditions and Ifs BIS1523 – Lecture 8.
Bools and simple if statements
Types, Truth, and Expressions (Part 2)
Comparing Strings – How to
Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and.
Boolean Expressions to Make Comparisons
Boolean logic Taken from notes by Dr. Neil Moore
Presentation transcript:

Decisions in Python Bools and simple if statements

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

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

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 ) < : print("close enough")

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

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

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

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

Bool operators and, or, not

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.

Truth Tables PQP and QP or Q TTTT TFFT FTFT FFFF Pnot P TF FT

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"

Precedence of Operators

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)

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

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

If / else

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

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

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”)

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

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

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”)

“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

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:”

elif

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”)

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

Semantics of elif

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.

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.

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.

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”)

Boolean functions

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.

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.

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!

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)

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.

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”.