13
9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes Will know what a block of code is. An understanding of if statements and boolean expressions used with them. An ability to use if-else statements An ability to use if-elif-else statements An understanding of conditionals used with strings Be familiar with boolean operators Be familiar with boolean algebra, including DeMorgan's law Be familiar with Truth tables Understand the use of logical and to replace nested ifs 2 Control Structures Control Structures allow different lines of code to be executed depending on an evaluation of some expression. The most common conditional structure is the if structure. An if structure contains an expression and a block or body of code. When the expression is true, the block of code associated with the if statement is executed, otherwise it's skipped. 3

Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

1

Conditionals and Booleans

CMSC 201

Fall 2012

Instructor: John Park

Lecture Section 01

Discussion Sections 02-08, 16, 17 1

Learning Outcomes

• Will know what a block of code is.

• An understanding of if statements and boolean expressions used with them.

• An ability to use if-else statements

• An ability to use if-elif-else statements

• An understanding of conditionals used with strings

• Be familiar with boolean operators

• Be familiar with boolean algebra, including DeMorgan's law

• Be familiar with Truth tables

• Understand the use of logical and to replace nested ifs

2

Control Structures

• Control Structures allow different lines of code to be executed depending on an evaluation of some expression.

• The most common conditional structure is the if structure.

• An if structure contains an expression and a block or body of code.

• When the expression is true, the block of code associated with the if statement is executed, otherwise it's skipped.

3

Page 2: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

2

“if” Statements and Control Blocks

• If statements take the form : if <condition>:

<block>

• Take note of the ':' after the <condition>.

• In Python, the ':' character, colon, is used to denote the start of a code block.

• All code in the block must be tab indented after the ':'.

(For the rest of the lecture, when we refer to “tabs”, we mean “an additional level of indentation”, not an actual TAB character)

4

“if” Statements and Control Blocks

• The first line that is not tabbed-in is the first line not included in that code block.

if <condition>:

block-line-1

block-line-2

block-line-3

out-of-block-line-1

out-of-block-line-2

5

“if” Statements and Control Blocks

• Many other structures in Python also use code blocks in this same form, where all lines after the ':' are tabbed in to be part of that block. This includes functions and loops.

• The indentation formatting is critical: the lines in the block must all be indented exactly the same amount.

• Although it's possible to indent in any way (1 space, 3 spaces, 1 tab, etc..), it must be consistent, or python will return an error.

• Our CMSC 201 Coding Standard mandates an indentation of 4 spaces for each level

6

Page 3: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

3

“if” Statements and Control Blocks

• If statements and other structures that use blocks may be nested.

– This means the number of tab indents must increase with the level of nesting.

if <condition1>:

block1-line-1

block1-line-2

if <condition2>:

block2-line-1

block2-line-2

out-of-block2-line-1-in-block1-line-3

out-of-block2-line-2-in-block1-line-4

out-of-block1-line-1

out-of-block1-line-2

out-of-block1-line-3 7

Managing Indentation

• Emacs automatically handles Python indentation for you:

– Emacs analyzes your code as you type, looking for special tokens like the ‘:’ . It then infers the level of indentation

– When you start a line by hitting the <TAB> key, emacs automatically indents that line by inserting the correct number of leading spaces.

– To finish a block, hit <TAB> to indent to the current block depth, then hit <Backspace> to “unindent” a level.

8

Managing Indentation

• Since emacs indents consistently for us, using it will keep us from having this kind of error when our code is in a file. You'll still have to be careful about indentation when using the interactive interpreter though.

9

Page 4: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

4

Managing Indentation

>>> if True:

... x = 1

... y = 2

File "<stdin>", line 3

y = 2

^

SyntaxError: invalid syntax

>>>

10

Boolean Expressions

• The <condition> part of the if statement represents a boolean expression that is either true or false.

• Expressions can be formulated using mathematical symbols to compare different values.

11

