An (“Evolving”) [List] of Python Resources

This list of Python resources for beginning coders is in (mostly) alphabetical order. I haven’t tried to provide different headers for videos versus MOOCs versus books, etc. I figure you can always search the page if you’re looking for something in particular. Where I can, though, I’ve given you the sometimes dubious benefit of my first-hand knowledge. In other cases, I’ve gone by what the website says or let you know what I’ve heard from others.

If you know of other sources that you think could be on this list, please shoot me a comment. Also, clue me in if any of the links don’t work properly.

16 Resources to Learn Python Programming: A shortish list of some of the best resources for learning Python. Many of these resources also appear in my list below, but there are few here that I’ve not yet checked out.

80+ Best Free Python Tutorials, eBooks & PDF To Learn Programming Online : A nice collection of resources. I especially like its list of cheat sheets, which is something few other resource guides provide.

After Hours Programming Python 3 Tutorial: An online tutorial with which I’ve not had much experience. It does have a code simulator, but it doesn’t seem to require you to code something correctly to move on with the tutorial. That can be a good thing when you’re sick of being tested, and it can be a bad thing when you need to be really challenged.

The Best Way to Learn Python: A handy, dandy list of some great Python resources.

Bootcamps: Bootcamps are places (physical or virtual) you go to learn specific programming skills in a matter of a few weeks. I’ve never attended one, but there are a number of websites devoted to helping you distinguish one from another. They include SwitchUp, Techendo, and Bootcamps.in. Bootcamps can be quite pricey, so it pays to be cautious and selective.

Byte of Python: An introductory text for beginners. For the most part, I think it’s clearly written. The author, Swaroop C.H., wrote it for Python 2, then updated it to Python 3, and then revised it back to Python 2 for reasons he explains in his book. But I’m glad I still have his PDF version on Python 3 on my mobile.

Check iO: I have a crush on this gamified tutorial (or, maybe it’s more of a game that teaches). Here’s the hitch: you need to solve the problems before you can see how other people of have solved them. This drives me mad, though usually in a good way. I don’t have the chops to get to the end anytime soon, but it’s a terrific vehicle for taking my own lame solutions and then comparing them against some other tightly written solutions by programmers who are much better than I. This is usually humiliating, but also in a good way. And it’s a great way to learn how to write code that is more Pythonic.

CodeBuddies.org: This is a group of people who meet on Google Hangouts at scheduled times to talk about code (usually as it relates to specific books or projects) while sharing their screens. It’s intended to help participants stay motivated and learn faster. I’ve only been to a few hangouts, but it seems worthwhile.

Codecademy: It has a very good, interactive online Python tutorial as well as a community to help support it. I recommend it.

Codementor: For a fee, this service “connects you with experienced mentors for instant help via screen sharing, video, and text chat.” I’ve not yet used it, but I’ve been tempted a few times when banging my head on an especially recalcitrant problem.

Computer Game Development Tutorial: This is a series of videos on how to develop games in Python.

Computer Science Circles: A nice little interactive online tutorial sort of along the lines of the interactive version of How to Think Like a Computer Scientist, which I reference below.

Dive into Python 3: Classic book on Python that can be found online.

Drag and Drop Programming: A growing number of sites allow beginning programmers to build code by dragging and dropping “blocks” (or other visual widgets)  rather than manually writing text-based code.  These do not necessarily use the Python language, but they are a place where beginners — including children — can go to get a feel for how to code. Among them are MIT ScratchCode.org, and Google Blockly. There’s a blurred boundary between these types of sites and sites that teach via gamification.

The Django Book: If you hang around the Python community for any length of time, Django will come up. It’s a Web framework — meaning, that you can use it to write Web apps — written in Python. Last time I looked, this particular book came with a warning about being out of date, though the site indicated it was in the process of being updated. I’ve read that the official Django tutorial is good and that Tango With Django is another useful resource.

Exercism.io: Here’s how Wired described it: “Exercism is updated every day with programming exercises in a variety of different languages. First, you download these exercises using a special software client, and once you’ve completed one, you upload it back to the site, where other coders from around the world will give you feedback.” Exercism may be a sophisticated, crowd-sourced learning experience, but, at least for now, it requires you to use GitHub and command lines. In other words, it’s somewhat complicated to get off the ground with it. Still, if you’re beyond the early beginner stages, it may be a natural next step. Newcoder.io/ seems to be a similar site.

