Selection Flashcards
Boolean values
True and False
A Boolean expression is an expression that evaluates to a Boolean value
Comparision operator
x == y # x is equal to y x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y
Logical operators
And Or Not
example:
x = 5
print x > 0 and x <10
n = 25
print n % 2 == 0 or n % 3 == 0
Precedences of operator
• Python will always evaluate the arithmetic operators first (exponentiation is
highest, then multiplication/division, then addition/subtraction)
• Next comes the comparison operators (sometime called relational operators)
• Finally, the logical operators are done last
If statement
if boolean expression:
statements_1 # executed if condition evaluates to True
else:
statements_2 # executed if condition evaluates to False
Unary selection
x = int(raw_input(“Please enter an integer: “))
if x < 0:
print “The negative number “, x, “ is not valid here.”
print “This is always printed”
Nested conditionals
if x < y: print "x is less than y” else: if x > y: print "x is greater than y” else: print "x and y must be equal”
Chained conditionals
if x < y: print "x is less than y” elif x > y: print "x is greater than y” else: print "x and y must be equal”
Boolean functions
def is_divisible(x, y): if x % y == 0: result = True else: result = False
return result
print is_divisible(10, 5)