Math, Comparison and Boolean Operators Math operators
|
Math Operators Math operators include standard notation for add, subtract, multiply and divide. You can also use parentheses to indicate the order in which operations should be carried out. Math operators can be used on number data types like integer and float. (Strings can be added together, but if you try to use most math operators on strings, you will get an error message.) For example: >>> print 5-9 -4 >>> print 5+3/2+7*2 20 >>> print 5+(3/(2+7))*2 5 |
jump
to top |
Comparison Operators
Comparison operators allow you to compare two different expressions. Comparisons evaluate to either true, which is represented by the integer 1, or false, which is represented by the integer 0. You can use comparison operators on integer, float or string data types. It is possible to compare strings because the computer encodes a string as a sequence of numbers that represent each character. (Of course, even though you can do it, comparing whether one string is greater than or less than another string may not be a very useful comparison!) For example: >>> print 4 == 5 0 >>> print 6 > 2 1 >>> print "rrr" == "rrr" 1 Because true and false statements are represented by the integers 1 and 0, you can also use standard math operators with comparison statements. For example: >>> print (6 > 2) + (4 == 4) 2 |
jump
to top |
Boolean Operators
Boolean operators make it possible to evaluate more complex expressions to either true (1) or false (0). When you join multiple expressions with the boolean operator and, BOTH expressions must be true for the combined expression to evaluate to true. >>> print (5 == 3) and (4 == 4) 0 >>> print (5 >= 5) and ("rrr" != "eee") 1 When you join multiple expressions with the boolean operator or, then only ONE of the expressions must be true for the combined expression to be true; however, if both are true, the expression will still evaluate to true. Expressions joined with the or operator only evaluate to false if ALL the expressions evaluate to false. >>> print (5 > 2) or (5 == 3) 1 >>> print ("abc" != "xyz") or (1 > 3) or (65 != 65) 0 |
jump
to top |