Why Not Take a Walk on the “While” Side?

On how to use “while” loops in Python

I like the language of the “while” loop because it verges on real-life, commonsense English.  After all, we run these kind of loops all the time in our daily lives.  For example, while my neighbor’s tree is producing lychee nuts and I’m allowed to pick them, I’m damn well going to pick some.  Once it stops producing good fruit (or once my neighbors tell me to take a hike), I’ll cease picking them.

“While loops” work the same way in Python. While a condition is True (or False), the code will do something. After that, it’ll stop.

Take the following example:

numbers = list()
i = 0
while (i <= 20):
    i = i+2

This almost reads like regular English. Here’s how to parse it: while the numbers in a list are equal to or less than 20, we keep adding the number 2 to them and sticking them in a list. The “numbers.append(i)” line is what “appends” the numbers into the list. Once the numbers go over 20, the conditions have changed and we stop running the loop. We wind up with a list full of even numbers like so:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Easy, right?

But if you screw up, you can send your computer into a spasm of infinite loops.  I’ve unintentionally done it before. I was fortunate that someone had told me that that I could press Ctrl-C to stop the script and get out of the loop.

Let’s take a simple example of a ‘while’ loop::

loopy = 1
while loopy < 4:
    print (loopy)
    loopy = loopy + 1

This loops a few times and prints out the following:


BUT, if we had left out the last line of code, we’d be stuck in an infinite loop because 1 is always  less than 4.  So, the computer simply would not  know when to stop. Keep in mind that computers can do things very quickly, including things that you don’t want them to do (but unintentionally commanded them to do). An infinite loop is out-of-control code that can crash your computer. But, on the brighter side, at least you gain a deeper appreciation for that loopy symbol for infinity.

The symbol in several typefaces

Featured image is Symbol used by Euler to denote infinity. Leonhard Euler - Variae observationes circa series infinitasCommentarii academiae scientiarum Petropolitanae 9, 1744, pp. 160-188.

Why Do Indents Make Deep Impressions?

On how to use indents in Python

Programs generally get written in blocks of code. A lot of programming languages use braces to indicate where a block starts and stops. Python doesn’t. It uses indents, sort of like paragraphs in English.  It’s more elegant than brackets, but if you don’t get the indents right, Python will torment you in a way your fifth-grade English teacher never could.

Let’s start with something simple.

Here’s a quick example of how indents can make a difference.

def indentsReallyMeanSomething():                       #Line 1
    print('Which line should print first?')             #Line 2
    print('This line or that line?')                    #Line 3
indentsReallyMeanSomething()                            #Line 4
print('It depends-how do you want to indent your code?')#Line 5

If we leave the indents as they look above, then we get a print out like this:

Which line should print first?
This line or that line?
It depends-how do you want to indent your code?

Now, we can take the indent out of Line 3 so the code looks like this:

def indentsReallyMeanSomething():                       #Line 1
    print('Which line should print first?')             #Line 2
print('This line or that line?')                        #Line 3
indentsReallyMeanSomething()                            #Line 4
print('It depends-how do you want to indent your code?')#Line 5

Then we get a print out like this:

This line or that line?
Which line should print first?
It depends-how do you want to indent your code?

I’ve set this code up so it works fairly well either way, but that’s not usually going to be the case. You might really screw things up by writing code that puts the wrong line first. Imagine telling a customer to check out before he or she even buys your product (doh!), or imagine telling someone to drive left and then right when you really mean to tell them to drive right and then left (WTF?).  Bottom line: the beauty of indents is more than skin deep when it comes to Python.

As a beginner, you should know a couple of more things about indents. First, the huge role that indents play in Python is pretty unusual in the world of programming languages. A lot of Pythonistas argue that it’s a graceful way of telling the computer which coding statements you want grouped together, a process sometimes referred to as “scoping.”

Not everybody is enamored with indentation, however. In fact, it’s one of the more controversial aspects of the language.  Andy Buckley, for example, wrote a blog post in 2007 called “Python indentation considered boneheaded.” He argues, among other things, that:

