The ABCs of Python: “del,” “if,” “else,” “elif,” and teeny cars

Here are four more Python keywords:


This means, as you might expect, “delete.” I became a fan of del after I read a discussion in which coders debated whether it’s an essential word. Here’s how one side of the argument went: “I can’t really think of any reason why python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign None to it.” I love this because it so coder-like. Rather than using a term that’s something like regular English, some keyword-frugal folks suggest abandoning it, going with the system of assigning None to things. This is a minor insight in the mind of programmers.

n = 'Nazi'
del n
#when print runs the 2nd time, Nazi will be deleted 
#so you should get an error

I should note that assigning None to something does not do the same thing as deleting it. A variable to which you assign None still exists. A variable you delete doesn’t.


I’m jumping ahead again in our alphabetical list because it’s best if we pair if with elif, which comes next. As we noted in When Does Your Code Get Iffy?, if is the key word in conditional statements. If your code contains a contingency or a test, then you likely need an if:

def gasMileage(mpg):
    if mpg >= 100:
        comment = 'need a can opener to get in that thing?'
        if mpg >= 80 and mpg < 99:
            comment = "that's frigging amazing"
            if mpg >= 40 and mpg < 80:
                comment = "huh, that's pretty good"
                if mpg >= 25 and mpg < 40:
                    comment = 'my bmw wagon does better'
                    comment = "that a global warmer, baby"
    return comment
print(gasMileage (25))


Yes, this word also means what it says, working hand-in-glove with if, as we saw in the previous example. You can look at the code above if you want to see how else is used in actual code.


This is a not-too-tricky combination of the words “else” and “if.” It sounds like it might be some phony, steroetyped Hollywood version of a Southern dialect: “If’n ya’ll want to get to the Piggly Wiggly, you drive on up County Road 40 a couple of miles. Elif you miss it, there’ll be a Kash n Kary just another half mile or so afore ya’ll cross the railroad tracks. Elif you cross those tracks, you better turn back because from there you’ve got 30 miles or so of pure Ocala Forest road with nary a store nor gas station to be seen.”

By using elif, you don’t need to have a multitude of indents in some code with lots of conditionals. Remember that code we used in when discussing if? Well, here’s another version:

def gasMileage(mpg):
    if mpg >= 100:
        comment = 'need a can opener to get in that thing?'
    elif mpg >= 80 and mpg < 99:
        comment = "that's frigging amazing"
    elif mpg >= 40 and mpg < 80:
        comment = "huh, that's pretty good"
    elif mpg >= 25 and mpg < 40:
        comment = 'my bmw wagon gets that kind of mileage'
        comment = "that's why FL is gonna be underwater soon"
    return comment
print(gasMileage (150))

It’s pretty neat, in more ways than one.

Featured image: American Automobile Culture: Cars from the Lane Motor Museum. Philip (flip) Kromer from Austin, TX.,_The_World%27s_Smallest_Car_ (Lane_Motor_Museum).jpg

The ABCs of Python: “except,” “try,” “finally,” and Looney Tunes

Here are three more keywords in Python:


This keyword is used to code for what Python calls (what else?) “exceptions,” which tend to mean that something has gone wrong in the execution of a program. That is, the program works except in a certain circumstance, as in, “Nothing can harm Superman except Kryptonite.” This keyword is partnered up with another one: try. That’s why I’m placing try below, along with some code that uses them in tandem.


This is try as in “try this and see what happens.” Below is a function in which we use try and except. All we’re doing is employing the index function to select a specific number from an array of numbers in a list. For example, let’s say we pick the third number in this list — [20, 12, 99, 15, 78] – remembering that we start counting from zero in Python. The third number here is 15. We then multiply 15 by itself three times. We’re going to call this function in several different ways so you can see how the code works.

def power_up_index(array, n):
     Find Nth power of the element with index N.
         return array[n]**n
     except IndexError:
         return ("Not gonna work")
