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 technological 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 the Python keywords of “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.

The ABCs of Python: “global,” “nonlocal,” and Celebs in Vegas

Here is a discussion of two more keywords in Python. These are less well-known and widely-used than a lot of the other Python keywords but have their uses in specific circumstances:

global

To understand this term, you must realize that a variable that is changed inside a function will not be recognized outside the function. Let’s imagine a celebrity visits Vegas and goes into serious bout of debauchery, adding an extra 100 pounds to his usual trim frame of 150 pounds. Now, check out the following code:

def celeb_change():
    celeb = 150
    celeb = celeb + 100
    return celeb
print (celeb_change()) #this will print 250
print (celeb) #but this will give an error message, saying, 
            #“NameError: name 'celeb' is not defined”

When we print the function called celeb_change(), it’ll tell us celeb is equal to 250. But if we then ask Python what the value of celeb is outside the realm of that function, it won’t have a clue. Any value changes only happen locally. It’s sort of like, “What happens in Vegas, stays in Vegas.” Except, in this case, it’s what happens in a function stays in a function.

But we can change this. We can, in essence, broadcast the changes that were made in the function, saying, “Hey, we gave a value to celeb within a function but we want this to be remembered outside of that function.” I suppose it’s like some paparazzi taking a video of that celebrity after he gained the extra 100 pounds and and uploading it to YouTube. Suddenly, what happened in Vegas did not stay in Vegas. Here’s how you can do that:

def celeb_change():
    global celeb #this line makes the existence and value  
                 #of celeb known outside this function
    celeb = 150
    celeb = celeb + 100
    return celeb
print (celeb_change()) #this will still print 250
print (celeb) #but this will also print 250 now because 
              #the celeb is known to have a value of 
              #250 even outside the function

nonlocal

So, then, what in the heck is nonlocal? Well, let’s say we have a local Vegas celeb who wanders out of his neighborhood but isn’t really going far: just over to another nearby neighborhood.  The local paparazzi don’t worry if he gets out of line because they know he’s not-quite-local but not a complete stranger to Vegas either. Here’s some code to help us understand. Before you run it, though, “comment out” the prior code (to do this in IDLE, you can use Alt-3).

def big_celeb():
    celeb = 250
    print('heavy celeb weighs: ', celeb)
    def normal_celeb():
        nonlocal celeb
        celeb = celeb - 75
        print('normal celeb weighs: ', celeb)
        def skinny_celeb():
            nonlocal celeb
            celeb = celeb - 25
            print('thinner celeb weighs: ', celeb)
        skinny_celeb()
    normal_celeb()
big_celeb()

print ('celeb outside the function is: ', celeb) 
#the print statement above will throw an error code like this:
#NameError: name 'celeb' is not defined
#That's because celeb is nonlocal rather than global

This is what will print out:

heavy celeb weighs: 250
normal celeb weighs: 175
thinner celeb weighs: 150
Traceback (most recent call last):
    File "C:/Python34/global and nonlocal.py", line 34, in <module>
      print ('celeb outside the function is: ', celeb)
NameError: name 'celeb' is not defined

What you see here are some nested functions. That just means, of course, that one function contains another function as part of it (and, in this case, there’s a third function is nested in there as well). Now, we want each of these three functions to “remember” that there’s a variable called “celeb” and its value the last time it was used. If we didn’t stick the words “nonlocal celeb” into the second and third functions, Python would throw an error. (Try it and see). We’re saying, “Hey, you nested functions, remember that this is the same celeb as the one mentioned in the previous part of the function.”

But, this does not mean that celeb will still be recognized outside the three nested functions. That is, the variable has not gone global. So, what happened in Vegas still stays in Vegas.

For more on global and nonlocal, see GeekforGeeks.

The ABCs of Python: “def,” “class,” and leopards

This post is about the Python keyword def, not to mention class.

def

This is short for “define.” You use this word to tell the computer that you’re defining something called a function. As we discussed in the posts Um, What’s Your Function, Again? and Could You Pass the Delicious-Looking Plate of Parameters?, a function is a block of lego-like code that not only helps you keep your code orderly but makes it a lot easier to use it again in future programs (or use it multiple times in the same program).

With def, you’re telling the computer, “Hey, pay attention! You’ve gotta remember what we’re doing here so you can reference it when needed.” It’s sort of like when a choir conductor points to the lead singer, indicating, “It’s your turn to play the lead verse, and I mean now!” Here’s a super simple example of a function:

def leopard(): #name of the function and a bad rock n' roll pun
    print("snarl") #this is what it does
leopard() #this is how you call it

class

You might remember this keyword from the “Got Class?” post. Classes can be thought of as blueprints or templates that help you to create a variety of related Python objects. You might think of a  class as a sort of “uber function” that, among other things, helps create and control a bunch of other functions.

But that’s not entirely accurate. This is probably a better definition: “A Python class is like an outline for creating a new object. An object is anything that you wish to manipulate or change while working through the code.”

But maybe it’s best if you just create few classes. Here’s a quick bit of code to remind you how it works. This one is a slightly modified version from the one on the official Python site:

class Leopardy:
    kind = 'cat'      # class variable shared by all instances
    def __init__(self, name):
        self.name = name #variable unique to each instance
d = Leopardy('Fangs')
e = Leopardy('Spot')
d.kind                  # shared by all leopards
e.kind                  # shared by all leopards
d.name                  # unique to d
e.name                  # unique to e
print(d.name)
print(d.kind)

If you run that code, you should get two things printed out: “Fangs” and “cat.”

Featured image from Def_Leppard_Allstate_Arena_7-19-12 wikipedia Wikipedia: Image by AngryApathy

How Do You Pass Notes to Others (or Your Dumber Self)?

On how to use comments in Python

In Python, if you want to say something that the computer doesn’t need to know but your fellow programmers do  – such as “If you change any characters in this line of code, the whole program goes kablooey” – then you need to stick in a pound sign (#) or put your comments into triple quotes. Try this in your Shell:

>>>print ("Hello, world!") #This line says hello

You should see Hello, world! without all the verbiage to the right of the pound sign. That message to the right of the sign is only for your self, or your fellow programmers. Now, try this (but in your Text Editor rather than the Python Shell):

print ("Hello, world!")
'''
This is a verbose comment to you, the programmer. I wanted 
to mention that this line provides an existential salutation,
a signal of optimism to an oft-hostile universe via a medium 
that is also a message
'''

Here’s how it would look in your Text Editor:

Go ahead and run it and you’ll see that the comment never shows up but “Hello, world!” does (except without the quotation marks).

Remember: that verbose comment needs to go below the first line. The triple quotations marks (outside the holy confines of the parentheses, that is) allows you to leave a multi-line comment to whomever will be seeing your code.

Also remember that Python is sensitive to indents, so you won’t want to mess around by indenting your comments.

If you’re thinking that you will just remember how your code works, then you’re badly, sorely, laughably mistaken. It’s amazing how quickly you forget how your code is supposed to work. Leave reminders even if it’s a pain in your rump. You won’t regret it.

For a little more on comments, I recommend After Hours Programming.

Featured image is by Hariadhi. See https://commons.wikimedia.org/wiki/File:Cheating.JPG