If more than one person, with different editor settings with regard to tab/space indentation edits the same Python code, a mix of spaces and tabs is pretty much guaranteed. In any other language, this doesn’t affect the bvehaviour of the code: in Python the invisible markup can completely change the logic. Oops.

Such complaints are one reason for the Python Style Guide. I should note that indenting with four spaces is the preferred indentation method in Python. Python 3 actually disallows mixing tabs and spaces for indentation in one piece of code.

As a beginner, I love the look of Python code, which has to be presented well in order to work. On the other hand, I’ll tell you that getting indents right has been one of the hardest things for me to learn.

But, to be honest, correctly using brackets might have proven just as hard. My issues probably have much more with my own boneheadedness than the boneheadedness of the language.

Feeling Loopy Yet?

On how to use loops in Python

It’s hard to do much coding without getting loopy. There are  reasons for that. First, we tend to use computers to do the same or similar tasks over and over, which is great because they don’t get bored (yet).

Second, loops allow your computer to go back to the same useful functions and plug in different values based on things such as input from human beings.

Third, loops help you write programs that go through long strings and lists of data one at a time (though incredibly quickly) to make decisions about them or otherwise use them.

Without loops, most programs would run for a split second and be done. So, loops are good –unless they’re bad — and when they’re bad, they can be very, very bad (play spooky foreshadowing music here).

Python has a simple and elegant loop system. There are really two kinds of loops, or three if you count nested loops (where you have loops within loops):

‘for’ loops
‘while’ loops
 nested loops

Let’s start with the “for” loops. Some programmers swear by them.  In one of the first books I read, Python in a Day, Richard Wagstaff notes, “I almost always use only the ‘for’ loop.” That’s largely because avoiding while loops reduces the risk of getting stuck in infinite loops.

“For” loops work in a number of ways. Here’s an example that uses a short list:

for number in [1, 2, 3]:
    print("Nobody expects the Spanish Inquisition! " * number)

Here’s what happens when you run this program:

Nobody expects the Spanish Inquisition!
Nobody expects the Spanish Inquisition! Nobody expects the Spanish Inquisition!
Nobody expects the Spanish Inquisition! Nobody expects the Spanish Inquisition! Nobody expects the Spanish 

We multiply the number of times we say this classic Monty Python quip by the numbers in the list (oh yeah, although you probably know this already, the symbol * means multiplication in Python). When I started with Python, it took me awhile to figure out that the most important two words in such code are the most innocuous ones: “for” and “in”.  In Line 1 above, the word “number” has no particular importance. If I substituted the word “tomcat” or “aluminium” or “jigglywiggly” for the word “number,” the code would work exactly the same way. Quite often, programmers just use the letter i as the stand-in. It’s quick and dirty but definitely doesn’t stand for “imagination.”

All Python really “knows” is that you want to do something a certain number of times, depending on what’s in the list.  Think of it as your idiot savant bro, ala Rain Man. It’s excellent at counting and listing, not so hot at nuance.

Let’s put the “for” loop at the heart of a new function, like the one below. We’ll get super corny and jump with both feet into a dog metaphor.  We’ll name this function LassTheTailWagger.  We feed that function treats, which are in the parenthetical maw of our parameter. For every batch of treats she eats, she wags her tail, thus giving us the total number of all the treats.

(Note: If you try this at home, don’t forget to put the indents in the right place. They make all the difference, as we’ll see in our next post)

def LassTheTailWagger(dog_treats_she_eats):
#Returns the sum of the numbers treats eaten, according to wags of tail
    sumOfWags = 0
    for number in dog_treats_she_eats:
        sumOfWags = sumOfWags + number
    return sumOfWags

print(LassTheTailWagger([5, 3, 2, 7]))

At first, there are zero wags but, as we feed her treats, the sum of all the wags continues to climb. In the first loop, we feed her 5 treats (based on the list of numbers in the print line), and the SumOfWags equal 5. The code runs and then we loop the next number in the list (3) up into the code. It adds 5 and 3. The loop continues to run until we get to the last number in the list (7). At that point, we have fed her 17 treats and the program stops running.