Instant Hacking: A super, duper abbreviated tutorial designed to teach Python on the fly.

Intro to Computer Science: I started and took a large segment of this Udacity MOOC when it was still relatively new. I enjoyed it. As far as I can tell, the courseware is still free, but there is paid version that includes extras such as project feedback, personal guidance, personalized pacing support, and a verified certificate.

Game-Based Learning: I’ve already mentioned Checkio, which is geared more toward adults, but there are other games as well that are even more “game-like” and sometimes geared toward younger audiences, including CodeCombat, Codingame, and Code.org. PythonChallenge is closer to Checkio but, instead of starting with pretty clear instructions about what goal you need to achieve, you have to interpret clues as you go along. I should note that some games (such as CodeCombat) are free to start but charge you something, such as a monthly subscription fee, once you’ve ascended to certain levels.

Google (and not just the search engine): It’s no secret that the famous search engine is often the coder’s best friend. You put a question into the magic rectangle and it serves up lots of possible answers, usually good ones. And then there’s Google’s Python Class, which has both text and video. It’s fun largely because it is delivered to Google employees in what I assume is a Googleplex classroom.

Hands-on Python Tutorial: This is actually a full university course taught by Dr. Andrew N. Harrington. I like it very much, having stumbled onto it via iTunes.

The Hitchhiker’s Guide to Python!: Bills itself as an “opinionated guide [that] exists to provide both novice and expert Python developers a best-practice handbook to the installation, configuration, and usage of Python on a daily basis.” Most of what I’ve read is not for rank beginners, but there seems to be a lot of canny advice. It also contains a good list of other Python resources.

How to Build a Python Bot That Can Play Web Games: This is based mostly on text and screenshots, and it entails building a Computer Vision-based game bot in Python.

How to Think Like a Computer Scientist: Various versions of this book exist, but my favorite is the interactive version to which I’ve linked here.  In my experience, it is a fine blend of beginner book and online tutorial. I hope more computer “books” will follow this approach in the future.

Introduction of Python’s Flask Framework: Like DjangoFlask is a Web framework for Python but it is often billed as smaller and easier to learn. Therefore, it may be an appropriate starting place for beginning programmers who want to use a Web framework.

Invent with Python: I’m a big fan of the book Invent Your Own Computer Games, which is geared toward kids but which is terrific for beginner programmers. There’s a free online version. It takes you through the process of code for specific games. He note only provides all the code but shows you how and why it works. There’s nothing else quite like it, in my experience. The author, Al Sweigart, has also authored Making Games with Python & Pygame and Hacking Secret Ciphers with Python, also available for free.

Invent with Python Bookshelf: This is a very nicely laid out list of books, many of which can be gotten for free. Al Sweigart, the owner of the site, not only includes his own books but many others as well.

Learnpython: This is an interactive Python tutorial that has a set of tutorials that teach the basics as well as more advanced lessons. I’ve used it and liked it. It’s straightforward, fast and without many bells or whistles.

Learn Python The Hard Way: Based on my experience in online communities, a lot of people use and swear by this. I’ve gone through parts of it. Some people say they’ve done it in a weekend, but I know I couldn’t complete it that quickly. There’s a free book online and also a relatively inexpensive (last time I checked) course that includes videos, among other things.

Introduction to Computer Science and Programming Using Python: An introduction to computer science as a tool to solve real-world analytical problems using Python 3.5.

Nettuts+’s Python from Scratch: This is a combination of text and video that demonstrates the “ins and outs of Python development,” starting from the most basic levels possible.

Non-Programmer’s Tutorial for Python 3: Also not interactive but, as with the 2.6 version, a nice set of Wikibooks-based lessons on learning the basics.

One Day of IDLE Toying:  A succinct introduction to IDLE, which stands for Integrated DeveLopment Environment. It’s the “integrated development environment” (that is, the doodad into which you write and run your programs) that’s bundled with Python, so you have it when you download the program.

Online Python Tutor: Free educational tool that allows a teacher or student to “write a Python program in the Web browser and visualize what the computer is doing step-by-step as it executes the program.”

Programiz: I stumbled on this site while looking for information on keywords in Python. Not only does it have an excellent explanation of keywords, complete with sample code, but the other parts of the online tutorial also look very clean and helpful. I’m looking forward to getting to know this site better.

