The Rising Seas of AI-Generated Media

We are about to be awash in AI-generated media, and our society may have a tough time surviving it.

Generated by Stable Diffusion. The prompt was “Dali tsunami”

Our feet are already wet, of course. The bots inhabit Twitter like so many virtual lice. And chatbots are helpfully annoying visitors on corporate websites the world over. Meanwhile, algorithms have been honing their scribbler skills on the virtual Grub Street of the Internet for a while now.

But soon, and by soon I mean within months, we will be hip deep in AI-generated content and wondering how high the tide is going to get.

My guess is high, baby. Very high indeed.

What Are We Really Talking Here?

Techopedia defines generative AI as a “broad label that’s used to describe any type of artificial intelligence that uses unsupervised learning algorithms to create new digital images, video, audio, text or code.” In short, it’s all about AI-generated media.

Generated by Stable Diffusion. Prompt was “network”

I think that label will ultimately prove too restrictive, but let’s start there. So far, most of the hype is indeed around media, especially image creation and automated writing, with music and video not being far behind.

But we’ll get to that.

For now it’s enough to say that generative AI works by learning from, and being “inspired by,” the dynamic global reticulum that is the Internet.

But generative AI also applies to things like computer code. And, by and by, it’ll start generating atoms in addition to bits and bytes. For example, why couldn’t generative AI be applied to 3D printing? Why not car and clothing design? Why not, even, the creation of new biological systems?

The Money Generator

First, let’s follow the money. So how much dough is going into generative AI these days?

Answer: how much you got, angels and VCs?

Generated by Stable Diffusion. Prompt “printing press printing money”

For example, a start-up called Stability AI, which created the increasingly popular Stable Diffusion image-generating algorithm, was recently injected with a whopping $101 million round of investment capital. The company is now valued at a billion bucks.

Meanwhile other image generators such as DALL-E 2 and Midjourney have already acquired millions of users.

But investors are not just hot for image generators. Jasper, a generative writing company that’s just a year old (and one that plagues me with ads on Facebook) recently raised $125 million in venture capital and has a $1.5 billion valuation.

Investing in these technologies is so hot that a Gen AI Market Map from Sequoia recently went viral. The wealth wave rises and everyone wants to catch it.

Running the Gamut

Although image and prose (usually with an eye toward marketing) are the hot tickets in generative AI for now, they are just the proverbial tip of the iceberg. Indeed, it appears that Stability AI, for one, has much grander plans beyond images.

Generated by Stable Diffusion. Prompt was “color gamut”

The New York Times reports that the company’s soon-to-be massive investments in AI hardware will “allow the company to expand beyond A.I.-generated images into video, audio and other formats, as well as make it easy for users around the world to operate their own, localized versions of its algorithms.”

Think about that a second. Video. So people will be able to ask generative AI to quickly create a video of anything they can imagine.

Fake Film Flim-Flams

Who knows where this leads? I suppose soon we’ll be seeing “secret” tapes of the Kennedy assassination, purported “spy video” of the Trump/Putin bromance, and conspiracy-supporting flicks “starring” a computer-generated Joe Biden.

Generated by Stable Diffusion. Prompt was “human shakes hands with extraterrestrial”

We can only imagine the kind of crap that will turn up on YouTube and social media. Seems likely that one of the things that generative AI will generate is a whole new slew of conspiracists who come to the party armed with the latest videos of Biden handing over Hunter’s laptop to the pedophiliac aliens who wiped Hilary’s emails to ensure that Obama’s birth place couldn’t be traced back to the socialist Venusians who are behind the great global warming scam.

Even leaving political insanity aside, however, what happens to the film and television industries? How long until supercomputers are cranking out new Netflix series at the rate of one per minute?

Maybe movies get personalized. For example, you tell some generative AI to create a brand new Die Hard movie in which a virtual you plays the Bruce Willis role and, presto, out pops your afternoon’s entertainment. Yippee ki yay, motherfucker!