If this is still confusing to you, the beginner, don’t worry about it. You’ve probably got the general idea, and it’ll become clearer as you learn more about coding in general and Python in particular. Keep in mind that playing around and repetition are the keys to learning. So, my advice is to play around with simple “for” loops for your own amusement until you’ve gotten the hang of them.

PS – If you want more tutoring on “for” loops, I recommend you try out the following: Python 3 Video Tutorial – For Loops

Featured image from Author User:Coaster J From https://commons.wikimedia.org/wiki/File:Blue_fire_loop.jpg

Could You Pass the Delicious-Looking Plate of Parameters?

More on Python functions, parameters, values and stuff

Last time around we started chatting about functions: that is, the legos of the Python universe. You always start a function with the word “def” followed by the name of the function, followed by parentheses and a colon. In other words:

def NameOfFunction ():

Sometimes there will something inside the parentheses. If so, that’s your “parameter.” In the world of Python, parameters and arguments are pretty much used interchangeably, but, technically, parameters are the variables and arguments are the values you give those variables.

If I write “height = 6,” then height is the variable and 6 is the value.

Anyway, a parameter sits beside the function and is often integral to the work it does, sort of like the chocolate chips in a cookie batter. To get an idea of how this works, check out the super simple code below. In this case, the name of the function is “theBatter” and the name of the parameter is “chips.” :

def theBatter(chips):
    return (chips)

All this does is crank out chips. That is, it cranks out whatever string is placed into parentheses next to the name of the function. I say that it “cranks out” but you don’t actually see the chips that it cranked out unless you tell Python to print them.

How to explain this? Let’s say somebody asks you to calculate 2 + 2. You do it in your head but don’t say anything. The answer is “returned” in your head. Then the person asks you to write the answer down. So you do, printing out “4”.

That’s how it works in Python in this case. Once the function runs, it “returns” the answer but the answer remains in Python’s “mind.” You don’t see the answer till you tell it to print.

Now, let’s actually use (or “call,” as they say) the function described above a couple of times and print out the results:

firstVision = theBatter ('Envision this string as filled with chocolate chips and being poured into batter')
secondVision = theBatter ("Not enough chips yet? That's okay. Pour this string of chips into the function as well")
print (firstVision)
print (secondVision)

Note that we placed a literal string of characters that discussed chocolate chip cookies between the parentheses. If you run this code, here’s what you should get:

Envision this string as filled with chocolate chips and being poured into batter

Not enough chips yet? That’s okay. Pour this string of chips into the function as well

Okay, now let’s do something moderately harder. Write this into a new program.

pecans1 = 50
pecans2 = 150
chips1 = 60
chips2 = 120
def yumFactor (ingredient1, ingredient2):
     total = ingredient1 + ingredient2
     return total
todaysCookies = yumFactor(pecans1, chips2)
tomorrowsCookies = yumFactor (pecans2, chips1)
print ("The yum factor for today's cookies is " + str(todaysCookies))
print ("The yum factor for tomorrow's cookies is " + str(tomorrowsCookies))

So, what’s happening here?

First, we assign some values to some variables. For example,  pecans1 is a variable that has a value of 50.

Second, we write a function called yumFactor. It takes two parameters: ingredient1 and ingredient2. All the function really does is add the values of those two parameters together and then give you the sum total.

Third, we “call” the function twice. The first time, we used two arguments: pecans1 and chips2. The second time, we used two other arguments. In both cases, we assign a name to the outcomes. Those names are “todaysCookies” and “tomorrowsCookies.”

Fourth, we print out those outcomes within the larger context of a string. What we actually get in the Shell are the following  two sentences:

The yum factor for today’s cookies is 170
The yum factor for tomorrow’s cookies is 210

(In case you couldn’t tell, I’m a fan of cookies.)

Here’s how all the code looks in IDLE before we run it:

And here’s what prints out in your Shell:

PS: Sometimes I  think of functions as dogs and parameters as dog biscuits (you can see that I tend to be drawn to food-related metaphors). You “call” the dog and give her some nice parameters to work on. She gobbles them up, “passing” them right through the body, building strong bones and teeth, as the commercials say. Of course, if we take the metaphor too far, I guess it means that our functions ultimately pass stuff that we have to pick up with plastic bags in the park. Metaphors are dangerous that way.