Primers on Python: There are surprisingly few good, short, introductory Python primers online. As I’ve been learning, I’ve created the oddball Quick and Quick for Python, and I recommend First Steps With Python as a less quirky alternative. One (perhaps overly) succinct work is Patrice Koehl’s Python Primer. There’s also Crash into Python, although I think that’s geared toward people who know how to code but are new to Python.  A Beginner’s Python Tutorial seems like a pretty nice tutorial for complete beginners, and I think After Hours Programming can also be a useful primer.

Programming for Everybody (Python): A University of Michigan MOOC from Coursera. You’ll need to register and login to see it. I’ve not taken this course. Last time I looked, there were a number of other Coursera offerings was well, such as  An Introduction to Interactive Programming in Python and Algorithmic Thinking from Rice University.

Pygame: A  set of modules designed for writing games in Python.

Python 3 Programming Tutorial: This is a series of videos on Python programming on YouTube. Generally speaking, YouTube is an amazing source of knowledge about programming and software usage in general. I’m pretty sure I could spend weeks there just watching hundreds of Python-related videos.

Python Books: From the official Python website, this is a list of books for both beginners and advanced practitioners. From what I can tell, it’s regularly updated (which is not always the case for other book lists). Here’s a much shorter list from a different source.

Python Course: By U.S. standards, this isn’t a course but, rather, an online tutorial that is almost all text and graphics. It has tutorials for both Python 2 and Python 3, and these tend to have pretty good explanations: or, at least, better than a lot of the official Python documentation, in my view.

Python for Beginners: From the official Python website, it has recommendations for installing, learning and otherwise investigating Python.

Python for Non-Programmers: From the official Python website, it has links to video tutorials, online courses, websites, books, and resources for younger students.

Python for You and Me: This simple but effective online book is written for programmers new to Python.

Python Turtle: I haven’t downloaded this but have used a version in a tutorial. It was fun. In essence, you write code to move your animated turtle in various ways. It “strives to provide the lowest-threshold way to learn (or teach) software development in the Python programming language.”

Python Docs: These are from the official Python.org website. My experience is that these contain a ton of great information but are, at times, difficult to parse. I sometimes need to go to other tutorials that are easier to understand, but I often start here.

Python Weekly is a “A free weekly newsletter featuring the best hand curated news, articles, new releases, tools and libraries, events etc. related to Python.” I receive it and enjoy it, but I find that it’s geared to more seasoned Python coders rather than to beginners.

Pythonic Perambulations is not a blog for beginners but it’s well-written and fun to read (even when I can’t quite grasp the details). Think of it as aspirational. When you start to really grok this blog, you’re past the beginner phase.

StackOverflow: If you do a Google search to find out how you do something in Python, you’ll likely be directed to this website, which is where both beginners and experts go to ask questions and have those questions answered by various Python programmers. It’s invaluable. Because this has been going on a while, your question has usually already been asked and answered here, so do a search before asking anything.

Steven Thurlow’s Python Tutorial: I stumbled onto this tutorial while looking for a decent explanations of modules  and classes. I believe his are the clearest I’ve seen anywhere.

Stupid Python Ideas: I’m only beginning to be able to parse a blog like this one, which goes into detail on more sophisticated Python coding concepts and practices. This blog strikes me as one of the clearer ones. It has helped me, for example, understand how the function called grouper works. I just couldn’t understand the official documentation on it.

Ten Python Blogs Worth Following: I’m not really up on which Python blogs to follow, but here are some recommendations by the author of Bite Sized Python Tips.

Tutorials Point: When I’m searching Google to find out how to do something in Python, I often wind up here, especially if I can’t understand the official Python documentation (a not uncommon occurrence for me). The explanations here tend to be written in clear English and the examples are usually helpful. You can also move through the tutorial in a systematic way if you like.

Twitter accounts: There are four that seem particularly worth following to me:  @ThePSF @planetpython @gvanrossum. I’m always interested in following other accounts if you have any recommendations.

Featured image: Català: Poema visual transitable en tres temps (Joan Brossa). Segon temps: camí -amb pauses i entonacions-. Jardins de Marià Cañardo, Velòdrom d'Horta (Barcelona). Author: Dvdgmz

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

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

with

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

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

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

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

Presto!

 yield

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

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

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

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

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

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

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

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

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

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

Featured image by Edithobayaa1: a crate of eggs in Ghana

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

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

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

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

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

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

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

and

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

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

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

or

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

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

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

not

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

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

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




 While Not ee cummings

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

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

as freedom is a breakfastfood

