CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Pythonic Constructs


    Congratulations on making so much progress in 15-112!
    All of the core concepts you've seen so far are broadly applicable to programming and computer science...
    ...but Python has some neat tricks that we want to teach you before you start into your term projects!
    Bear in mind that these may not exist or may be *very different* in other languages, but this is Python Country.
    There's so much more to learn, but this is a handful of advanced topics that we find most useful. Read on!

  1. f-Strings
  2. Generators
  3. Helpful Modules

  1. f-Strings
    Note: This syntax only exists in Python 3.6 and above. It was introduced in this PEP. Newer feature proposals can be pretty interesting reads!

    Let's start off with something useful and not too tricky. String formatting is a pain, right?
    That's why the f-String is here to save us. This is Python-specific syntax, which is why we don't teach it to you first.
    String formatting in other languages will more likely resemble what you've already seen, but f-Strings pretty much explain themselves.
    #Note: Our brython version is pre-Python 3.6, so try this into your own editor! name="Mike" coProf="Kelly" course=112 sCount=[150,250] #The f here just tells Python to evaluate anything inside { } s=f"Hi {name}! How's {course} going?" print(s) #It will evaluate stuff like list indices just fine s2=f"I heard you have {sCount[0]} students in your lecture!" print(s2) #Sometimes it's handy to have simple expressions that add or combine things s3=f"{coProf} has {sCount[1]} so together you have {sCount[1]+sCount[0]}!" print(s3) #You can call functions and methods inside {} too! import random print(f"That's a {random.choice(['really big','huge','gargantuan'])} course!")


  2. Generators
    First, remember that functions are objects!
    Generators are functions that start running upon creation and have a sort of persistent state.
    Note the "yield" in the example. It's sort of like return, except when the function reaches yield, it waits to be called again.
    At this point, it will pass out any value it might have and continue running until it reaches the next yield.
    Generators can be handy for creating the next item or object in a sequence on-demand.
    def oddsGenerator(): print("Started a generator!") odd = 1 while True: yield odd #Hey what's this do? print("Yielded!") odd += 2 def oddsGeneratorDemo(): print("Demonstrating use of oddsGenerator()...") print(" looping over oddGenerator():") for odd in oddsGenerator(): # This is how generators are typically used print(odd) if (odd > 20): break print("Done!") print(" This time, using the next() function:") g = oddsGenerator() for i in range(11): # Explicitly calling the next() function is a less common # way to use a generator, but it still works, of course. print(next(g)) print("Done!") oddsGeneratorDemo()

  3. Helpful Modules
    Here's a list of modules we, as a staff, keep coming back to for day to day use
    1. csv: Reading and writing csv files (like spreadsheets)
    2. datetime: Managing and formating dates -- useful if you want to filter something by this semester, or last year
    3. collections: Dictionaries with default values, automatic dictionaries of counts, named tuples, and more
    4. matplotlib: Great for making graphs
    5. numpy: Fast scientific computation, matrices, Python's answer to Matlab
    6. scipy: Numpy and matplotlib's parent package. "numerical integration and optimization"