PPS: If you’re looking for a more sensible tutorial on functions, here’s one you might try.

Featured image from Andrew6111. Wikimedia Commons. https://commons.wikimedia.org/wiki/File:Plate_of_chocolate_chip_cookies,_ready_to_munch.jpg

Um, What’s Your Function, Again?

On a first look at functions in Python

Everybody needs to find a place in this world, and that includes your computer code.  One of the best ways of making sure your code knows its proper place is by writing it in the form of a function.  A function is kind of like a lego block. You write it in such a way that it can connect up nicely with other functions and lines of code. Together, they build something cool.

These structured blocks of code are used to perform an action and return some type of value.  They’re modular, so you may be able to use them over and over. In fact, Python has lots of built-in functions, such as the “print” function, designed to make your life easier. You take its built-in blocks and snap them together with blocks of your own design.

It’s sort of like child’s play, but with more cursing.

You know a function when you see one because it starts with the keyword known as “def,” which stands for “define.” That is, you immediately define what your block of code does. It’s sort of like those nametags at business conferences: “Hi, I’m So-and-So, and Work at NameOfBiz as a NameOfOccupation.” Except functions somehow seem a lot less lame than nametags.

Function blocks start with def and then are followed by function’s name, parentheses and a colon (don’t forget the colon!). Like so:

def function_name():

But that’s not all, there’s more! A lot more, as you’ll see in the next post.

PS – If you’re the instant gratification type and want to learn more about functions right now, then here are some sites I recommend:

Featured image from GTurnbull925. Wikimedia Common. https://commons.wikimedia.org/wiki/File:Pile_of_lego_blocks.jpg

When Does Your Code Get Iffy?

On using conditional if-else statements in Python

We live in a contingent world. That’s why it’s so hard to make predictions with any accuracy. Are you going to live in your current house for the next ten years? Well, that depends. If  we don’t inadvertently produce more kids and if we can afford to add on a new adults-only bathroom and if my boss doesn’t continue to drive me bonkers and if interest rates continue to climb like kudzu and if… Well, you get the idea. It’s all about how various conditions shape up.

Programmers need to worry about lots of contingencies as well. That’s why, in the world of programming, we have “conditional statements.” That’s usually just a fancy name for lines of code that begin with the world “if.” The programmer has to work out the possible conditions in advance.

Let’s say you want to write a program that automatically gives people their horoscopes. Well, that horoscope will be contingent on what year the person was born, what time they were born, what hour they were born, whether Venus was in retrograde (whatever that even means), etc. In short, there are a whole lot of “ifs” here.

Let’s start at a basic level. Write the following short code in a text editor and run it. (Don’t forget the indents because Python is extremely sensitive to those, which is a subject for another post!)

height = 8
if height == 8:
     print ("Hiya, Charlie! Nice stilts!")
     print ("Hey, Charlie, no stilts today?")

You should get the message, “Hiya, Charlie! Nice stilts!” Now, go ahead and assign the variable “height” to a smaller value such as 5 or 6 and run the code again. Because the condition of height changed, you got a different response. Such is the power of “if” and it’s sidekick  “else”.  If you can master “if,” you can prepare your code for a world in which conditions change and the future always looks iffy.

PS – If you want more information on conditionals, I recommend the Hands-on Python Tutorial.

Featured image from Tall Camp. Author Jennifer Morrow from San Francisco. Wikimedia Commons. 

The Tao of Python

I’ve been thinking about the Tao of Python. It’s a tricky thing to pin down. The Chinese concept of Tao is, in itself, famously hard to grasp and, therefore, to translate. It’s sometimes glossed as “the way” or “the path.” But what I’m aiming at here is to explain (at least to myself) the spirit of this programming language.

Why? Because I suspect it’s easier and more motivating for the beginner to learn a new computer language if they have a feel for the essential aspects of it, aside from the strictly technical details. These days, amid the plethora of  language choices, adopting a new argot is like learning a new culture. If you divorce the technical details from the culture, you likely suck a lot of the enjoyment out of coding.

This will feel like pure sentiment to some people, who view any code as little more than a tool. Does one wax poetic over one’s hammer, drill or soldering iron? Probably not. But computer languages feel different, and it seems to me that Python brings out more emotion in people than do most other languages.

