more expressions (slides)

CSc 110 More expressions

Review of arithmetic operations

  • + : plus

  • - : minus

  • * : multiple

  • / : divide

  • ** : power

  • // : divide and floor

  • % : modulos


Review of previous expressions

Evaluate the expressions below:

4 * 4 / 2 % 2
( 2 + 3 ) / ( 2 - 1.5)
3**3 // 7
5**2 + 25**0.5

Review of previous expressions

Evaluate the expressions below:

4 * 4 / 2 % 2
0.0
( 2 + 3 ) / ( 2 - 1.5)
10.0
3**3 // 7
3
5**2 + 25**0.5
30.0

Comparisons

  • What will be the result of the following expressions:
8 == 7
8 < 7
8 > 7
  • What are the other comparison operators?

Comparisons

Expressions with comparisons operators are evaluated to True or False

  • == equal
  • != different
  • >= greater or equal
  • > greater
  • <= less or equal
  • < less

Write a function

  1. Its name is odd and it takes one integer argument n
  2. It returns True if n is odd, False if n is even
print( odd(10) ) # False
print( odd(5) ) # True
print( odd(0) ) # False

Write a function – solution

def odd(n):
  return n % 2 == 1

def main():
  print( odd(10) ) # False
  print( odd(5) ) # True
  print( odd(0) ) # False
  
main()
False
True
False

Arithmetic vs Comparison Operators

Arithmetic Operators:

  • (expressions...), **, *, /, //, %, +, -

Comparison Operators:

  • ==, !=, >=, >, <=, <

Order of operations: arithmetic operators come before comparison operators.

Evaluate the expressions

Evaluation the expressions on your whiteboard and answer attendance questions on Gradescope.

3**2 < 25**0.5
9 % 3 == 8 % 2
10 // 3 > 9 // 3
14 % 2 != 15 % 2

Evaluation order

  • (expressions...)

  • ** : Exponentiation

  • *, /, //, % : Multiplication, Division, Floor Division and Remainder

  • +, - : Addition and subtraction

  • <, <=, >, >=, !=, == : Comparisons

  • not x : Boolean NOT

  • and : Boolean AND

  • or : Boolean OR

not

Expression Result
not True False
not False True

and

Expression Result
True and True True
False and True False
True and False False
False and False False

or

Expression Result
True or True True
False or True True
True or False True
False or False False

Evaluate the expressions

not 2**3 == 8 and 4 % 2 == 0
25*0.5 > 5**2 or 4 <= 2**2
4 % 2 == 0 or 4 // 0 == 0
4 % 2 != 1
not 0
not 1

Evaluate the expressions

not 2**3 == 8 and 4 % 2 == 0
False
25*0.5 > 5**2 or 4 <= 2**2
True
4 % 2 == 0 or 4 // 0 == 0
True
4 % 2 != 1
True
not 0
True
not 1
False