print(power_up_index ([20, 12, 99, 15, 78], 3))
the number 3 is n in this case. You pick the third
number and multiply that number by itself three times.
print(power_up_index([1, 2, 3, 4], 2)) #you multiply 3 
                                       #by itself two times
print(power_up_index([1, 2], 3))
you get an error message because the computer cannot locate the 
third number in this array (which only has two numbers,
as you can see). Thus, you get the “Not gonna work” message.

This code will produce three lines:

Not gonna work


By using finally, you can always get the final word in. Even if your error code appears as a result of an exception, you can still say or do something else. The following code is another version of what we just saw, except this time we get in the sign-off of “That’s all, folks!” regardless of what else happens.

You can, of course, do other things with finally as well. For example, if your code opens a file but something goes wrong in the execution of your program, you can still close your file with the finally statement. This ensures you can tidy things up.

def power_up_index(array, n):
     Find Nth power of the element with index N.
         print ("The answer is: " + str(array[n]**n))
     except IndexError:
         print ("Not gonna work")
         print ("That's all, folks!")
(power_up_index ([20, 12, 99, 15, 78], 3))
(power_up_index([1, 2], 3))

This time around, we get the following results:

The answer is: 3375
That’s all, folks!
Not gonna work
That’s all, folks!

PS – For more on information on exception handling, I recommend tutorialspoint.

Featured image from Intertitle of the Public Domain short film "Crowing Pains," 1947, Warner Brothers

The ABCs of Python: “break,” “continue,” “pass” and Rudolph

Here are three more keywords in Python:


This causes a break in the computer action. Whatever the program was doing, it stops doing it. It’s like when a cop on a bad television show yells, “Freeze!” This is great if you want your function to stop looping for some reason. In the code below, for example, the code stops as soon as the name of “Rudolph” is encountered. After all, some Christmas legend purists will say that Rudolph is a wanna-be reindeer made up by Robert May as recently as the 20th century.

#this code uses "break"
santasReindeer =  ["Dasher", "Dancer", "Prancer", "Vixen", "Rudolph", "Comet", "Cupid", "Donner", "Blitzen"]
for deer in santasReindeer:
    if deer == "Rudolph":

#Run this code and you'll get the following:



Technically, the keyword class should come next, but we’re jumping ahead to continue because it can be an alternative to break in your code. That is, instead of stopping the code midstream, continue will allow it to continue after it eliminates whatever seems to be troublesome or unwanted. To see what I mean, let’s go back to Santa’s reindeer:

#this code uses "continue"
santasReindeer =  ["Dasher", "Dancer", "Prancer", "Vixen", 
"Rudolph", "Comet", "Cupid", "Donner", "Blitzen"]
for deer in santasReindeer:
    if deer == "Rudolph":

#Run this code and you'll get the following:


This time, all the reindeer except Rudolph are printed out. You’ve got to feel a bit sorry for Rudy. After all, we’re using code to exclude him from joining any reindeer games (like Monopoly).


Let’s also have a look at pass so that we’re grouping similar keywords together. Pass is the term you use when, syntactically speaking, you’ve got to do something but you don’t really want to do anything. For example, maybe your code requires you to use an if statement somewhere but you don’t particularly want to do anything useful with that statement. In that case, pass can be handy. Here’s a way we can use it in our reindeer code.

#this code uses "pass"
santasReindeer =  ["Dasher", "Dancer", "Prancer", "Vixen", 
"Rudolph", "Comet", "Cupid", "Donner", "Blitzen"]
for deer in santasReindeer:
    if deer == "Rudolph":
        print ('"My deers, stop excluding Rudy from all your reindeer games."')

print('Dasher responding: "Okay, Mrs. Claus. Sorry!"')