Python Comparison Operators

Operation Python Operator

is less than <

is less than or equal to <=

is greater than >

is greater than or equal to >=

is equal to ==

is not equal to !=

12

Page 5: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

5

Python Comparison Operators

• The same 6 operators can be applied to strings, in which case it tests for equality or alphabetical order.

• Equality test (“==“) is strict, case-sensitive test

• For ordering, comparison is done position-by-position, stopping when a difference is found

– “less than”, (i.e., “earlier””) determined by comparing ASCII codes.

– So, upper-case letters come before lower-case

“ab” < “ac”, “ab” < “abc”, and “Abc” < “aBC” (why?) 13

Boolean Expressions

• When an expression is evaluated, it returns a boolean value in Python

• The Python boolean values are True and False (capitalization is important!)

• Examples:

>>> x = 6

>>> y = 4

>>> x < y

False

>>> x <= y

False

>>> x == y

False

>>> x >= y

True

>>> x > y

True

>>> x != y

True

14

Boolean Expressions

• Like any other type in Python, variables can store boolean values.

>>> aBoolean = x > y

>>> print aBoolean

True

• Boolean values themselves are boolean expressions.

15

Page 6: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

6

Converting to Boolean

• Other data types can be converted to booleans by using bool(value); the conversion rules are:

– Integer or Float 0 becomes False, any other number becomes True.

– An empty string becomes False, any other string becomes True.

– An empty list becomes False, any other list becomes True.

16

Converting to Boolean

>>> bool(0)

False

>>> bool(3)

True

>>> bool(-1)

True

>>> bool(0.0)

False

>>> bool(0.1)

True

>>> bool("")

False

>>> bool("hi")

True

>>> bool([])

False

>>> bool([1, 2])

True

# Some strange e.g.s:

