Python Programming · Week 4

Comparisons
and Conditionals

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

This week

A program that decides

so far

▼

every run: every line, top to bottom

this week · one program, four runs

Score: 95

Grade: A

Score: 72

Grade: C

Score: 45

Grade: F

Score: 150

A score is from 0 to 100.

it looks at the answer, then chooses what to do

1 · it asks a question about a value

comparisons

2 · it chooses which lines run

conditionals

comparisons and conditionals · this week's topic

This week

The whole program: fourteen lines

score = int(input("Score: "))

if 0 <= score <= 100:

if score >= 90:

print("Grade: A")

elif score >= 80:

print("Grade: B")

elif score >= 70:

print("Grade: C")

elif score >= 60:

print("Grade: D")

else:

print("Grade: F")

else:

print("A score is from 0 to 100.")

five questions

each one answers True or False

comparisons

if · elif · else

the answers choose which lines run

conditionals

fourteen lines · by the end of this video, you can read and write every one

Comparisons

Asking a question

>>> score = 95

>>> score >= 90

True

>>> score = 72

>>> score >= 90

False

six comparisons

<

less than

3 < 5 → True

>

greater than

3 > 5 → False

<=

less than or equal to

5 <= 5 → True

>=

greater than or equal to

7 >= 10 → False

==

equal to

5 == 5 → True

!=

not equal to

5 != 3 → True

a comparison asks a question · the answer is True or False

Comparisons

= stores, == asks

one =

>>> x = 5

(nothing comes out)

stores 5 in x

two ==

>>> x == 5

True

asks: is x equal to 5?

>>> 5 = x

SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

one = stores · two == ask a question

Comparisons

True and False

operators · two values in, one value out

72 + 60 → 132

72 >= 60 → True

>>> type(3 < 5)

<class 'bool'>bool: the kind for True and False

>>> passed = 72 >= 60

>>> passed

Trueright side first, then store

>>> light_on = True

>>> light_on

Truetyped by hand, like 3 or "Kim"

>>> light_on = true

NameError: name 'true' is not defined. Did you mean: 'True'?

four kinds so far

int 3
float 3.0
str "3"
bool TrueFalse

no quotes · a capital first letter

Comparisons

>>> 0.1 + 0.2 == 0.3

False

week 2: 0.1 + 0.2 → 0.30000000000000004

== asks “exactly equal?” · a float is often a tiny bit off

Comparisons

Compare the distance

absolute value

>>> abs(-3.5)

3.5

>>> abs(3 - 5)

2

abs gives the absolute value

∣a−b∣|a - b| in Python: abs(a - b)

The two values from the last slide: 0.1 + 0.2 and 0.3.

>>> abs(0.1 + 0.2 - 0.3)

5.551115123125783e-17the distance: almost zero

>>> abs(0.1 + 0.2 - 0.3) < 0.000001

Trueclose enough

0.000001 the tolerance: how close counts as equal · you choose it

floats: do not ask “exactly equal?” · ask “close enough?”

Conditionals

Choosing a path

so far, at the prompt

>>> score >= 90 → True and that is all

in a program

True → print("Grade: A") the answer chooses what runs

a program, drawn as paths

True False score = int(input("Score: ")) score >= 90 print("Grade: A")print("Well done!") print("Done")

Score: 95

Grade: A

Well done!

Done

Score: 72

Done

True: the side path runs · False: it is skipped · then both paths go on together

Conditionals

if

The same program, written in Python.

a file, run with the Run button

score = int(input("Score: "))

if score >= 90:

print("Grade: A")

print("Well done!")

print("Done")

if, a condition, a colon

the condition is the question: True or False

the block: indented under the if, 4 spaces

it belongs to the if: both lines run only when True

print("Done"): no indent

outside the block: it runs every time

Conditionals

Common mistakes with if

no colon

score = 95
if score >= 90
    print("Grade: A")
SyntaxError: expected ':'

a loud error · read the last line

no indent

score = 95
if score >= 90:
print("Grade: A")
IndentationError: expected an indented block after 'if' statement on line 2

a loud error

Well done! not indented

score = 72
if score >= 90:
    print("Grade: A")
print("Well done!")
Well done!

printed for 72: outside the block · no error, and a wrong answer

the block is the indented lines · VS Code adds the 4 spaces after a colon

Conditionals

else

When the condition is False.

score = int(input("Score: "))
if score >= 60:
    print("Pass")
else:
    print("Fail")

else has no condition, just a colon

True False score = int(input("Score: ")) score >= 60 print("Pass") print("Fail")

Score: 72

Pass

Score: 45

Fail

if or else · exactly one of the two blocks runs

Conditionals

elif

Short for “else if”: one more question, asked only when the ones above were False.

score = int(input("Score: "))
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

the user typed 85

False True True False True False True False score >= 90 score >= 80 score >= 70 score >= 60 Grade: A Grade: B Grade: C Grade: D Grade: F

