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

This is introductory course for computer science. Its about basic concepts involving in computer programming, structure and working. Key points in this lecture handout are: Conditionals, Boolean Expressions, Logical Expressions, Basic Conditional Execution, Conditional Statement Syntax, Boolean Condition, Flow Charts

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2012)
Today ...
Boolean expressions (cont.)
Conditionals
S. Bowers 1 of 7
pf3
pf4
pf5

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