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
Wikipedia

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:

>>>pokerBuddies[0]

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

'Joe'

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:

>>>pokerBuddies[1]

This time you should see:

'Shiho'

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"]
thisList.remove("Joe")
thisList.append("Sarah")
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

You Tipple Wine, But What Do You Tuple? 

On the meaning and usage of tuples in Python

I dig the word “tuple”. It sounds like a word you should know but can’t quite place. It makes me think about tipple, as in tippling wine at the gallery opening. That, in turn, reminds me of the Monty Python sketch called “Stock Exchange Report,” in which a reporter broadcasts, “Ting tang tong rankled dithely, little tipples pooped and poppy things went pong!”

Great, right? That, in turn, reminds me of Lewis Carroll: “Twas brillig, and the slithy toves did gyre and gimble in the wabe.”

What’s a Tuple?

But I digress. Back to tuples, a word that sounds like nonsense but is actually a mathematics term meaning an ordered grouping. One of the reasons it sounds familiar even to non-mathematicians is because it makes its way into the language in other ways, such as quintuple, sextuple, and octuple. So, when you think about some poor woman bearing quintuplets, think of them as a pretty darn long grouping of darling babies.

In Python world, a tuple is also like a grouping, consisting of a number of values separated by commas and contained inside parentheses.  Here’s an example of a tuple:

pokerFriends = ("Joe", "Shiho", "Jose")

Go ahead and type that into your IDLE shell and hit enter. Now, If you type the word “pokerFriends” into the Shell, it should spit out the tuple:

('Joe', 'Shiho', 'Jose')

So, now you have a tuple (which is a grouping, of course) that is called pokerFriends. The names, which are separated by commas, are the values. We could (and will) go deeper into these matters, but let’s quit for now. Just remember that you tipple wine and tuple values.

PS – If you’re the instant gratification type and want more info on tuples right now, you can try tutorialspoint or How to Think Like a Computer Scientist.

Featured image:  Dionne quintuplets, 1937, unknown author: https://commons.wikimedia.org/wiki/File:The-dionne-quintuplets_1937.jpg

Any Smooth Operators Around Here?

On how to use operators in Python

The world of coding takes a lot of its cues from the world of mathematics, so it’s no surprise that there’s a lot of stuff about “operators” in Python. Generally speaking, an operator is a symbol or function that tells the computer to perform certain logical or mathematical operations, such as addition, subtraction, multiplication, and division. You know what I mean: symbols such as + and  – and * and  /.

Even in the meager coding examples I’ve shown you so far, I’ve had to use an operator, the =, and explain how it is different from ==.  But there are plenty of other operators to be aware of. Python can do all the stuff a basic calculator can do. You just have to know how to wield your operators. Here are some examples of the arithmetic operators at work.

So, you can see that if you enter 5 + 2, for example, the program tells you that equals 7. Five minus 2 is 3. Five multiplied by 2…well, you get the idea.

But there’s some weird stuff here, as well. For example, why in the heck does 5//2 give you 2? Well, it’s because it’s dividing 5 by 2 and then rounding to the nearest whole number (aka, floor division). Another weird one is 5 % 2. Why does it give you 1? Because it is giving you the remainder of 5 divided by 2. That may seem strange at first but you’ll find these operators can be quite useful for writing various programs.

If I really wanted to bore you you silly, I could systematically go through the whole list of operators, which come in a variety of flavors, including (in addition to arithmetic operators) comparison operators, assignment operators, logical operators, identity operators, and even the (sometimes mind boggling) bitwise operators.

Rather than spend pages doing that, I recommend that you go to any of the great online resources that give you the full treatment, such as the following:

  • Tutorialspoint (which tells you how these work in direct English)
  • w3resource (which is great because it also tells you about the “shorthand” for assignment operators, which you’ll be running into a lot in other people’s code)
  • Python Programming wikibook (which is fairly self explanatory)
  • Python.org (which explains things in a much less intuitive way but does tell you about related functions, which we’ll get to later)