from the top · stops at the first True · the rest are skipped · else: when none is True

Conditionals

Order matters

The same questions, upside down.

score = int(input("Score: "))
if score >= 60:
    print("Grade: D")
elif score >= 70:
    print("Grade: C")
elif score >= 80:
    print("Grade: B")
elif score >= 90:
    print("Grade: A")
else:
    print("Grade: F")

95 prints Grade: D · no error, and a wrong answer: the worst case

the user typed 95

True False True False True False True False score >= 60 score >= 70 score >= 80 score >= 90 Grade: D Grade: D Grade: C Grade: B Grade: A Grade: F

Python stops at the first True · so ask about 90 before 80, 80 before 70

Comparisons

A typed score is a string

score = input("Score: ")
if score >= 90:
    print("Grade: A")

Score: 95

TypeError: '>=' not supported between instances of 'str' and 'int'

quotes around 90?

if score >= "90":

no error now: two strings

>>> "95" >= "90"

True

>>> "100" >= "90"

Falsestrings: character by character · 1 comes before 9

>>> "Kim" == "kim"

Falsea capital K is a different character

a number typed by the user · change it to a number first, then compare

Combining bools

not, and, or

Operators on True and False: bools in, a bool out.

not

turns True into False, and False into True

not True → False not False → True

and

True only when both sides are True

True and True → True True and False → False

or

True when at least one side is True

True or False → True False or False → False
Combining bools

Joining comparisons in an if

score is 85

if score >= 0 and score <= 100:

→ True and True → True

the block runs

if score < 0 or score > 100:

→ False or False → False

the block is skipped

if 0 <= score <= 100:

a range, as in math: 0≤score≤1000 \le \text{score} \le 100

exactly the same as score >= 0 and score <= 100

Combining bools

Numbers as True or False

0 → False
7-3100… → True

every number except 0

in not, and, or

not 0 → not False → True 7 and True → True and True → True -3 and False → True and False → False 0 or False → False or False → False

Python allows this · but give not, and, or real bools: comparisons such as x != 0

Combining bools

A silent trap

x = 5
if x == 1 or 2:
    print("x is 1 or 2")
x is 1 or 2

x is 5 · no error, and a wrong answer

how Python reads it: two sides, each on its own

x == 1 or 2 False True

→ False or True → True

the right side is always 2: True for every x

a whole comparison on each side

if x == 1 or x == 2:

x is 5: False or False → False · nothing is printed

Combining bools

Order of operations, extended

first to last

  1. 1( )
  2. 2**
  3. 3* / // %
  4. 4+ -
  5. 5< <= > >= == !=
  6. 6not
  7. 7and
  8. 8or

grey: from week 2

step by step

x = 12

x > 10 and x % 2 == 0

12 > 10 and 0 == 0

arithmetic first: 12 % 2 is 0

True and True

then the comparisons

True

then and

Not sure? Add parentheses.

Conditionals

An if inside an if

score = int(input("Score: "))

if 0 <= score <= 100:

if score >= 90:

print("Grade: A")

elif score >= 80:

print("Grade: B")

elif score >= 70:

print("Grade: C")

elif score >= 60:

print("Grade: D")

else:

print("Grade: F")

else:

print("A score is from 0 to 100.")

inside the if True False True False True False 0 <= score <= 100 A score is from 0 to 100. score >= 90 Grade: A score >= 80 Grade: B ⋮

an if inside an if works like and

if 0 <= score <= 100:

if score >= 90:

print("Grade: A")

the same as

if 0 <= score <= 100 and score >= 90:

an inner if runs only when its outer block runs · so a grade is given only for a score from 0 to 100

This week

The whole program

score = int(input("Score: "))
if 0 <= score <= 100:
    if score >= 90:
        print("Grade: A")
    elif score >= 80:
        print("Grade: B")
    elif score >= 70:
        print("Grade: C")
    elif score >= 60:
        print("Grade: D")
    else:
        print("Grade: F")
else:
    print("A score is from 0 to 100.")

←int(): the typed score, as a number

←the range first · a short form of and

←an if inside the if · the grade chain

←from the top · stops at the first True

←every comparison above was False

←the score is not from 0 to 100

fourteen lines · every idea on them comes from this video

This week

Which lines run?

score = int(input("Score: "))

if 0 <= score <= 100:

if score >= 90:

print("Grade: A")

elif score >= 80:

print("Grade: B")

elif score >= 70:

print("Grade: C")

elif score >= 60:

print("Grade: D")

else:

print("Grade: F")

else:

print("A score is from 0 to 100.")

four typed values

typed 95

Grade: A

typed 85

Grade: B

typed 59

Grade: F

typed 150

A score is from 0 to 100.

last week, every line ran every time
now the typed value chooses which lines run

Next steps

Next: the practice video.

Have Python open. Type everything with me.

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space