Arithmetic

Calvin (Deutschbein)

W3Mon: 8 Sep


Announcements

  • By MONDAY 11:59 PM: "Problem Set 1: Karel" assignment.
    • One problem (probably) using "def" and "for"
    • One problem using at least "while" and maybe the other three.
  • Sections reminder: Wed & Thurs PM.
    • Problems: email jjrembold@, you may cc ckdeutschbein@
  • By NEXT MONDAY 11:59 PM: "Problem Set 2: Checkers" assignment.
    • One Karel problem (probably) using "if" and "while"
    • One Python problem using arithmetic and (probably) "for"
    • One writing problem.

Today

  • Do we need homework screencapture slides?
    • Doing homework: It's fun.
  • I can live-code any homework questions.
    • Let's crush this homework... together.
  • Introducing Python, cont.

      if / elif / else
      + - * // / % ** - # operators
      = == # assignment vs comparison
      return

if / elif / else

  • We know 'if', but 'else' is very useful on Checkerboard
  • E.g., place beeper after moving ONLY if moving from an unbeeped square. def check_move(): if no_beepers_present(): move() put_beeper() else: move()
  • What happens if we: import karel def main(): while front_is_clear(): check_move()

if / elif / else

  • 'elif', short for 'else if', allows longer, more complicated checks. def sign_check(x): if x < 0: print("negative") elif x > 0: print("positive") else: print("zero")

Today

  • Introducing Python, cont.

      if / elif / else # ✓
      + - * // / % ** - # operators
      = == # assignment vs comparison
      return

Operators

  • Most arithmetic in Python is "as expected" with a few differences.
  • Easy ones:
    Additiona + b
    Subtractiona - b
    Multiplicationa * b
    Divisiona / b
  • Weirder ones:
    Integer Divisiona // bLeaves a "Remainder"
    Moduloa % b calculates the "Remainder"
    Exponentiationa ** bNote: The caret ^ is something else

Operators

  • Most arithmetic in Python is "as expected" with a few differences.
  • Easy ones:
    Additiona + b
    Subtractiona - b
    Multiplicationa * b
    Divisiona / b
print(1 + 2) print(1 - 2) print(1 * 2) print(1 / 2) 3 -1 2 0.5

Note: Division takes whole numbers (integers) and returns numbers with a decimal ('floats').

Operators

  • Most arithmetic in Python is "as expected" with a few differences.
  • Weirder ones:
    Integer Divisiona // bLeaves a "Remainder"
    Moduloa % b calculates the "Remainder"
    Exponentiationa ** bNote: The caret ^ is something else
