Docsity

Conditionals - Computer Science - Lecture Notes, Study notes of Computer Science

Partial preview of the text

Download Conditionals - Computer Science - Lecture Notes and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Boolean expressions (cont.)
  • Conditionals

Logical expressions can be nested

((not (2 > 3)) or (4 < 2)) and not ((2 > 3) or False) True

If operands are not Boolean expressions, Python will convert for us

  • Does not work the way you would expect ...

17 and 54 54

0 or 20 20

len([10, 20]) or "spam" 2

len([10, 20]) and "spam" "spam"

  • Good idea to avoid this whenever possible

What is going on?

  • How Python evaluates logical expressions
    • x or y if x == True return x
    • x or y if x == False return y
    • x and y if x == True return y
    • x and y if x == False return x

Basic conditional execution (aka selection)

Conditional statement syntax if boolean condition: statement statement ...

  • If the boolean condition evaluates to True
  • Then execute the body of the if statement
  • Otherwise, skip the body of the if

Flow Charts

  • A diagram notation for representing conditional statements

if x < y: # condition x = x + 1 # if statement y = y - 1 # statement after if

Condi&on

Statement

Statement

False True x^ <^ y^?

x = x + 1

y = y - 1

No Yes

If-Else statements

If-Else statement syntax if boolean condition: statements else: statements

  • Same as before except ...
  • Evaluate the body of the else if the if condition is False
  • The two alternatives are called branches

The flow chart

if x < y: x = x + 1 else x = x - 1 y = y - 1

Condi&on

Statement

Statement

False True x^ <^ y^?

x = x + 1

y = y - 1

No Yes

Statement x = x - 1

Simple example using elif conditional statement ...

  • Define a min3 function that returns minimum of 3 given values
  • For example, min3(1, 2, 3) and min3(3, 1, 2) should return 1

def min3(x, y, z): if x <= y and x <= z: return x elif y <= x and y <= z: return y else: return z