or truth can live with right and wrong

or molehills are from mountains made

—long enough and just so long

will being pay the rent of seem

and genius please the talentgang

and water most encourage flame

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

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

cummings()

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

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

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

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

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

The ABCs of Python: “raise,” “return,” “while” and knowing when to quit

Here are three more keywords. I know they look like a bit of a hodgepodge. Perhaps I should have discussed raise when I discussed the other exception handling words and while when covering for and in.  But, at least this way I get to keep some semblance of alphabetical order. What’s more, as I wrote this, I realized there’s a common theme for all these keywords: that is, they help our code know when to quit.

raise

In Python, the keyword raise is used to “raise” a virtual penalty flag for the user, telling them that there’s a problem.  You may remember our power_up_index function from before. We’re going to put it back into action, except we’ll engage the keyword raise.

def power_up_index(array, n):    

    '''
    Find Nth power of the element with index N.
    '''

    if len(array) < (n +1):
        raise IndexError
    else:
        return array[n]**n
   
print(power_up_index ([20, 12, 99, 15, 78], 3))
'''
n is the number 3 in this case. So, you pick the third
number, which is 15 in this case, and multiply that 
number by itself three times.
'''

print(power_up_index([1, 2, 3, 4], 2)) #you multiply the second number, which is 3 
                                       #since Python counts from 0, 
                                       #by itself two times so you get 9

print(power_up_index([1, 2], 3))
'''
you get an error message -- specifically an IndexError -- 
because the computer cannot locate the third number in 
this array (which only has two numbers,
as you can see).
'''

This code will produce something like this:

3375
9
raise IndexError
IndexError

return

When first learning to code in Python, there were few words more puzzling  to me than return.   I kept wanting to use print statements in lieu of return because I could see some results from print statements whereas not much seemed to be happening when I used return.  I didn’t quite grok its critical function. The depth of ignorance must seem bonkers to any seasoned coder.

So, when do you use return and what does it do? Here’s a metaphor. There’s a busy person who never goes to the post office or a public mail box to post a letter. Instead, she sticks her outgoing mail in her private mailbox when she is leaving to go to work in the morning. The postal worker picks up her outgoing mail and then posts it for her.

In a sense, this is how return works.  It only lives inside a function, as the woman lives in her house. It is used to exit the function and provide some sort of value. So, imagine the woman going to her mailbox and posting a letter with a single value on it. Maybe the value is a number or a string or a Boolean, but it’s something useful.  That message gets sent somewhere else (maybe to another function) where it becomes essential input. Failing to put the return in the function is sort of writing a letter and then forgetting to put it in the box. Nobody gets it.

It’s also sort of like posting a blank sheet of paper. That is, when you forget to add a return statement, the function will not know what to do and so just spit out the word None.

Of course, a simpler metaphor is that return hits the Enter key in your code. You’re not going to input much without hitting that key.

Anyway, here’s a quick example of how it works, an example inspired by the one in Programiz:

def send_letter():
    x = "letter"
    return x

print(send_letter())


def send_nothing():
    x = "letter"

print(send_nothing())

If we run this code, we’ll see that the first print statement produces the word “letter”. The second one, however, will produce “None”. That’s because we forgot to “post the letter” — that is, forgot to add the return statement in that function.

I should note that there are cases of functions that don’t require a return, such as the on-the-fly functions produced with lambda.  And there is also code that only needs to do something (such as print a statement) without returning anything. But let’s keep things simple for now. Just remember that if you write a function without a return, then the function doesn’t produce a value (except for None) even if the rest of the code in your function is perfect.

while

We won’t dwell too much on the supremely powerful while keyword because I wrote a whole post on it before. Just remember that while is used to create loops and that those loops will continue to run until the condition (or conditions) for them no longer applies (or until the loop runs smack into a break statement).  If you write a while statement incorrectly (which is not so hard to do), your code will get stuck in an infinite loop that will ultimately crash your program (if that happens, use Control-C). Here’s a simple program that uses while.

numbers = list()
counter = 0
while (counter <= 20):
    numbers.append(counter)
    counter = counter+2
print(numbers)

You should end up with a list like this: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Note that this program hinges on the line counter = counter+2. That line increases the value of counter until it is equal to or more than 20, thereby letting the code know when to stop  And knowing when to stop is one of the great secrets in life

For more information on keywords, I recommend Zetcode

The ABCs of Python: The Not-Nothingness of “None”