The Yin and Yang of Python

I’ve found that, like anyone else, Python has a lighter side and a darker side. When you go to python.org in order to download it, poke around for a bit to get a feel for what else is there. It’ll give you an idea of what I deem the yin and yang of Python world.

Yin and Yang symbol
by Klem

The yin represents of the soul of Python: that is, the ideals, the culture, the community and overall vibe. It’s the kind of stuff that helps motivate you when learning a language, but it’s usually given short shrift, if mentioned at all, in books or tutorials.

The yang, on the other hand, is the body of Python: that is, the coding details, the documentation, the references, the tutorials, bylaws and sundry other particulars. It’s the kind of stuff that’s usually the subject matter of books and other resources.

So, why don’t more books and blogs focus on the yin? Two reasons, I think. First, a lot of committed coders have already bought into the yin. They’ve often been coding since they were wee lads and lassies. The yin is the air they’ve been breathing, so they don’t need any discussions or celebrations of it. Second, coders tend to be practical folk. They want just the facts, ma’am, because they want to get up-to-speed on a new language as soon as they can, often in order to get a specific project done.

But the true beginners? We want facts, sure, but we also want to believe we’re doing something fun and worthwhile in a world rife with countless other ways to spend our time. We need, in short, to be converted to the Church of Coding.

The Yin

The Community

At the soul of Python is its community. You can get a feel for it at python.org, where there is a large section called (what else?) “Community.” It provides practical information on conferences, workshops, awards, user groups, etc. But I think that the Python community goes beyond the stuff appearing on that page.

From a wider perspective, the community is made up of folks who go to the trouble of helping each other solve problems in many different forums. Stackoverflow.com, for example, is “a question and answer site for professional and enthusiast programmers”; I’ve found that it’s a great place to gain practical insights into Python (among other things).

There are also face-to-face meetings, though they can be harder to find. Many cities now have makerspaces/hackerspaces where people congregate to make stuff, teach one another to code, and otherwise fly their geek flags. There are also meetups and user groups in which people come together just to discuss programming in Python. And there are a number of Python-focused conferences in a given year.

The Open-Source Vibe

There’re are bound to be communities built up around just about any computer language, but Python has a certain idealistic vibe about it due to its origins and licensing. After all, Python is free and open-source, otherwise known as FOSS. You can download it onto your computer for free, but “free” has another meaning when it comes to Python. That is, you’re free to copy and re-use it.

As for the term “open source,” it means that that people can have access to the source code – that is, the computer instructions written in a human-readable computer language.  There are other criteria associated with open source as well. In fact, the Open Source Initiative includes ten different criteria, including ideas such as that an open-source license “must not discriminate against any person or group of persons” and that it must not “restrict anyone from making use of the program in a specific field of endeavor.”

There’s a sort of practical idealism here that, in other situations, might be sniffed at as some sort of Commie-Socialist-New-Age craziness.  But toward the end of the 20th and beginning of the 21st centuries, open-source software changed the landscape of the software industry, “turning it from a mostly capitalist economy into a mixed one,” according to the The Economist.

Open source has become a critical part of today’s businesses. Indeed, we now have articles from consulting groups explaining to businesses “Why You Need an Open Source Software Strategy.”

Bottom line: the Python vibe is unique but is influenced by the larger open-source ambiance that has radically altered the software landscape. You get the sense this stuff is going to have much more lasting legacy than the communes of the 1960s.

The Way of the Python Programmer

There’s an aesthetic associated with Python programming. I think it applies outside the Python community as well but is especially associated with it. It’s nicely summed up in the following guiding principles developed by Tim Peters:

The Zen of Python

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

There’s a combination of humor and wisdom here that seems especially “Pythonic”. You can just write “import this” into your IDLE and you’ll find that the poem is printed directly into your console!

Mischievous, fun, practical and beautiful: it’s all part the Python aesthetic.

Another place to pick up on it is at the geek-beloved webcomic xkcd, Here’s one of the more famous Python-focused comics:

But there are also some other great ones related to Python such as New Pet and Electric Skateboard. It’s whimsical geek humor at its best.