print('Dasher whispering to Rudolph as an aside: "Come on, you red-nosed freak. 
Just wait till we play Kill the Carrier. Yur going to get it!"')
# Here's how it should print:
"My deers, stop excluding Rudy from all your reindeer games."
Dasher responding: "Okay, Mrs. Claus. Sorry!"
Dasher whispering to Rudolph as an aside: "Come on, you red-nosed freak. Just wait till we play Kill the Carrier. Yur going to get it!"

Yes, kids can be cruel. But don’t worry, Rudolph wins them all over eventually. He even winds up going steady with Vixen, yet another nerd made good.

Hermey the elf and Rudolph, two characters from Rudolph the Red-Nosed Reindeer. See Rudolph_the_Red-Nosed_Reindeer#/media/ File:Hermey_the_elf_and_Rudolph.jpg

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

Here are two more keywords in Python:


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


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): = name #variable unique to each instance
d = Leopardy('Fangs')
e = Leopardy('Spot')
d.kind                  # shared by all leopards
e.kind                  # shared by all leopards                  # unique to d                  # unique to e

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

The ABCs of Python: The Dynamic Duo of “for” and “in”

Here are two more keywords that are especially key in the realms of Pythonland. If you’ve been reading this blog in anything like a linear way, you’ll remember them from Are You Feeling Loopy Yet?


Let’s hear it for for. Within the realm of Pythonland, it’s dull-looking but crucial in the larger scheme of things, sort of like Phil Coulson of comic book, film and TV fame. But boring-looking for wouldn’t be much without its cohort in. They make a pretty dynamic duo, kind of like Phil and Nick Fury, or Batman and Robin, or Laurel and Hardy, or Wayne and Garth, or Walter and Jesse. You get the idea. Python would be a lot less powerful without them.


If you want to move through a list, for example, nothing works better than “for i in x” or “for dog in hotdog” or “for beautiful in spacious_skies”. The foundation is always the for and the in. Here’s an example of the duo’s powers in action:

double = []
sizes = [3, 4, 5, 7, 10, 13]
for each_number in sizes:
    double.append (each_number*2)
print (double)

Here’s what we get back:

[6, 8, 10, 14, 20, 26]

This bit of code takes every single number in the list called “sizes,” doubles those numbers, and sticks them into a different list called “double.” In the line “for each_number in sizes,” we’ve used “each_number” so it reads more like standard English, but we could just as well have used “i”. In fact, using “i” in these cases is something of a convention in Python, as in “for i in x.”

PS – For more information on for and in, I recommend’s excellent wiki tutorial. And if you’re looking for something a little more interactive, I recommend a short portion of How to Think Like a Computer Scientist.

Publicity photo of Stan Laurel and Oliver Hardy. Author: Hal Roach Studios

The ABCs of Python: “async,” “await” and feeding the durn cat 

The keywords “async” and “await” were not on the list when I started learning Python. These keywords allow programmers to engage in concurrent computing. I think that means multiple tasks can be run in such a way that they overlap with one another. This stuff is over my head but I’ll take my best whack at it.

This form of computing is based on a “single-threaded, single-process design,” which I believe means that the computer can only do one thing at a time. But even though it does one thing at a time, that doesn’t mean it can’t pop back and forth between different tasks.

Let’s say I get up in the morning and turn on my slow laptop rather than my speedy PC. I hit the start up button and walk away to go start some coffee and then, having started the coffee, I can feed the (acting out) cat, then I go back to the laptop and open the browser, then check on the coffee, then let the (now meowing) cat out, then pour the coffee, then go back to the now functional laptop.

I’m just one person, a single processor. I’m not doing any of these things at the same time (like a parallel computer might). I’m just popping back and forth among different tasks, coming back to the right tasks at the right time.

At least I think that’s about right. Anyway, here’s a very simple application of these key words.

import asyncio

async def hang_on_three_secs():
    print('Hey, just give me three seconds')
    await asyncio.sleep(3)
    print("Okay, I'm back")