Another keyword. This time it’s a widely misunderstood and high-profile one:

None

None is not what your typical English-speaking, non-coder might expect. That is, None is not just another way of expressing zero (or zip, zilch, nada, bubkis, or diddly–squat, for that matter). In fact, None is not equal to zero at all. If we assert that None is equal to zero, Python will set us straight, as follows:

>>> None == 0
False

None is also not equal to an empty list:

>>> None == []
False

As we mentioned when discussing del, you don’t utterly eradicate something when you assign it to None. Rather, None indicates that something doesn’t have a specific value even though it exists as an object. It literally becomes a “Nonetype,” which is a unique ghost in the Python universe.

>>> x = None
>>> x
>>> type(x)
<class 'NoneType'>

So, what the heck does one do with a NoneType, anyway?

In a sense, your function will return None as a sort of last resort or shrug of the shoulders. It says, “Yeah, this is all I got and it’s pretty much bubkis” and then shoots out a None.  For example, try to call and print the following function:

def return_not_nothing():
    big = "a big fat bowl"
    nearly_null = " of not nothing"
    squat = big + nearly_null
    return squat
print(return_not_nothing())

If we run this code, it produces “a big fat bowl of not nothing”

Now, run it again without officially returning anything (that is, without the last line of the function).

def return_not_nothing():
    big = "a big fat bowl"
    nearly_null = " of not nothing"
    squat = big + nearly_null
print(return_not_nothing())

This time the code produces None.

Why? Because even though the code is doing something, it doesn’t actually produce a value. In lieu of a value, it automatically returns None.

Sometimes a function will usually return a value but occasionally return None. The function below, for example, will return a None about one out of 10 times. That’s because we haven’t told it to return anything in particular if random.randint selects a six.

import random
def re_turn_squat ():
   big = "big fat bowl"
   null = " of not nothing"
   if random.randint(1,10) != 6:
       squat = big + null
       return squat
print(re_turn_squat())

So, is None the same as null in some other computer languages? Well, it can be a close cousin, but None is not the lack of an object (as a null reference can apparently be) but, as we mentioned, a kind of unique object. Using my best Zen-like thinking, I tend to think of it as the sound of one computer shrugging.

For a deeper look at None, I recommend the following:

PythonCentral

The History of Python

Programiz

Featured image is the enso, a symbol of Zen Buddhism,
 by Zenwhat

The ABCs of Python: The Silence of the “lambda”

Just for minute or so, forget what lambda can do for you. Savor the sound of the word itself. The accent is on the first syllable. It has a sophisticated, round and educated sound to it.

It’s also a cool-looking word in English, partly because it’s redolent of various animals: lamb, lama, panda. You can just about envision its surreal advent through a shadowy forest.

The word also feels ancient, and so it is, being the 11th letter of the Greek alphabet. Some version of the lambda sound probably rolled off Homer’s tongue as he chanted his epic poems.  We can imagine Sophocles using it to write his tragedies, Herodotus his histories, Aristophanes his comedies, and Aristotle his philosophies.

Since the time of those famous ancients, this one letter name has taken on many other meanings. There is lambda as a type of calculus, and lambda the junction in the brain, lambda the uncharged and unstable elementary particle, and lambda the phage.

And then there’s lambda the Python keyword, the one that can be used to create small, anonymous functions and procedures that are often concocted on the fly, nearly as obscure, silent and subtle as the elementary particle or the bacterial virus.

Lambda is something Python beginners should learn, if only to be able to comprehend the more Pythonic lines of code written by the more practiced wielders of the form. There have been times when I’ve written programs of 20 lines or more, only to discover that the same purpose could be achieved in one or two written with the lambda. It’s simultaneously breath-taking and maddening. (I should note, though, that lambda isn’t magic. You can write very succinct code when using standard forms of functions, as well. But lambda can help condense and add flair.)

Here’s an example of a simple function with the familiar def:

def cubism (root):
    return root**3
print(cubism(10))

Now here’s an example of lambda equivalent:

y = lambda x: x**3
print (y(10))

They do the same thing and get the same result (that is, 1000). We could even use the same terms, if we like. The lambda version is, however, a little less easy to read for the beginner unfamiliar with its syntax. That is due, in part, to the fact that lambda doesn’t need a return. Python automatically returns whatever expression is provided: in this case, x**3.

(By the way, an “expression” is code that returns some sort of value, as Python Conquers The Universe makes clear.  Lambda is more limited than a normal function in that it can only take one expression.)