So, AI-generated media on steroids. On an exponential growth curve!

Play that Fakey Music

Then there are the sound tracks to go with those AI-gen movies. The Recording Industry Association of America (RIAA) is already gearing up for these battles. Here’s a snippet of what it submitted to the Office of the U.S. Trade Representative.

Generated by Stable Diffusion. Prompt was “music”

There are online services that, purportedly using artificial intelligence (AI), extract, or rather, copy, the vocals, instrumentals, or some portion of the instrumentals (a music stem) from a sound recording, and/or generate, master or remix a recording to be very similar to or almost as good as reference tracks by selected, well known sound recording artists.

To the extent these services, or their partners, are training their AI models using our members’ music, that use is unauthorized and infringes our members’ rights by making unauthorized copies of our members’ works. In any event, the files these services disseminate are either unauthorized copies or unauthorized derivative works of our members’ music.

That’s an interesting argument that will probably be tried by all creative industries. That is, just training your AI based on Internet copies of musical works violates copyright even if you have no intention of directly using that work in a commercial project. I imagine the same argument could be applied to any copyrighted work. Who know what this will mean for “synthetic media,” as some are calling.

Of course, there are plenty of uncopyrighted works AI can be trained on, but keeping copyrighted stuff from being used for machine learning programs could put a sizeable dent in the quality of generative AI products.

So, it won’t only be media that’s generated. Imagine the blizzard of lawsuits until it’s all worked out.

Stay tuned.

Revenge of the Code

AI can code these days. Often impressively so. I suppose it’d be ironic if a lot of software developers were put out of work by intelligent software, but that’s the direction we seem headed.

Consider the performance of DeepMind’s AlphaCode, an AI designed to solve challenging coding problems. The team that designed it had it compete with human coders to solve 10 challenges on Codeforces, a platform hosting coding contests.

Generated by Stable Diffusion. The prompt was “Vinge singularity”

Prof. John Naughton writing in The Guardian describes the contest and summarizes, “The impressive thing about the design of the Codeforces competitions is that it’s not possible to solve problems through shortcuts, such as duplicating solutions seen before or trying out every potentially related algorithm. To do well, you have to be creative.”

On its first try, AlpaCode did pretty well. The folks at DeepMind write, “Overall, AlphaCode placed at approximately the level of the median competitor. Although far from winning competitions, this result represents a substantial leap in AI problem-solving capabilities and we hope that our results will inspire the competitive programming community.”

To me, a very amateurish duffer in Python, this is both impressive and alarming. An AI that can reason out natural language instructions and then code creatively to solve problems? It’s kind of like a Turing test for programming, one that AlphaCode might well be on target to dominate in future iterations.

Naughton tries to reassure his readers, writing that “engineering is about building systems, not just about solving discrete puzzles,” but color me stunned.

With this, we seem to be one step closer to Vernor Vinge’s notion of the technological singularity, in case you needed another thing to keep you up at night.

Up and Atoms

Movies? Music? Code?

What’s next for generative AI once it finds its virtual footing?

Generated by Stable Diffusion. Prompt was “atoms”

Well, atoms are the natural next step.

Ask yourself: if generative AI can easily produce virtual images, why not sculptures via 3D printers? Indeed, why not innovative practical designs?

This is not a new idea. There is already something called generative design. describes, “Instead of starting to work on a design from scratch, with a generative design process, you tell the program what you need to accomplish, you set your design goals and mention all the parameters you can. No geometry is needed to start a project. The software will then deliver you hundreds or thousands of design options, the AI can also make an in-depth analysis of the design and establish which one is the most efficient one! This method is perfect to explore design possibilities to get an optimal part.”

Yup, perfect.

How About Bio?

Generated by Stable Diffusion. Prompt was “bioprinter”

Not long ago, I wrote a tongue-in-cheekish post about the singularity. An acquaintance of mine expressed alarm about the idea. When I asked what scared her most, she said, “If AI can alter DNA, I’d say the planet is doomed.”

