The ABCs of Python: “with,” “yield” and the magic of egg production

We arrive at our last two Python keywords: with and yield. We could get all esoteric on you with these two words, but we’ll try to keep it simple.

with

Be patient. There’s a payoff. The keyword with  “is used to wrap the execution of a block of code within methods defined by the context manager,” according to programiz. The official documentation states,  “[T]he ‘with‘ statement clarifies code that previously would use try…finally blocks to ensure that clean-up code is executed.”

Got it? If not, that’s okay. The bottom line is that you can use with to toss text into another file and then make sure that file is closed at the end of the process. Try this: create an ordinary text file called “write_to.txt” and put it in the same directory as your other python files. Close that file. Now, use your editor to write the following code and then run it.

with open('write_to.txt', 'w') as a_file:
    a_file.write('I am writing this into the write_to document')
    print("I wrote to 'write_to'")

In addition to printing “I wrote to ‘write_to'” into your shell, this code should print “I am writing this into the write_to document” into (you guessed it) that “write_to.txt” document you just created. To check, go open that doc up and see what’s there.

Presto!

 yield

Okay, this is the last keyword on our list (yay!). Remember return? Well, yield is a more powerful return (sort of). When you use return in a function, you produce just one thing (even if it’s one long list). When you use yield, you can produce a virtual deluge of them if you like. BUT you produce them one at a time so you don’t wind up with some hellaciously large list.

If you’re confused, just hang on a sec. We’ll try to make it pretty concrete.

The keyword yield produces a doo-dad called a generator. A generator, as you might expect, generates stuff. Here’s an example that is modified but based on the elegant one provided by the programiz folks:

def generates_eggs():
    e = "egg "
    for i in range(20):
        yield i*e

g = generates_eggs()
for i in g:
    print(i)

If you run that, you get a lot lines made up of the word “egg.” Each line is a word longer than the previous one because the function using yield generates an ever larger number (up to 19, in this case) of eggs. Therefore, you should get something that looks like this:

egg
egg egg
egg egg egg
egg egg egg egg
egg egg egg egg egg
egg egg egg egg egg egg
egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg
egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg egg

Back in the day, you might have called that concrete poetry. But today we’ll just call it a whole heckova lot of eggs, brought to you by yield.

For a more sophisticated explanation of yield, check out How to Use Generators and yield in Python.

And for much fuller explanation of with, check out The Python “with” Statement by Example.

Featured image by Edithobayaa1: a crate of eggs in Ghana

The ABCs of Python: “not,” “or,” “and” in coded cummings

The Python keywords not, or and and (the last of which we already discussed  once here) are not just critical parts of the language but critical concepts in their own right. Together, these three are the foundation of Boolean logic, which extends well beyond the world of Python into other features of our modern landscape.

For example, periodical search engines tend to run on Boolean logic, allowing users to refine their searches through these three terms. And, in electronics there are Boolean-based logic gates that perform logical inputs in order to produce a single logical output.

In Python, Booleans work in much the same way. Using them in any given function as operators, you can handle all kinds of inputs that can be distilled into a single True or False statement.

By the way, beginners may get confused about how statements with these operators work. If you have a line such as “if dog and cat,” what you really mean is “if dog and cat are both True.” Python assumes the “are both True” part.

Let’s say, for example, that you create variables called “stars” and “sky” and assign them some value. Then, if you put down the line “if stars and sky,” Python will automatically recognize that statement as being True. Like so:

stars = 1000000000
sky = 1
if stars and sky:
    print("let there be light!")

and

An and is used for the process of conjunction, which means two or more things need to be True for a statement to be True, as in:

dog = True
cat = True
if dog and cat:
    print ("yep, you have a dog and a cat in your house")

#this will print "yep, you have a dog and a cat in your house"

or

Or signifies the process of disjunction. That is, only one of various statements needs to be True for the whole statement to be True.

dog = False
cat = True
if dog or cat:
    print ("yep, you have a dog or a cat in your house")

#this prints "yep, you have a dog or a cat in your house"

not

Not signifies the process of  negation, of course. In this case, negative statements are True, as counter-intuitive as that sounds.

dog = False
cat = False
if not dog or cat:
    print ("yep, you don't have either a dog or a cat in your house")

#this prints, "yep, you don't have either a dog or a cat in your house"




 While Not ee cummings

Remember “while”? Well, we can combine “while” and “not” to create code that keeps looping back until we get something right.

I’m an ee cummings fan. He’s playful, lyrical, witty, experimental and devastatingly creative all at once. When I started thinking about Booleans, I was reminded of his poem “as freedom is a breakfast food”, which is jam-packed with “ands and “ors“. Then I thought maybe we could use “not” to play around with the poem. Here’s the poem’s first stanza:

as freedom is a breakfastfood

or truth can live with right and wrong

or molehills are from mountains made

—long enough and just so long

will being pay the rent of seem

and genius please the talentgang

and water most encourage flame

As an homage to cummings, I wrote the following function:

def cummings():
    freedom = ''
    truth = ''
    molehills = ''
    while not (freedom == "as freedom is a breakfast food"):
        print ("As freedom is a what?")
        freedom = input()
    while not (truth == "or truth can live with right and wrong"):
        print ("Or truth can live with what?")
        truth = input()
    while not (molehills == "or molehills are from mountains made"):
        print ("Or molehills are made from what?")
        molehills = input()
   print ("long enough and just so long")
   print ("will being pay the rent of seem")
   print ("and genius please the talentgang")
   print ("and water most encourage flame")

cummings()

By combining “while” and “not,” you can create a function that continues to ask you questions until you get the answer right. That is, while you do not have the right answer, you keep getting the same query. That’s what “input ()” does.

Remember, you can use Control-C to get out of a loop if you’re stuck. When you run this code by calling the function (that is, by adding “cummings ()”), you need to type in the first three lines of the stanza correctly to get the rest of the stanza printed out. Here’s how the output looks in your IDLE shell:

As freedom is a what?
as freedom is a breakfast food
Or truth can live with what?
or truth can live with right and wrong
Or molehills are made from what?
or molehills are from mountains made
long enough and just so long
will being pay the rent of seem
and genius please the talentgang
and water most encourage flame

PS: By the way, for those inclined toward irony, there actually is a breakfast brand called Freedom these days. I imagine cummings would have been amused. Something about it reminds me of another cummings line: “The snow doesn’t give a soft white damn whom it touches.”

Featured image from New York World-Telegram and the Sun staff photographer: Albertin, Walter, photographer.