CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Pythonic Constructs
-
Congratulations on making so much progress in 15-112!
- f-Strings
- Generators
- Helpful Modules
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!
- 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!")
- 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() - Helpful Modules
Here's a list of modules we, as a staff, keep coming back to for day to day use- csv: Reading and writing csv files (like spreadsheets)
- datetime: Managing and formating dates -- useful if you want to filter something by this semester, or last year
- collections: Dictionaries with default values, automatic dictionaries of counts, named tuples, and more
- matplotlib: Great for making graphs
- numpy: Fast scientific computation, matrices, Python's answer to Matlab
- scipy: Numpy and matplotlib's parent package. "numerical integration and optimization"