Operators are as boring to read about as your average Congressional record, but they’re important to know. If you have a tough time remembering them, then I suggest using online resources such as Quizlet or Anki to create flashcards for yourself. In some cases, people will already have made flashcards of them (see the Quizlet link), so you may only need to find theirs through a search. My motto is to use what other people have already made as often as you can. That is, when in doubt, take the lazy way out.

Featured image: Author:  Joseph A. Carr, Jersey Telecom telephone operator at switchboard, 1975, source: http://www.JoeTourist.net/, Wikimedia Commons 

Calm Down or You’re Going to Lose Your Variables

On how variables and values work in Python

The word “variable” sounds intimidatingly technical but it’s really just something that, well, varies — or, at least, it can vary. Let’s say you’re starting an exercise routine. You’ve gotten flabby and out of shape and your weight is up in the 230 pounds range (damn this scale!). So, you assign a number to your weight as follows:

weight = 230

Type that into your Shell and hit return. Now, if you type the word weight into your shell and hit return, you should get the number 230.

Let’s say you go on an exercise program and lose a little weight, then a little more, then maybe gain some weight back (the story of my life), and then lose some more again. You can keep assigning different numbers to the variable called weight. Therefore, you’re using the same word but assigning a variety of numbers to it. Variable…vary. Very logical.

See the below for an example of how this works as you assign different numbers to the variable we call weight:

Now, let’s say you’re talking about the cost of a tablet computer. When you buy it, it’s worth $800. A couple of year later, it’s worth about $300. And a year after that, you can only get $100 for it on eBay. So, our variable called tablet could be assigned various values depending on its age.

And, indeed, “value” is what we call the numbers that we assign to variables. Therefore, the last value of weight was 205 in the first example above. The last value of tablet we discussed was $100. The value of variables (just like human values) can shift over time.

I’ve been using a bit of extra jargon in this particular post: that is, the word “assign.” When you assign the value $100 to the variable tablet, you write it like this:

tablet = $100

You’re using the equals sign on your keyboard to assign a value. That would all be fine and dandy if there weren’t any math in computer programming. But there is. Sometimes you want your equals sign to actually mean “equals” rather than “assign.” When you add a couple of numbers in the real world, for example, you typically use an equals sign, as in 2 + 2 = 4.

Just for giggles, go ahead and put this into your Shell:

>>>2 + 2 = 4

Now, hit Enter. If you’re doing it right (or, in this case, wrong), you’ll get another error message:

SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

Thanks for the hint, Python! Indeed I did! So, let’s try putting this into the Shell:

2 + 2 == 4

Now hit your Enter key again. This time, Python should spit out the word True. You see, Python refused to use the single equals sign for math. It always wants the double equals sign if you’re doing math.

This can get annoying, but you’ve just got to live with it a while and allow it to become second nature. Think of it as one of those vexing habits of someone you love. You live with it because you love them. That habit still annoys the crap out of you until the day it becomes expected and even endearing. Welcome to Python world (or, for that matter, the world of programming).

At times, you can lose track of your variables. You think you’ve assigned some value to a variable and then you plug it into your code. Python, however, disagrees. It thinks you haven’t assigned a value to that variable yet. So, you get into a spat. Python always wins those spats, of course, because it is more logical and stubborn than you are.

You can get feel for Python literalness by looking at this:

You can see I’ve assigned the number six to Joe. If I type in Joe, Python spits out the number six. But then I type in Jo, and Python throws up an error message called a NameError. This time, it helpfully asks “did you mean: ‘Joe'”?

Which is groovy because when I first learned Python, I did not get those kind of helpful hints. Python has gotten a little smarter and more civil in recent years as it has mellowed.

The bottom line, however, is that should try to avoid losing track of your variables. If you’re programming, you’re going to need them.

PS – If your looking for more information about variables, you might want to try tutorialspoint and/or learnpython.org

Featured image is a cartoon created by Gunny Wolf. Author is Marines from Arlington, VA, United States. See Wikimedia Commons at https://commons.wikimedia.org/wiki/File:Calm_Down_(8455073021).jpg

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