That particular scenario had never occurred to me, but it’s easy enough to see her point. DNA is biological code. Why not create a generative AI that can design new life forms almost as easily as new images?

Generated by Stable Diffusion. Prompt was “live cells”

In fact, why stop at design? Why not 3D print the new critters? Again, this is a concept that already exists. As the article “3D Bioprinting with Live Cells” describes it, “Live cell printing, or 3D bioprinting, is an emerging technology that poses a revolutionary development for tissue engineering and regeneration. This bioprinting method involves the creation of a spatial arrangement of living cells and biologics into a functionalized tissue.”

The good news? Probably some fascinating new science, designer replacement organs on demand, and all the strange new machine-generated meat you can eat!

The bad news? Shudder. Let’s not go there today.

Mickey Mouse and the Age of Innovative AI

Although we’re calling this generative AI, the better term might be innovative AI. We are essentially contracting AI writers, artists and coders to do our bidding. Sure, they’re imitating, mixing and matching human-made media, but they are nonetheless “the talent” and will only get better at their jobs. We, on the other hand, are promoted to the positions of supercilious art directors, movie producers and, inevitably (yuck) critics.

Generated by Stable Diffusion. Prompt was “Tim Burton 3 people caught in whirlpool”

If the singularity ever actually happens, this emerging age of innovative AI will be seen as a critical milestone. It feels like a still rough draft of magic, and it may yet all turn out wonderfully.

But I find it hard not to foresee a Sorcerer’s Apprentice scenario. Remember in Fantasia, when Mickey Mouse harnesses the power of generative sorcery and winds up all wet and sucked down a whirlpool?

Unlike Mickey, we’ll have no sorcerer to save our sorry asses if we screw up the wizardry. This means that, on sum, we need to use these powerful technologies wisely. I hope we’re up to it. Forgive me if, given our recent experiences with everything from social media madness to games of nuclear chicken, I remain a bit skeptical on that front.

Feature image generated by Stable Diffusion. The prompt terms used were "Hokusai tsunami beach people," with Hokusai arguably being the greatest artist of tsunamis in human history. In other words, the AI imitated Hokusai's style and came up with this original piece.

Poetry, Programming and People Management

The human brain does ambiguity well. Most of us are strangely drawn to multiple meanings, surrealities and pattern recognition. We thrive on metaphors and similes, rejoice in symbols, dance to nonsense syllables and ad hoc syncopations. And paradoxes? We both hate and love them — paradoxically, of course.

No More Artful Ambiguities

This may be one of the reasons so many people become frustrated and even fearful when confronted by math and logic. Those disciplines feel so cold and hard-edged with their unitary meanings and wearisome concatenations of implacable reasoning.

It’s the same with computer coding. If you take an Introduction to Computer Science course, the professors often go out of their way to compare natural languages (a phrase which itself is an oxymoron) with computer languages.

Yao graph with number of ray k=8; from Wikimedia, by Rocchini

The gist is that while while both types of language share common and, indeed, essential properties such as syntax and semantics, they differ widely in that natural language can often be understood even when the speaker or writer fails to follow basic spelling or grammatical rules. In contrast, a computer program (much like a mathematical equation) will typically fail to work if even a single character is left out or misplaced. An absent bracket can be a fatal bug, a backwards greater-than symbol can cause an infinite loop, a poorly assigned variable can inadvertently turn  100 dollars into a dime.

A computer has no use for the artful ambiguities and multiple meanings of poetry. If you give the machine a couple of lines of verse such asanyone lived in a pretty how town (with up so floating many bells down)”,  it will — unless you carefully guide the words into the code as a string —  give you an error message.  (I know a lot of people who might respond the same way, of course.)  Yet, without the precisely imprecise wordplay of e e cummings, those lines of poetry would not be poetry at all.

How Does People Management Fit?

So, what does any of this have to do with people management?

