Relational and Boolean Operators CSIS 1595: Fundamentals of Programming and Problem Solving 1
Relational Operators Conditional expressions of form operand1 relationalOperator operand2 – Comparing operand1 and operand2 in some way Python relational operators: >greater than <less than <= less than or equal to >=greater than or equal to != is not equal to ==is equal to (not same as =)
Relational Operators Example
Relational and Arithmetic Operators Can combine in same condition x = 3 y = 7 if x * 2 < y + 1: … Precedence: Arithmetic operators done first 1.Evaluate expressions on either side of relational operator to get 2 values 2.Evaluate relational operator in term of those 2 values to get either True or False
Relational Operators and Types Some operators only make sense for certain types – Numbers: > = <= == != Be careful with floats and == – Strings: == != password = input(“Enter password:”) if password == “xyzzy”: … – Can do > = <= but get strange results Can only compare similar types “Fred” > 2 error
Equality and Float Type == checks whether operands are same number – Can be problem with floats due to lack of precision x = 5 * 2/3 y = 2/3 * 5 if x == y: … False
Equality and Float Type Goal: determine whether x and y are “close enough” – Within some “margin of error” of each other Method: – Compute difference between the values – Take absolute value Difference may be positive or negative Have built-in fabs function – Compare with “margin of error” using < instead of == x = 5 * 2/3 y = 2/3 * 5 if math.fabs(x – y) < : …
Boolean Logic Some problems involve multiple conditions – “x must be between 1 and 10” – “either a or b must not be 0” Can create using and, or, other boolean operators – x must be greater than or equal to 1 and less than or equal to 10 – a must not be 0 or b must not be 0
Boolean Expressions Syntax: conditionalExpr booleanOp conditionalExpr Examples: – if x >= 1 and x <= 10: … – if a != 0 or b != 0: …
Boolean Operators and: true if both operands are true – true and true true – true and false false – false and true false – false and false false or: true if either operands are true – true or true true – true or false true – false or true true – false or false false
not Operator not: Reverses boolean value of unary operand – Syntax: not conditionalExpr not true false not false true – Example: if not x > 0: … Can often just use “opposite” relational operator – if x <= 0: … Commonly used to reverse value of boolean function – if not math.isfinite(x): …
Precedence and Boolean Operators Precedence: 1.Evaluate arithmetic expressions in conditional expressions 2.Evaluate conditional expressions to True or False 3.Evaluate boolean operators using those values 1. not evaluated first 2. and evaluated next 3. or evaluated last – Can always use () if not sure!