This will print out the words, “Hey, just give me three seconds” and then, exactly three second later, will print out “Okay, I’m back.”

For a way more detailed, erudite and probably accurate explanation of these keywords, I recommend RealPython.

Got Class?

On how to use classes in Python

Here are the metaphors I use to understand Python’s functions, modules, methods and classes:

Functions are like individual legos. Once you’ve created them, you can snap them in and out as needed to create working code.

Modules are sort of like prefab buildings that you have (or someone else has) built, in part, with those legos. You can add these entire prefabs to some larger construction project, or you can just scavenge some bits and pieces from a prefab and add it the construction project.

Modules are just Python files that contain relatively normal programs that are useful and can be utilized as often as you like. A module can have definitions of variables, functions, and even classes. You use “import” to bring modules – or pieces of modules – into whatever code you’re writing.

Methods are the same as functions, more or less. Except for the fact that they live “inside” classes. But, then, what in the heck are classes?

Classes are the blueprints, a metaphor I took from Steven Thurlow. He writes that a class “isn’t something in itself, it simply describes how to make something. You can create lots of objects from that blueprint – known technically as an instance.”

That sounds nifty, right? First you have legos, then prefabs made of legos, and then blueprints to keep it all organized.

Except this blueprint is also a bit like instructions that you put into a virtual 3-D printer. That is, the class both organizes and helps produce objects, all of which have similar characteristics and functions (or methods).

But enough metaphors for now. Let’s build a class, or draw a blueprint, or whatever works for you.

Step One: Decide what you want your overarching structure to cover. I’ve decided to build a dog, sort of.

Step Two: Next do the designing. In this case, we’re going to keep it somewhat basic but not so basic that you can’t see any nuances. The comments I’ve left explain how I see things.

Step Three: Create stuff (i.e., instances) based on your blueprint (i.e., class):

class Dog: #creates class called "Dog"

    def __init__(self, breed, height, weight, length, color):

        The code line above is a method common to classes. 
        Based on how you call the function, Python can 
        figure out what "self" is, so you don't need to 
        put it in among the parameters. You only need to 
        pass in the values called breed, height, weight, 
        length, and color
        self.breed = breed
        '''The line above makes sure that the program knows 
        that the value "breed" is going to be passed as 
        self.breed. Self is a placeholder for whatever 
        you decide to use. In this case, self is a 
        placeholder for 'Hank', as you can see below. The 
        same principle applies to the four other parameters 
        directly below'''
        self.height = height
        self.weight = weight
        self.length = length
        self.color = color
    def bark (self, sound):
        This adds a new method call "bark". When you call it, 
        it prints out whatever word you've put in as a parameter
        print (sound)
Hank = Dog('labrador', '24', '100', '36', 'yellow')
Here we are assigning the name Hank to Dog with these five values. As you can see, we don't need to put in a value for self. This is an example of how we are using a class to create an 'instance' named Hank. 

print("This is Hank's breed: " + Hank.breed + ". And here is his weight: " + str(Hank.weight)) 
print("Oh yeah, and here is his length: " + str(Hank.length)) 
In the lines above, we are printing out three specific values associated with Hank. This all hinges on what the blueprint describes in the class. We are putting some actual objects in based on that blueprint 

Hank.bark("bow wow") 
print("Really? Bow wow? You couldn't get more imaginative than that, you shmuck?") 
Hank.bark("How about wan-wan, as the Japanese dogs say?") 
Here we are calling the method of def bark(self, sound) in a couple of ways. 

And here’s how this stuff prints:

This is Hank’s breed: labrador. And here is his weight: 100
Oh yeah, and here is his length: 36
bow wow
Really? Bow wow? You couldn’t get more imaginative than that, you shmuck? How about wan-wan, as the Japanese dogs say?

Okay, I think that’s about right. I should also mention that one class can inherit features from another class. It’s almost as if such classes are part of a family tree and they all share the same DNA/bloodline. But, if you’re a beginner, then your mind is probably already blown, so we won’t bother with inheritance for now.