Lambda often goes hand in hand with tools such as filter(), map() and sort(). Let’s use sort() on a list of the dwarves from The Hobbit to give you an idea of how it works. Here, we are using lambda to create three different functions on the fly that give us the list sorted by three different criteria:

We tell sorted to sort the tuples by a specific “key,” and that key is a lambda function. For example, in the first one, “lambda height” tells Python, “We are defining a quick function called ‘height’.” The next part, which is “height[1]”, works on the second item in each tuple in the list, all of which are indicators of the height of the dwarves.

Image by Rotox: Wikipedia
dwarves = [
('Fili', 126, 'blue'),
('Kili', 125, 'blue'),
('Oin', 134, 'brown'),
('Gloin', 136, 'brown'),
('Dwalin', 132, 'green'),
('Balin', 139, 'red'),
('Bifur', 137, 'yellow'),
('Bofur', 135, 'yellow'),
('Bombur', 140, 'green'),
('Dori', 141, 'purple'),
('Nori', 138, 'purple'),
('Ori', 133, 'grey'),
('Thorin Oakenshield', 145, 'blue')
]

print("A list of the Thorin's company sorted by height in cm: " 
+ str(sorted(dwarves, key=lambda height: height[1])))

print('')

print("A list of the Thorin's company sorted by name: " 
+ str(sorted(dwarves, key=lambda name: name[0])))

print('')

print("A list of the Thorin's company sorted by color of hood: " + str(sorted(dwarves, key=lambda hood: hood[2])))

We get the following:

A list of the Thorin’s company sorted by height in cm: [(‘Kili’, 125, ‘blue’), (‘Fili’, 126, ‘blue’), (‘Dwalin’, 132, ‘green’), (‘Ori’, 133, ‘grey’), (‘Oin’, 134, ‘brown’), (‘Bofur’, 135, ‘yellow’), (‘Gloin’, 136, ‘brown’), (‘Bifur’, 137, ‘yellow’), (‘Nori’, 138, ‘purple’), (‘Balin’, 139, ‘red’), (‘Bombur’, 140, ‘green’), (‘Dori’, 141, ‘purple’), (‘Thorin Oakenshield’, 145, ‘blue’)]

A list of the Thorin’s company sorted by name: [(‘Balin’, 139, ‘red’), (‘Bifur’, 137, ‘yellow’), (‘Bofur’, 135, ‘yellow’), (‘Bombur’, 140, ‘green’), (‘Dori’, 141, ‘purple’), (‘Dwalin’, 132, ‘green’), (‘Fili’, 126, ‘blue’), (‘Gloin’, 136, ‘brown’), (‘Kili’, 125, ‘blue’), (‘Nori’, 138, ‘purple’), (‘Oin’, 134, ‘brown’), (‘Ori’, 133, ‘grey’), (‘Thorin Oakenshield’, 145, ‘blue’)]

A list of the Thorin’s company sorted by color of hood: [(‘Fili’, 126, ‘blue’), (‘Kili’, 125, ‘blue’), (‘Thorin Oakenshield’, 145, ‘blue’), (‘Oin’, 134, ‘brown’), (‘Gloin’, 136, ‘brown’), (‘Dwalin’, 132, ‘green’), (‘Bombur’, 140, ‘green’), (‘Ori’, 133, ‘grey’), (‘Dori’, 141, ‘purple’), (‘Nori’, 138, ‘purple’), (‘Balin’, 139, ‘red’), (‘Bifur’, 137, ‘yellow’), (‘Bofur’, 135, ‘yellow’)]

Okay, there’s more to be said on the subject of lambda, but this gives you at least glimpse of the strange beast. For more on lambda, I recommend the following:

Yet Another Lambda Tutorial

Bogotobogo

Official Python Documentation on Lambda Expressions

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

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

global

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

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

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

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

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

nonlocal

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

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

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

This is what will print out:

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

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

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

The ABCs of Python: “from”, “import” and rolling the dice

Here are two more keywords in Python. We’ll take them in reverse alphabetical order because our explanations should make more sense that way:

import

The keyword import is one of the very best friends of the lazy (some would say “productive”) programmer. Using import, you can bring pre-made modules into your program. Let’s say, for example, that you want to be able to inject some randomness into your code (although that sounds bad, it can be fantastically useful) but you don’t especially want to spend time writing up unique functions for achieving that. So, you write the following:

