More expressions (class slides)

CSc 110 More expressions

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 two 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

Write a function called odd that takes one integer argument n and returns True if n is odd, False if n is even

print( odd(10) ) # False
print( odd(5) ) # True
print( odd(0) ) # False

Submit your odd.py file to attendance on Gradescope

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

Comparisons

Expressions with comparisons operators are evaluated to True or False

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

Evaluate the expressions

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

Evaluate the expressions

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

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

and, or, not

  • What will be the result of the following expressions:
not True

True and True
True or True

False and True
False or True

False and False
False or False

and, or, not

  • What will be the result of the following expressions:
not True
False
True and True
True
True or True
True
False and True
False
False or True
True
False and False
False
False or False
False

Evaluation order

  • (expressions...)

  • ** : Exponentiation

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

  • +, - : Addition and subtraction

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

  • not x : Boolean NOT

  • and : Boolean AND

  • or : Boolean OR

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