PS –  However, if you want to learn more about classes and inheritance immediately, I can recommend the following sources of information:

An Introduction to Classes and Inheritance (in Python) on Classes

Python from Scratch: Object Oriented Programming

Featured image: Hank by Cyndi Vickers

The ABCs of Python: “and,” “as,” “assert” and Stephen King

Let’s take it from the top. Alphabetically speaking, here are the first three keywords in Python:


Shocker! This pretty much has the same meaning as the English word and, aside from the all the Boolean logic stuff we discussed before. Bottom line: If you tell your program that it must have, let’s say, both a poncho and an umbrella before it takes some action, then it’ll take you very literally. Don’t expect it to do what you want without both of them. The code below uses and. Go ahead and run it your text editor. If that works, change the dog assignment to False and see what happens:

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


The popular writer Stephen King has been known to pen books using the alias of Richard Bachman. Sometimes you’ll see this phrase: “Stephen King writing as Richard Bachman.” That’s pretty much the same way Python uses the word as. It creates aliases, especially for modules that you “import” into your code so you can use them without writing them from scratch.

Let’s take the example of the “turtle” module, which you can use it to draw pictures using, well, turtles. If you wanted to just use it, you could write “import turtle” to get started (we’ll talk more about import a little later ). But you could also give the turtle module an alias. Let’s say you want to give it the alias “slowOne” and then use the renamed “slowOne” module. Here’s how you might go about that.

import turtle as slowOne    # allows us to use the turtles library

wn = slowOne.Screen()     # creates a graphics window
alex = slowOne.Turtle()   # creates a turtle named alex
alex.forward(150)         # tells alex to move forward by 150 units
alex.left(90)             # turns by 90 degrees
alex.forward(75)          # completes the second side of a rectangle

Feel free to play around with the module for a bit. For a tutorial on how to use it, I recommend the chapter “Python Turtle Graphics” in the interactive version of the book How to Think Like a Computer Scientist.


This handy, dandy keyword helps you discover whether or not you’ve written buggy code. You assert that something is true. If it is, nothing happens. No news is good news. If it’s not true, however, it gives you an “AssertionError.” What’s more, you can add your own verbiage to the assertion error. Run the following code in your text editor and you’ll see what I mean:

#this code uses "assert" and produces an AssertionError
x = 100
assert x < 2, "the value of x is just too big, dude"
Featured image: Stephanie Lawton -

How Many Words Are in Pythontongue?

On using keywords in Python

If we’re just counting so-called keywords, then there really aren’t a lot to learn in Python. Things change over time as new versions of Python appear, but by my count and at the time of this writing, there are only 35 key words. So take heart, newbies, this definitely ain’t Mandarin.

Clywd-Powys Archaeological Trust, Rod Trevaskus

In fact, as a beginner who is taking tutorials, you’ll regularly use only about half those words. Still, I suspect that if you learn them all now, you’ll become a better coder faster (advice I wish someone had given me before I began my inefficient perambulations through Python coding). They don’t call them keywords for nothing.

So let’s start with an alphabetical list:

  1. and
  2. as
  3. assert
  4. async
  5. await
  6. break
  7. class
  8. continue
  9. def
  10. del
  11. elif
  12. else
  13. except
  14. False
  15. finally
  16. for
  17. from
  18. global
  19. if
  20. import
  21. in
  22. is
  23. lambda
  24. None
  25. nonlocal
  26. not
  27. or
  28. pass
  29. raise
  30. return
  31. True
  32. try
  33. while
  34. with
  35. yield

Not too intimidating, right? Easier than memorizing the school play you were in elementary school (unless, of course, you played the tree, my personal fav).  Now that you know what the keywords are, you need to know what they all mean and can do. That’s where the next series of blog posts come in.

PS – If you want to know more about keywords right now, I highly recommend Programiz’s Description of Keywords in Python with examples.