Just this: people management is sometimes poetry, sometimes programming, and it helps to know which is which. Before the rise of civilizations and cities, when virtually all people were hunting and gathering in smallish bands and clans, people management (in the forms it would have existed then) was all poetry.

Sure, there were unwritten rules, harsh taboos, constant rumors and deadly serious superstitions. And a leader, to the degree there were leaders as we understand them today, could leverage those cultural components to influence his or her clansmen. But this was mostly a matter of nuance, persuasion, the formation of alliances, the wielding of knowledge and lore (when, that is, it wasn’t a matter of force and coercion). In the largest sense, it was art and song.

Today, good managers must still be attuned to the poetry of human attitudes and actions, able to sort through the ambiguities of rumor mills and hurt feelings and arrogant posturings. But now managers must also cope with or even rely on laws, regulations and rules.

Hard Coding Humanity

Is there a “zero tolerance” clause in the company policy somewhere? Then even a terrific employee who gets caught using illegal drugs may need to go.  Are there complex legal regulations barring a worker from having financial holdings in a certain client company? Well, then, the employee must divest or hit the door. There are countless other examples of rules that are as hard-and-fast as rule-of-law societies can make them. Although these human rules will never be quite as rigorous as the requirements of programming languages, they are a kind of human programming; there are true and false statements,  barriers that can’t be broken, classifications that should never be breached.

This is why we have legal departments. It is also why uncertain managers call in the hired gun of the HR professional to take care of dismissals and drug tests and background checks.

We simultaneously hate  this programming of human behavior and depend on it. We can, for example, rely on the kind of code that states:

while worker performance >= level 3: { {

provide paycheck and health insurance }

else if: {

performance <= level 2:

leverage performance review proceedings


Okay, the coding in companies is much more complex than that. Still, the point is that we rely on it because it’s clean, logical and, best of all, spares us from having to make hard and potentially dangerous decisions on our own. In such settings, we are no longer “poets of people management,” the kind of managers who might have led a clan though a vast and dangerous prehistoric wilderness in millennia gone by.

People in Both Programs and Poetry

This dependence on programming is a shame in many ways, one that harried managers should ponder from time to time.  I know we can’t utterly avoid modern programming — at least, not unless we retreat into the wildness, as metaphorically  isolated as Thoreau in his cabin by Walden Pond. Nor should we. The rule of law is essential to our modern societies, and formal policies are often forged to protect employees from arbitrary or biased decisions. Still, we might strive to be better poets, respecting employees as the people they are rather than viewing them as components of a well-programmed machine.

Walden Pond; from Wikimedia, by QuarterCircleS
Featured image: The Parnassus (1511) by Raphael: famous poets recite alongside the nine Muses atop Mount Parnassus.

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 others. 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. 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, 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. 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. 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 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 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.


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.



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:

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

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 technological landscape.

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

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

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

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

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


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 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 signifies the process of  negation, of course. In this case, negative statements are True, as counter-intuitive as that sounds.

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

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

 While Not ee cummings

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

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

as freedom is a breakfastfood

or truth can live with right and wrong

or molehills are from mountains made

—long enough and just so long

will being pay the rent of seem

and genius please the talentgang

and water most encourage flame

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

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


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 Python 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.


Among Python keywords, 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
        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:

raise IndexError


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


def send_nothing():
    x = "letter"


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.


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):
    counter = counter+2

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 Python keywords, I recommend Zetcode

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

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


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

None is also not equal to an empty list:

>>> None == []

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

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

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

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:


The History of Python


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 Python keyword “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

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("A list of the Thorin's company sorted by name: " 
+ str(sorted(dwarves, key=lambda name: name[0])))


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


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:


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


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)

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", line 34, in <module>
      print ('celeb outside the function is: ', celeb)
NameError: name 'celeb' is not defined

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

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

For more on global and nonlocal, see GeekforGeeks.

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

Let’s look at the Python keywords “from” and “import.” We’ll take them in reverse alphabetical order because our explanations should make more sense that way.


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))


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