import random

Now, you can use any of the functions that are part of that module. You can, for example, use the randint and the randrange functions.  Maybe you want to randomly select one number from 2 to 50 and you want to select another from the same range but only if it’s an even number (that is, the outcome could be 2 or 4 or 6, etc.). After you’ve imported random, You can write:

print (random.randint(2,50))
print (random.randrange(2, 51, 2))

from

Now let’s say you don’t need to use multiple functions from the random module. You just need the one called randint. You can do it this way:

from random import randint
print (randint(1,6))

This will give you a random number between 1 and 6, as if you were rolling a virtual dice.

So, when should you use the from statement to import just one function from a module? Good question. Unfortunately, there’s no clear answer. It’s a bit of a roll of the dice since each has its advantages and disadvantages. If you want to know more, I recommend the ‘import module’ or ‘from module import’ discussion in Stackoverflow.

Featured image: Diacritica - Own work; Wikimedia Commons

The ABCs of Python: “False,” “True,” Stephen Colbert and Santa Claus

It could reasonably be argued that the two most important keywords in Python are False and True. As we noted in Are Booleans from Outer Space?, almost everything in Python  boils down to these concepts. Let’s start with the latter.

False

False means, as you would expect, “not true.” But that doesn’t quite state the immense importance of False (and, yes, Python wants the word capped). Python has a deeply encoded instinct for falsehoods. Just as Santa Claus knows when you’ve been good or bad, Python knows when you’ve been True or False (at least within confines of basic mathematics).

Python is not, however, strictly mathematical in its reasoning. It has other opinions about False that are only logical from its own computer program perspective. For example, it views the number 0 as False and the number 1 as True. Although this sounds odd, it is logical from a Boolean perspective and turns out to be immensely useful in certain programs.

The following code, when put into your IDLE shell, gives you a taste of how False works:

>>> 7 == 8
False
>>> 9 > 10
False
>>>False == 0
True
>>>False == []
True
>>>[] is []
False

True

This keyword is, of course, the other side of the same coin. Not only does Python tell you when basic mathematical assertions are True, it’ll also perceive some other circumstances as True. The following code gives a sense of how it works:

>>> 5 * 5 == 25
True
>>> 5 + 5 == 10
True
>>> True == 1
True
>>> square = 4
>>> square == 4
True
>>> square == 3
False
[] == []
True

Stephen Colbert

As the former incarnation of Stephen Colbert might have said, that there’s just not enough “truthiness” in Python. You can’t claim something is True just become because it “feels right.” In a way, Python is your anti-Colbert, always basing its arguments on rigorous logic. On the other hand, it’s quite possible to get your computer to tell falsehoods, as long as you correctly evaluate its underlying, internal logic. In this, perhaps, maybe all computers can demonstrate an element of truthiness of which Colbert would be proud.

Featured image: 1881 illustration by Thomas Nast 

Stephen Colbert photo from Montclair Film, https://www.flickr.com/photos/montclairfilmfest/49205031397/

The ABCs of Python: The Identity of “is”

is

In English, no verb is more profound than “to be”.  All the really deep questions and statements contain some form of is or am.

  • Who am I?
  • What are we?
  • Is there a God?
  • I think, therefore I am.
  • To be or not to be

In Python, the keyword is isn’t quite that deep, but it’s definitely a reflection of its more profound cousin.

Python’s is can be used to test the identity of objects.  But, you may ask, isn’t that what the == symbol does in Python, as in 3 == 3? Well,  not quite. Just because my clone and I are equivalent doesn’t make us the same person. Similarly, an empty list is equivalent to another empty list, but they are not the exact same list. Either one of of them may change at any moment, becoming more than they are. Therefore:

>>> [] == []
True
>>> [] is []
False
>>> {} == {}
True
>>> {} is {}
False

Yes, there are also good technical reasons for this.  Lists and dictionaries are located separately in Python’s memory.

Get a load of the code below. Which statement is going to print? By now, you probably know, but you might want to run it and see for sure:

a = [1, 2, 3]
b = [1, 2, 3]
if a is b:
    print("a really is b")
else:
    print("a and b are equal but not the same")

The bottom line is that is compares the identity of two Python objects whereas == compares their values. Honestly, I’m not sure if that’s really deep or if I’ve just been dipping too deeply into my Zeppelin collection this evening.

Featured image: Hamlet’s Vision by Pedro Américo