The Yang

Despite the fun, whimsy and camaraderie associated with the yin of Python, Python isn’t some New-Agey all-inclusive drum circle where even the rhythmically challenged are welcome. At its core is the serious computer language that is used to build software on which businesses and sometimes even lives depend.

If you’re a beginning coder, think of yourself as a lion cub. You play around a lot, mixing it up with the other cubs, stalking insects, watching your elders bring home the big prey. Most of your playing around, however, serves a serious purpose: getting skilled and strong enough to move beyond wrestling with kittens and eating bugs. You want to eventually engage in the serious art of hunting and killing gazelles (or whatever) and battling dangerous threats when needed. In short, all that playing around had a serious purpose.

In the human world of coding, there’s no reason you can’t stay a cub forever, as long as programming isn’t required to make your living. You can fool around with Python tutorials and games to your heart’s content. But there are plenty of folks who use Python and other languages to not only earn their bread but to tackle some of the most important problems in the world. Python is a tool for creating solutions to those problems, solutions that programmers refer to as algorithms.

The terrific book (which has an interactive edition) How to Think Like a Computer Scientist defines an algorithm as “a step by step list of instructions that if followed exactly will solve the problem under consideration.” So, you’re taking those instructions and putting them into a language (in our case, Python) that the computer can understand. Once you’ve done that, you have essentially automated the execution of your solution to a given problem.

Bottom line: this process requires precision, which is one reason coding has much bloody documentation. If you don’t sweat the details, your code just won’t work properly. For people who are used to the creative ambiguity of human languages, this can seem persnickety and anal and just no frigging fun.

Poetry, for example, thrives on artful ambiguity and multiple meaning. Coding doesn’t. Computers are literal creatures. They need things properly and exactly spelled out. It’s their way or the highway. This deep need for structure, logic and rigor can be thought of as the yang of Python.

Speaking in Tongues While Handling Snakes

Python demands that you obey its internal logic. To do this, you need a crystal clear understanding of how it works. The good news is that the language itself is pretty darn lucid, perhaps better than any other computer language. The bad news is that good coders can be rotten writers. That is, they can fail miserably when they write for other people, especially beginning coders.

I think that a lot of the documentation in the otherwise excellent python.org website is a case in point. It’s sometimes like trying to parse some awkwardly translated instruction manual when trying to put together a new grill set. Or maybe like striving to grok Stéphane Mallarmé’s symbolist poetry:

Nothing, this foam, virgin verse
Depicting the chalice alone:
Far off a band of Sirens drown
Many of them head first.

You want to yell, “Speak the English!”

This is clear even to some Python experts. Giving a short talk at PyCon, the largest annual Python-related conference, Python instructor Simeon Franklin asked other Python professionals to take a close look at information on the python.org site in regard to specific features such as “docstrings.” He says that, if those professionals didn’t already know what these features were, they’d have a tough time gleaning it from the text.  He urges them to look at such information with a “beginner’s mind.”

But that can be hard to do for many experts. As a result, it’s as if somebody got filled with some holy spirit of coding and started going all glossolalia on us, speaking in Python tongues. If I were a tad more paranoid, I’d think the documentation were intentionally designed to obfuscate the esoterica of the erudite, to bewilder and baffle the benighted seekers after coding clarity and light. Here’s an example of what python.org reports tells us in section called “What is a Docstring”:

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

Um, okay. Sure thing. Uh huh.

Look, as a beginner, I’m not going to have much of a clue about what distinguishes a module from a function from a class. And alluding to the  __init__ constructor just seems cruel, as if someone were giving you their phone number in Morse code.

Now here’s how Swaroop C H puts it in his book A Byte of Python:

Python has a nifty feature called documentation strings, usually referred to by its shorter name docstrings. Docstrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand. Amazingly, we can even get the docstring back from, say a function, when the program is actually running!

See, was that so hard? He then goes on to show examples of what docstrings look like in some easy code.

The bottom line is pretty simple: programmers use docstrings to tell one another what various blocks of code are supposed to do. Yes, there are other relevant details, such as where to use docstrings and how to format them, but those nuances are less important to the beginner than answering the basic question, “What in the hell is it?”