print(5 // 2) print(5 % 2) print(5 ** 2) print(5 ^ 2) 2 1 25 7

It may seem weird, but % ("modulo" or "remainder") is extremely useful, and I use it more than anything except maybe + ("plus" or "addition")

Two divisions

  • Integer division // is nice when we might want to calculate a value then loop that many times. for i in range(5//2): print(i)
  • That is allowed, this isnt: for i in range(5/2): print(i)
  • You'll see this: Traceback (most recent call last): File "<stdin>", line 1, in <module>> TypeError: 'float' object cannot be interpreted as an integer

type()

  • If you ever aren't sure what something will be, ask Python with "type()"
    print(type(5/2)) print(type(5//2)) print(type(5)) print(type(5.0)) <class 'float'> <class 'int'> <class 'int'> <class 'float'>

    'for' loops need "<class 'int'>"

Today

  • Introducing Python, cont.

      if / elif / else # ✓
      + - * // / % ** - # ✓
      = == # assignment vs comparison
      return

=

  • We use '=', which I term 'single equals' or 'assignment', to 'assign' a value (like 7) to a variable (like x). x = 7
  • Then x does all the things seven does.
    print(x) print(7) print(x+6) 7 7 13
  • It means "make this equal to that"
  • Be advised, this is not allowed: 7 = x

    (We aren't allowed to set seven equal to any other value, like 3 or "hi")

Weird thing

  • We are allowed to set a variable, like x, equal to some arithmetic over x, like x = 1. x = 7 x = x + 1 print(x)
  • This would give 8, and is useful to e.g. count things.
  • Imagine if we could count how many beepers Karel placed, or how many moves. def ten_even_numbers(): x = 0 for i in range(10): x = x + 2 print(x)

==

  • We use '==', which I term 'doubles equals', 'equality test', or 'comparison', to 'check' if two things, either values or variables, are equal.
  • '==' is kind like '+': given two things, it gives back a value - but that value is either true or false.
    x = 7 print(7 == x) print(x == 7) print(6 == x) print(1 == 2) print(x + 6) # Blank line to line up. True True False False 13

Comparison Operators

  • Besides double equals, many other tests for equality/inequality.
  • Easy ones:
    Greater-than-or-equala >= b
    Less-than-or-equala <= b
    Not equala != b
    Greater-thana > b
    Less-thana > b
print(1 >= 2) print(1 <= 2) print(1 != 2) print(1 > 2) print(1 < 2) print(1 < 1) print(1 <= 1) False True True False True False True

Checking Numbers

  • We check if numbers are even... def is_even(x): # check if x is even if x % 2 == 0: # no remainder when divided by two print("even") elif x % 2 == 1: print("odd") else: print("not a whole number")
  • Test it:
    print(is_even(2)) print(is_even(1)) print(is_even(1.5)) even odd not a whole number

Today

  • Introducing Python, cont.

      if / elif / else # ✓
      + - * // / % ** - # ✓
      = == # ✓
      return

Return

  • Print is how the computer tells us things.
  • Sometimes we want it to tell itself things, like:
    • Whether some number is divisible by another number...
    • The greater of two numbers..
  • Print has a limitation here.
    def is_even(x): print(is_divisible_by(x,2)) def bigger(x,y): if x > y: print(x) else: print(y)
  • What if I want to assign some variable 'c' to be the greater of 'a' and 'b'?

Return

  • If we write "is_divisible_by" like this: def is_divisible_by(value,divisor): print(value % divisor == 0) # has no remainder
  • This code won't work: def is_even(x): print(is_divisible_by(x,2))
  • It will print out "None", which is probably not what you want to see.

Return

  • Why? 'is_divisible_by' prints True or False, but doesn't tell 'is_even' what it prints.
  • The way to 'tell' a computer what happened in a def/function is with 'return': def is_divisible_by(value,divisor): return (value % divisor == 0) # has no remainder
  • We use return on its own line, and it doesn't need parenthesis or colons. def is_even(x): return is_divisible_by(x,2)
  • Something like 'front_is_blocked()" returned either True or False.

Return

  • Until you write code with zero errors on the first time...
  • You should never write a function (def) with no return.
  • Most programers expect Python to return when it does not. def is_divisible_by(value,divisor): # checks if value is evenly divided by divisor check = value % divisor == 0 # compare remainder to zero if check: # print what we find print("Value is evenly divided by divisor") else: print("Value is not evenly divided by divisor") # do not forget to return return check
  • Print is for you to read, return is for the computer or for you to use.

Exercise

  • Do "Problem Set 1: Karel"
    • Use comments
    • The first problem "newspaper" benefits from functions, and perhaps for loops
      • It is possible, but annoying, to do without either
    • The second problem, "painting" benefits from 'while' loops (and could use 'if')
      • I used four (4) 'while' loops, and no 'if' statements or 'for' loops

Announcements

  • By MONDAY 11:59 PM: "Problem Set 1: Karel" assignment.
    • One problem (probably) using "def" and "for"
    • One problem using at least "while" and maybe the other three.
  • Sections reminder.
  • By NEXT MONDAY 11:59 PM: "Problem Set 2: Checkers" assignment.
    • One Karel problem (probably) using "if" and "while"
    • One Python problem using arithmetic and (probably) "for"
    • One writing problem.