What’s a String and What’s Knot? 

On how strings work in Python

Strings are the things stuck between quotation marks.  It’s like dialogue in a book, except a bit knottier.  So, “Hello, it’s me” is a string. Using IDLE (see previous post), try printing that out in Python 3 like this:

>>>print (“Hello, it’s me”)

It should work like a charm. Now, try this:

>>>print (Hello, its me)

This time, I’ve set you up for failure. You should have gotten the annoying message: SyntaxError: invalid syntax. That’s because Python is looking for a string here and won’t accept it without some quotation marks. It’s like having a super strict elementary school teacher who will not cut you any slack (yes, I’m looking at you, Mrs. Decker!). But Python will also accept some other versions of quotations marks to make a string. Try these two versions in your Shell:

                                                >>>print ('Hello, it is I')
                                               >>>print ('''Hello, it is I''')

Those should work. Bottom line: you can use single, double, or even triple quotation marks to make a string. (Mrs. Decker would have hated that.) Now, try this:

                                                >>>print ('Hello, it's me')

That should give you another error, this time a “SyntaxError.” That’s because Python can’t tell the difference between a quotation mark and an apostrophe. In its little literal mind, it sees three quotation marks and so can’t tell where the string is starting and ending. So, it’s not quite a string. It’s more of a knot. And knots will tangle you up. Kind of like a real python will. Beware.

Indian Rock Python Python molurus. Photographed by Dr. Raju Kasambe at Keoladeo National Park, Bharatpur, Rajasthan. Wikimedia Commons.

PS – There are about a bajillion ways of messing around with strings. For a long list of ways of playing with string, I recommend you have a look at the official list of string methods. Just don’t let the list intimidate you. For most folks, only a handful of these are used on a day-to-day basis.

The Yggdrasil Effect

Without trees, our planet and our lives would be dramatically different. Indeed, given the fact our ancestors lived in trees, it’s certain we would not be here at all.

Trees do so much, in fact, that I think we can classify their impact as the Yggdrasil Effect. Yggdrasil, of course, is the immense and sacred tree of Norse mythology. The branches and roots of the great tree connect the various parts of the cosmos. Yggdrasil is not, however, in perfect health thanks to serpents that chew at its roots and stags that chew on its leaves. In short, the great tree–and therefore the cosmos itself–is mortal and under constant threat.

The Yggdrasil Effect highlights both the many essential functions of trees in our world as well as their essential fragility and mortality.

Pumping the World Up

According to myth, Yggdrasil has three major roots that it uses to pump water from three magic springs or wells, presumably pushing those waters to the rest of the cosmos. In real life, trees play a similar role. If it weren’t for trees, in fact, most of today’s dry land would be deserts.

You see, clouds form over oceans (where most of the water is, of course) and then those clouds float over nearby land, whereupon they unleash the rain they contain. Wohlleben writes. “If depended on just this mechanism for water, life would be possible only in a narrow bank around the edge of continents.”

So, what do trees do to pump water into the rest of the world? First, they spread their canopies over the land. After the rain falls, much of it remains in the canopies where it evaporates again rather than just running off back into the oceans. “In addition,” Wohlleben writes, “each summer, trees use up to 8,500 cubic yards of water per square mile, which they release into the air through transpiration. This water vapor creates new clouds that travel farther inland to release their rain. As the cycle continues, water reaches even the most remote areas.”

So, if you happen to live in a place is not near a coast but where you get a goodly amount of rainfall, you can thank the trees.

Altered Carbon

You may have heard that the world has a carbon problem. Global monthly average concentrations of carbon dioxide have risen from around 339 parts per million in 1980 to 412 parts per million in 2020, an increase of more than 20%. More carbon means more global warming, which means all kinds of bad stuff, including more frequent and devastating forest fires.

But as long as they are not being incinerated, trees are amazingly good at pulling carbon dioxide out of the air and storing it in their bodies. Even once the trees die, much of the carbon is stored underground as they disintegrate into the forest floor. Wohlleben writes,

It’s true that some of this carbon dioxide does indeed return to the atmosphere after a tree’s death, but most of it remains locked in the ecosystem forever. The crumbling tree is gnawed and munched into smaller and smaller pieces and worked, by fractions of inches, more deeply into the soil….The farther underground, the cooler it is….And so it is that carbon dioxide finds its final resting place in the form of humus, which continues to become more concentrated as it ages.

If we could just stop burning all the ancient carbon that is stored below ground in the form of carbon-rich fossil fuels, then eventually the trees could capture much of the carbon in the air and once again cool down our ever-hotter planet. It’s nice to plant more trees, of course, as a way of vacuuming and storing carbon, but it’s even better if we can leave the older trees alone to do their thing. The larger tree, the more quickly it grows in terms of total biomass, thereby sucking up more carbon.

Controlling the Climate (for Reals!)

Controlling the weather has long been a trope in the world of fiction. (Typically associated with carton villains: Simon Bar Sinister anyone?) In the real world, we haven’t gotten very far with weather control aside from some cloud seeding. On a larger scale, of course, there’s the climate, both global and regional. We’ve been affecting climate via our massive global bumbling with greenhouse gases, but this is a case where we’ve changed it for the worse for our own species (not to mention so many species).

Simon Bar Sinister

Trees, however, have a much better track record in this area, able to create their own climates, both macro and micro, for their own benefit. We’ve already discussed the macro aspect of pumping water all over the planet (which obviously serves the need of trees as well as humanity). But trees are also pretty good at affecting climate on other scales. Wohlleben provides the example for a little forest of beech trees.

With their annual leaf fall, the beeches created an alkaline humus that could store a lot of water. In addition, the air in this little forest gradually became moister, because the leaves of the growing beeches calmed the air by reducing the speed of the wind blowing through the trunks of the pines. Calmer air meant less water evaporated. More water allowed the beeches to prosper…

In short, the beeches became part of a positive feedback loop, helping to create an environment in which they could thrive. Now that’s an excellent case of climate control.

Beneath the Arms of Giants

Wohlleben also refers to tree-driven “microclimates.” When I read that, I could immediately relate. We have an oak tree in our front yard, which feels so different from our back yard that they might as well exist in separate dimensions. Whereas the front yard often feels cool and moist even in the heat of the summer, the back yard feels parched and blazing hot, especially in the summer. In the Florida winter, the temperature is somehow more moderate under the tree, a characteristic that made more sense when I learned, according to Wohlleben, that “trees sweat.”

Huh. So that’s why our cars don’t get frost on their windshields in the winter as they did when we used to parked them on a treeless corner in the same city. They’re kept warmer under the giant, radiating, sweaty tree. I’m not sure if that’s gross or comforting. Maybe a bit of both.

Of course, I was perfectly aware that parking under a tree is messy, though I never quite considered it was because trees shed bits of bark and sticks in the same way we human beings shed our skin (which is where so much of the dust in our houses come from–I know, ew).

In short, trees are literally the moist, smelly, sweaty, shedding giants in our midst, so big that they create the micro-climates in which we live. I suppose we know that at some level. On another level, however, we often tend to see them as inanimate things such fences, pillar, streetlights and the roofs of houses. Maybe that’s because we hold their lives in our hands. Viewing them as beings rather than things means we have responsibility for these giants on whom we so depend. It’s a lot of pressure. I suspect many of us would rather not think about it.

Note: This post covers some of the material in chapters 16 to 18 in The Hidden Life of Trees.
Featured image: The norns Urðr, Verðandi, and Skuld beneath the world tree Yggdrasil (1882) by Ludwig Burger. https://en.wikipedia.org/wiki/Yggdrasil#/media/File:Die_Nornen_Urd,_Werdanda,_Skuld,_unter_der_Welteiche_Yggdrasil_by_Ludwig_Burger.jpg