All the documentation on python.org is supposed to bring light to users with questions. Sometimes it does, being very rich in detail. But to the beginner, it often feels more like dense, dim thickets through which we have to machete our way. Ah well. In the case of particularly dense thickets, there are usually other sources of information in books, tutorials or on the Web. You’ve just got to figure it out. After all, yang happens. It’s all part of the path.

PS – The Python community has, to its credit, become more accommodating to beginners over the years. For example, here are Python Frequently Asked Questions geared toward beginners.

Feature image by Rolf Dietrich Brecher from Germany. See https://commons.wikimedia.org/wiki/File:Yin_and_yang_(36365569814).jpg

Are Booleans from Outer Space? 

On the indispensable nature of Booleans in Python

There are a couple of Python operators worth spending a bit of extra time on. These are the Booleans, which sound to me like some species of Star Trek alien. But they are from inner rather than outer space. That is, to the degree your computer has internal thoughts, it thinks in Boolean.

Computers are, of course, made up of a multitude of circuits, each one of which represents a binary digit of information (aka, a bit). When one of these circuits is on, it represents a “1”, and when it’s off, it represents a “0”. This dichotomous thinking is also represented by Boolean truth values, which come in just two bool types: True and False.

Try this in your IDLE Shell. Type

>>>4 == 5

Hit Enter. The program should print the word False in return. Now do the same with:

>>>6 > 5

This time you get the word True. Clearly, the program knows what’s true and what’s not at a basic mathematical level. That comes in very handy.

Boolean truth values are based on Boolean logic, which was created by a one of those crazy smart English dons of the early Victorian Age. At its most basic level, it’s pretty easy to explain:

George Boole

You start off with a statement that is either True or False. There’s no messy middle ground here. Then, you add in other statements, all of which are also either True or False. You combine those statements by using some Boolean operators (which are “and,” “or” and “not”) and, presto, you’ve got a computer program!

Let’s say, for example, you want to automate a dog catcher. The dog-catcher robot is tooling around looking for stray dogs. It sees some animal crossing the street. One line in its code determines whether or not it is a dog. If the animal is a cat, for example, the line of code delivers False. But if it’s a dog, it delivers True.

Now another line of code asks whether or not the dog is loose. If the dog is on a leash, then this line of code returns False, but if the dog is walking by itself with no leash, then the code returns True.

Here you have two true statements that will result in a certain action: one truth is that the animal is a dog, and the other truth is that it’s loose. When both these statements are True, the automated dog catcher goes ahead and chases down the dog. (Yes, this sounds like a horrible tech to me, too).

Sure, writing a dog-catching program is not quite that easy, but you get the point. Basically, everything in your code boils down to True and False statements.

These statements follow a specific logic when you combine them. That logic can hurt your brain a bit when you first start delving into it, but ultimately you (or, at least, I) start to see it as a thing of beauty. In fact, I prefer to see the following “rules”—which I took from Codecademy—as a kind of poem. Read it aloud and you might see what I mean:

The Boolean Operators at Work

True and True is True
True and False is False
False and True is False
False and False is False
True or True is True
True or False is True
False or True is True
False or False is False
Not True is False
Not False is True

Maybe someday you’ll want to memorize these basic Boolean rules, but for now it’s enough to just admire them. I should note that when you write something as simple as “6 > 5” (as we did above), it’s what’s known as a “condition.” In this case, the condition is “True”.

There are lots of ways of using conditional statements. In fact, you can weave them together in a virtually infinite number of ways.

PS – By the way, a really nice explanation of Boolean logic can be found at I PROGRAMMER.

Featured image from Joe Wos. Wikimedia Commons. 25 October 2020.

 If You’re Starting to List, How Bout a Slice? 

On how to slice Python lists and why it’s so helpful

When I think of a slice in the real world, I tend to think pizza. In the world of programming, however, I think of lists. And, like pizzas, they’re just begging to be sliced up.

In fact, you could argue that slicing and dicing data is what computing is all about.  In the Python coding world, lists are the pizzas (or maybe the loaves of bread or pieces of pie or whatever you fancy). As when you’re slicing up your favorite food, however, you’ve got to watch out for your digits.