Is Khristmas in Your Dictionary?

On how to use Python dictionaries

So, we’ve talked a little about tuples (which use parentheses) and lists (which use square brackets). Now let’s talk dictionaries, which use those cute little curly brackets — that is {} — that come standard on keyboard but that you’ve probably never used unless you happen to be a mathematician.

Here’s your chance to put those curly brackets (sometimes called braces) to work. In Monty Python’s Bookshop Sketch, a customer comes in looking for various books, including “A Khristman Karol” and “Knickerless Knickleby.” Alas, the peeved Proprietor has never heard of them, at least not with those spellings.

But, with Python, we can easily enough create a dictionary in which those titles actually exist. Python’s dictionaries represent a kind of baroque list using the curly braces. These fancy lists are totally mutable and typically jam-packed with pairs of stuff called “items.” An item includes a key and a corresponding value or, to put it in plainer English, a name and some data you want to store along with the name.

So, let’s build a quick list based on the Bookshop Sketch. These are titles of books followed by the names of their authors:

Monty_Python_Library = {'Thirty Days in the Samarkind Desert \
with the Duchess of Kent': 'A. E. J. Eliott', 'David \
Coperfield': 'Edmund Wells','Knickerless Knickleby': \
'Edmund Wells', 'A Khristman Karol': 'Edmund Wells', \
'Rarnaby Budge': 'Charles Dikkens', 'Karnaby Fudge' : \
'Darles Chickens', "Olsen's Standard Book of British Birds: \
 Expurgated Version" : 'Olsen','Ethel the Aardvark goes \
Quantity Surveying' : 'Anonymous'}

Each book and its associated author is placed in a string, and a colon is used to connect them. If you don’t want to do all that typing, you can paste that into your text editor.

Note that I’ve added backslashes (\) to the code so that it can be broken into multiple lines and still run. Those backslashes are not part of the dictionary code. If you remove all the backslashes but put all the code onto a single line, it’ll still work. Now add the following:

print (Monty_Python_Library)

Run those the dictionary code and the print statement and you’ll see the entire dictionary appear in your IDLE Shell. So, that’s easy enough to create (I hope). It’s also easy to add or subtract things from that dictionary. Here’s how you add something:

Monty_Python_Library ['The Gospel According to Charley Drake'] = 'Charley Drake'

Now, if you print the library again, you’ll see the classic by Charley Drake added in.

Here’s how the code looks in my IDLE, though note I’ve added some extra print lines to make it a bit clearer:

But what if you want to get rid of some items? There are a couple of common ways of doing that as well. One uses the term del (as in delete), and the other uses the term pop (as in stick a needle in a balloon). We’ll use both below:

del Monty_Python_Library ['Thirty Days in the Samarkind Desert 
with the Duchess of Kent']
Monty_Python_Library.pop ('Rarnaby Budge')

If you print the dictionary again, those should be missing from the list.

You can now use this dictionary to find out who wrote specific titles. For example, we can use the following line to ask who wrote ‘David Coperfield’. We get, of course, the not-so-renown (except among Monty Python fans) Edmund Wells.

>>>Monty_Python_Library ['David Coperfield']

'Edmund Wells'

If you wanted to expand this library, you could add in more corresponding values to the titles, stuff such as publication date, publishing house, etc.

Monty_Python_Library ['David Coperfield'] = 'Edmund Wells', 'Random House', 1876

Here’s how this coding looks in my IDLE:

There’s plenty more to know about compiling and structuring dictionaries, but that’s enough to cover the basics. If you’ve suddenly developed a passion for dictionaries (and who hasn’t, at some point?), then I recommend the following sources:

Learn Python the Hard Way

Hands-On Python Tutorial

Feature Image: Duchess_of_Kent,_2013 wikimedia The Duke and Duchess of Kent; Image by Carfax2 in Wikimedia,_2013.JPG