ميـــحرلا نحنحنرلا للوللوا مــسب Fundamentals of Programming Python Session # 5 By: Saeed Haratian Spring 2016
Outlines Boolean Algebra Conditional Statement Chained conditionals Nested conditionals Example : Bar Chart Return Values Example : Distance
Boolean Algebra Boolean Value Boolean Expression Logical Operators Opposite Operators Boolean Operators Truth tables
Simplifying Boolean Expressions x and False == False False and x == False y and x == x and y x and True == x True and x == x x and x == x
Simplifying Boolean Expressions … x or False == x False or x == x y or x == x or y x or True == True True or x == True x or x == x
Simplifying Boolean Expressions … De Morgan Law's not (x and y) == ( not x) or ( not y) not (x or y) == ( not x) and ( not y)
Conditional Statement
Conditional Statement … if BOOLEAN EXPRESSION: STATEMENTS_1 else : STATEMENTS_2
Omitting the else clause
Chained conditionals if x < y: STATEMENTS_A elif x > y: STATEMENTS_B else : STATEMENTS_C
Chained conditionals …
Nested conditionals
Nested conditionals … if x < y: STATEMENTS_A else : if x > y: STATEMENTS_B else : STATEMENTS_C
The return statement def print_square_root(x): if x <= 0: print("Positive numbers only, please.") return result = x**0.5 print("The square root of", x, "is", result)
A Turtle Bar Chart
Return Values def area(radius): b = 3.14159 * radius**2 return b def area(radius): return 3.14159 * radius * radius
Return Values … def absolute_value(x): if x < 0: return -x else : return x def absolute_value(x): if x < 0: return -x return x
Return Values … def absolute_value(x): if x < 0: return -x elif x > 0: return x
Return Values … def find_first_2_letter_word(xs): for wd in xs: if len(wd) == 2: return wd return "" >>> find_first_2_letter_word(["This","is","a","parrot"]) ’is’ >>> find_first_2_letter_word(["I","like","cheese"]) ’’
Example : Distance def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx*dx + dy*dy result = dsquared**0.5 return result
Example : Distance … import math def distance(x1, y1, x2, y2): return math.sqrt( (x2-x1)**2 + (y2-y1)**2 )
Recommend
More recommend