Let’s harken back to our original list of poker buddies:

>>>pokerBuddies = ["Joe", "Shiho", "Jose"]

Go ahead and type that into your IDLE Shell and hit Enter.

Now, before we discuss slicing, I’ve got to tell you another weird thing about Python. It’s has an annoying habit. Let’s say Python holds up its proverbial finger and asks you what number it is. You say, “One, of course.” Python says, “No, dummy, it’s zero.”

That is, if you want to count to three in Pythonese, you count, “Zero, one, two, three.”

Here’s how that affects slicing. If you want to slice out the first name in the list above, you write:


Put that into your Shell and hit Enter. What the Shell should spit back out at you is:


That’s because you have sliced out the first item in the list (which is actually the 0 item in the list). That number represents what we call the slicing index, or just index.

Now try this:


This time you should see:


Obviously, you get the second item in the list. As long as you  count up from zero, it’ll be okay.

In the previous post, we showed you how you could remove a name from a list and add a different name. Here’s another way you can do it via slicing:

>>>pokerBuddies[0] = ‘Sarah’

What you’re doing is assigning the first position in the list to Sarah instead of Joe (Joe, as you’ll recall, has a nacho breath problem). Now, your list reads:

['Sarah', 'Shiho', 'Jose']

Okay, those are the basics. There’s oh-so-much more to this topic. In fact, some people might even object to calling this simple stuff “slicing.” Slicing, they might legitimately argue, involves taking more than one piece out of the pizza. For example, you can cut more than one name out of the list above. Here’s how:

>>> pokerBuddies[0:2]

This slices two names out of the list. Do you see that second index number, which is 2? Weirdly, Python requires that the second number be the number just beyond the last numbered item you want to slice. That is, if you want to slice out the first two names, you do not use, as you might expect, [0:1]. Rather, you use [0:2]. If you fool around with this list and longer lists, you’ll start to get the idea.

If you want more information on list slicing and lists in general, I recommend Dive Into Python and How to Think Like a Computer Scientist.

Feature image: A sign for pizza by the slice at a restaurant in San Francisco, California. Matthew Dillon from Hollywood, CA, USA - Pizza By The Slice. Go to https://en.wikipedia.org/wiki/Pizza_by_the_slice#/media/File:Pizza_By_The_Slice_sign.jpg

So, After Tupling, When Do You Start to List? 

On the crucial differences between tuples and lists in Python

Listing is sort of like tupling, except lists are more loosey goosey. The stuff in a tuple is more solid than rock. It can’t be changed, not with a chisel, a jackhammer or bunker-busting bomb (however, see the postscript below for a loophole).

Lists, in contrast, are more flexible than your average yogi.  The data in a list can be changed, and the lists themselves can grow longer or shorter at will (or close to it).

You recognize a list because it comes in brackets rather than parentheses. So, here’s an example of a list:

thisList = [“Joe”, “Shiho”, “Jose”]

What’s cool about the list is that we can swap elements in or out. Let’s say Joe is just getting too gross for the poker-playing gang, with his jalapeno nacho breath and his cheesy fingers. We dump Joe from the list and substitute in Sarah, who makes an awesome bean dip. She’s on the list now, and Joe is out.

Here’s how you could do that in Python:

thisList = ["Joe", "Shiho", "Jose"]
print (thisList)

That will print your new list, the one with Joe gone and Sarah added::

 ["Shiho", "Jose", "Sarah"]

If you try to do the same thing with a tuple, it won’t work. Therefore, if you need some flexibility, go with the list. If you need tight, anal-compulsive security, go with the tuple.

PS: If you want some more information on lists, I recommend TutorialsPoint.

PPS: Some experts have noted that tuples are immutable but not necessarily unchanging. Yeah, I know that sounds like a contradiction. To learn about it, though, have a look at “Python tuples: immutable but potentially changing”.

Features image: Brazilian poker player Maria Eduarda "Maridu" Mayrinck during the World Series of Poker, 2009, Author: Juliano Maesano. From https://commons.wikimedia.org/wiki/File:Maridu.jpg