>>> bool(“False")

True

>>> bool([0])

True

>>> bool([False])

True

17

“if” Statement Execution

• When the condition of an if statement evaluates to true, the code block for that if statement is executed, otherwise it is skipped.

>>> x = 6

>>> y = 4

>>> if x > y:

... print "x is greater than y“

...

x is greater than y

>>> if x <= y:

... print "x is less than or equal to y“

...

>>>

18

Page 7: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

7

“if” Statement Execution

Restating the obvious:

– The conditional "x > y" tests whether x is a greater value than y and if that is true, the string "x is greater than y" is printed.

– It is not a mathematical assertion that x is greater than y

• The condition expression of an if statement is implicitly converted to a boolean:

>>> str = ""

>>> if str:

... print ’string "str" is not empty’

...

>>>

– Notice nothing was printed out

19

if-else

• If you want to handle cases when a condition fails, as well as when it succeeds, use the else

statement in conjunction with the if.

• else statements also contain a code block and are executed when the condition in the if statement is false, otherwise it is skipped.

• if-else statements take the form of : if <condition>:

<true-block>

else:

<false-block> 20

if-else

• We can revise the previous example as : >>> x = 6

>>> y = 4

>>> if x >= y:

... print "x is greater than or equal to y“

... else:

... print "x is less than y“

...

x is greater than or equal to y

21

Page 8: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

8

if-else

• If we swap the values of x and y and rerun the if-else we get:

>>> x = y

>>> y = x

>>> if x >= y:

... print "x is greater than or equal to y“

... else:

... print "x is less than y“

...

x is greater than or equal to y

• Something went wrong!

22

Digression: Swapping Variables

• So here's what we should have written : >>> x = 6

>>> y = 4

>>> temp = x

>>> x = y

>>> y = temp

>>> if x >= y:

... print "x is greater than or equal to y“

... else:

... print "x is less than y“

...

x is less than y

24

Digression: Swapping Variables

• Most languages require the use of a third variable (conventionally called temp) to perform a swap

• Python has a short-cut built into the language for this, called simultaneous assignment:

var1, var2 = var2, var1

• You can even rotate a set of variables: a, b, c, d = b, c, d, a

25

Page 9: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

9

Digression: Swapping Variables

• So here's what we should have written : >>> x = 6

>>> y = 4

>>> x, y = y, x

>>> if x >= y:

... print "x is greater than or equal to y“

... else:

... print "x is less than y“

...

x is less than y

26

Nested if Statements

• You can think of an if structure as a fancy statement: you can insert it anywhere where you would put a simple statement.

• So, you can even put it inside another if: >>> x = 1000001

>>> if x > 0:

... print "x is positive“

... if x > 1000000:

... print “Boy, x is REALLY positive!!!“

... else:

... print "x is not positive“

...

x is positive

Boy, x is REALLY positive!!!

>>> 27

Nested if Statements

• You can also put it inside the else block: >>> x = 0

>>> if x > 0:

... print "x is positive“

... else:

... print "x is not positive“

... if x < 0:

... print “In fact, x is negative“

... else:

... print “In fact, x is zero“

...

x is not positive

In fact, x is zero

>>>

28

Page 10: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

10

Nested if Statements

• You can use this to make a n-way selection >>> x = 3

>>> if x == 1:

... print “You selected 1“

... else:

... if x == 2:

... print “You selected 2“

... else:

... if x == 3:

... print “You selected 3“

... else:

... if x == 4:

... print “You selected 3“

... else:

... print “Invalid selection“

...

You selected 3

>>>

29

if-elif-else

• That was tedious; is there a better way? Yes: the if—else-if—else chain

– Python actually uses keyword “elif”—more terse >>> x = 3

>>> if x == 1:

... print “You selected 1“

... elif x == 2:

... print “You selected 2“

... elif x == 3:

... print “You selected 3“

... elif x == 4:

... print “You selected 4“

... else:

... print “Invalid selection“

...

You selected 3

>>>

30

Boolean Operators

• How do you do complex comparisons?

– E.g.: “x is greater than 0, but less than 10”

or: “x is either less than -10, or greater than 10”

or: “x is not in a given list”

• Python provides the boolean operators “and”, “or”, and “not”

31

Page 11: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

11

Boolean or

X Y X or Y

T T T

T F T

F T T

F F F

32

Boolean and

X Y X and Y

T T T

T F F

F T F

F F F

33

Boolean not

X not X

T F

F T

34

Page 12: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

12

Combining Boolean Operators

• Order of operator precedence, from high to low is: not >> and >> or

• Expressions may use parentheses to change the order of operations

• These basic principles can be used to construct more complex operators:

– E.g.: exclusive-or: (P or Q) and not (P and Q)

35

Combining Boolean Operators

X Y not X and Y

T T F

T F F

F T T

F F F

36

Combining Boolean Operators

X Y not (X and Y)

T T F

T F T

F T T

F F T

37

Page 13: Conditionals and Booleans Learning Outcomespark/cmsc201/fall12/...9/26/2012 1 Conditionals and Booleans CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections

9/26/2012

13

Boolean Algebra

• You can use Boolean algebra to manage and reduce complex expressions.

• The and and or operators distribute over each other.

– a or (b and c) == (a or b) and (a or c)

– a and (b or c) == (a and b) or (a and c)

38

Boolean Algebra

• DeMorgan's Law distributes an outer 'not' by negating (not-ing) each of the components and flipping ands to ors and ors to ands.

– not(a or b) == (not a) and (not b)

– not(a and b) == (not a) or (not b)

39

Example

• So now, combining several things we just learned:

>>> str = raw_input(“Enter a char: “)

>>> ch = str[0]

>>> if str >= ‘a’ and str <= ‘z’:

... print “Lower-case letter“

... elif str >= ‘A’ and str <= ‘Z’:

... print “Upper-case letter“

... else:

... print “Non-alphabetic character“

...

Enter a char: q

Lower-case letter

>>>

40