simplifications csci 1101b modules and commonsharmon/static/1101/lecs/1101_lec9.pdf ·...
TRANSCRIPT
Modules and Common Simplifications
CSCI 1101B
Warm-up Exercise
Classic Wire Dilemma Trope
We need a working function that tells us how to disable the device.
Credit: ARMA 2, cobra4v320
Warm-up: Disable the Hacking Device
def get_advice(red_wire, num_wires) instruction = “” if red_wire = True: instruction = “Cut the red wire!” elsif num_wires = 0 or < 0: instruction = “Press the off button!” else: instruction = “Some days you just can’t get rid of a hacking device!” return instruction
Can you find all of the problems with this function?
Warm-up: Disable the Hacking Device
def get_advice(red_wire, num_wires): instruction = “” if red_wire == True: instruction = “Cut the red wire!” elif num_wires == 0 or num_wires < 0: instruction = “Press the off button!” else: instruction = “Some days you just can’t get rid of a hacking device!” return instruction
Today’s Outline
● Common Simplifications
● Making and Importing Modules
Part I
Common Simplifications
Top Factoring
if test: blah() some_thing()else: blah() some_other_thing()
Top Factoring
blah()
if test: some_thing()else: some_other_thing()
Bottom Factoring
if test: some_thing() blah()else: some_other_thing() blah()
Bottom Factoring
if test: some_thing()else: some_other_thing()blah()
Boolean Assignment
if test:
b = True
else:
b = False
Boolean Assignment
if test:
b = True
else:
b = False
(Just say b = test instead!)
Flattening Nested Ifs (usually!)
if a == 0: print(“Not quadratic”)else: if discriminant >= 0: # Compute roots else: print(“Roots are imaginary”)
Flattening Nested Ifs (usually!)
if a == 0: print(“Not quadratic”)elif discriminant < 0: print(“Roots are imaginary”)else: # Compute roots
Temporary Boolean Variables
● Readability rather than simplification
if not ((row >= 0 and row < 8) and (col >= 0 and col < 8)): print(“Invalid chess location”)
vs.
is_valid_row = row >= 0 and row < 8is_valid_col = col >= 0 and col < 8if not is_valid_row or is not is_valid_col: # De Morgan’s laws help too! print(“Invalid chess location”)
Part III
Making and Importing Modules
Different Ways to Import (Review)
● Can import the entire moduleimport mathprint(math.pi) # imported data valueprint(math.sqrt(9)) # imported function
● OR we can import selected data/functionsfrom math import pi, sqrtprint(pi)print(sqrt(9))
Importing Custom Modules
To import your own files, just write:
import your_filename
Modules - Main Function
if __name__ == “__main__”:
Modules - Main Function
def main(): # Main function code, for example… test_1() test_2()
if __name__ == “__main__”: main()
Summary
● You can import your own files (modules) now!
● For clean code, simplify your conditional statements and use:
if __name__ == “__main__”: