import matplotlib.pyplot as plt """ DS2000: Programming with Data (Prof. Rachlin) Lecture 04 TODAY'S TOPICS: - Visualizing the Collatz Conjecture - Controlling program flow: if if..else if..elif..else if..elif..elif..else if..elif..elif..elif..else . . . etc. while loops. """ # ok, new content! # a big step for us today: conditional statements # %% # last time we talked about Boolean variables print(True) print(False) print(2 == 2) print(2 == 3) print(2 > 3) print(2 != 3) # %% # there are also 'logical operators' that we can use print(True and False) print(True or False) print(3 == 3 or 2 == 3) print(not 2 == 2) # %% x = 101 print(x > 1 and x <= 100) print(1 < x <= 100) # %% # by themselves, boolean statements may not seem *terribly* # useful, but they can be used to decide how a program behaves! # introducing: IF statements! if True: # do something print("hi!") # %% if 2 + 2 == 4: print("Python can do math!") else: print("You better switch to Java!") # %% # how about checking if a given number is a multiple of 10? x = 101 if x % 10 == 0: print(x, "is a multiple of 10.") else: print(x, "is *not* a multiple of 10.") # %% # note that we can actually leave out the else clause if we like x=100 if x == 100: print("x is 100!") print("I'm done") # %% # one thing we can do with if statements, for example, is check user-input # or other variables before an operation x = 100 z = 0 if z != 0: ratio = x / z print(ratio) else: print("cannot divide by 0!") print(ratio) # %% # let's come back to our hobbies example. as you may recall, we asked # for exactly three hobbies. how can we check that the user complies? hobbies = input("input 3 hobbies separated commas: ").split(",") if len(hobbies) == 3: # ... print("ok good!") else: print("I said 3!!") # %% # but this still assumes they respected comma separation. can we check this as well? hobby_input = input("input 3 hobbies separated commas: ") if "," in hobby_input: hobbies = hobby_input.split(",") if len(hobbies) == 3: # ... print("ok good!") else: print("I said 3!!") else: print("I said separated by commas!") # %% # sometimes there are multiple "special cases" that we want to treat separately # for example imagine we have a special message for two users (cathy and bob) # and a generic one for everyone else name = input("what is your name? ") if name == "Bob": print("Hi Bob.") elif name == "Cathy": print("Hi Cathy.") else: print("Hello stranger!") # %% while loops and counting to 10 x = 1 while(x <= 10): print(x) x += 1 # %% Count forever until you halt the program manually # Input/Output (I/O) is one of the slowest operations you can perform on a computer! x = 1 while(True): print(x) x += 1 #%% Here we are still counting one-by-one, but only printing every millionth # value to the console x = 1 while(True): if x % 1000000 == 0: print(x) x += 1