I dig the word “tuple”. It sounds like a word you should know but can’t quite place. It makes me think about tipple, as in tippling wine at the gallery opening. That, in turn, reminds me of the Monty Python sketch called “Stock Exchange Report,” in which a reporter broadcasts, “Ting tang tong rankled dithely, little tipples pooped and poppy things went pong!”
Great, right? That, in turn, reminds of Lewis Carroll: “Twas brillig, and the slithy toves did gyre and gimble in the wabe.”
But I digress. Back to tuples, a word that sounds like nonsense but is actually a mathematics term meaning an ordered grouping. One of the reasons it sounds familiar even to non-mathematicians is because it makes its way into the language in other ways, such as quintuple, sextuple, and octuple. So, when you think about some poor woman bearing quintuplets, think of them as a pretty darn long grouping of darling babies.
In Python world, a tuple is also like a grouping, consisting of a number of values separated by commas and contained inside parentheses. Here’s an example of a tuple:
pokerFriends = ("Joe", "Shiho", "Jose")
Go ahead and type that into your IDLE shell and hit enter. Now, If you type the word “pokerFriends” into the Shell, it should spit out the tuple:
('Joe', 'Shiho', 'Jose')
So, now you have a tuple (which is a grouping, of course) that is called pokerFriends. The names, which are separated by commas, are the values. We could (and will) go deeper into these matters, but let’s quit for now. Just remember that you tipple wine and tuple values.
The world of coding takes a lot of its cues from the world of mathematics, so it’s no surprise that there’s a lot of stuff about “operators” in Python. Generally speaking, an operator is a symbol or function that tells the computer to perform certain logical or mathematical operations, such as addition, subtraction, multiplication, and division. You know what I mean: symbols such as + and – and * and /.
Even in the meager coding examples I’ve shown you so far, I’ve had to use an operator, the =, and explain how it is different from ==. But there are plenty of other operators to be aware of. Python can do all the stuff a basic calculator can do. You just have to know how to wield your operators. Here are some examples of the arithmetic operators at work.
So, you can see that if you enter 5 + 2, for example, the program tells you that equals 7. Five minus 2 is 3. Five multiplied by 2…well, you get the idea.
But there’s some weird stuff here, as well. For example, why in the heck does 5//2 give you 2? Well, it’s because it’s dividing 5 by 2 and then rounding to the nearest whole number (aka, floor division). Another weird one is 5 % 2. Why does it give you 1? Because it is giving you the remainder of 5 divided by 2. That may seem strange at first but you’ll find these operators can be quite useful for writing various programs.
If I really wanted to bore you you silly, I could systematically go through the whole list of operators, which come in a variety of flavors, including (in addition to arithmetic operators) comparison operators, assignment operators, logical operators, identity operators, and even the (sometimes mind boggling) bitwise operators.
Rather than spend pages doing that, I recommend that you go to any of the great online resources that give you the full treatment, such as the following:
Python.org (which explains things in a much less intuitive way but does tell you about related functions, which we’ll get to later)
Operators are as boring to read about as your average Congressional record, but they’re important to know. If you have a tough time remembering them, then I suggest using online resources such as Quizlet or Anki to create flashcards for yourself. In some cases, people will already have made flashcards of them (see the Quizlet link), so you may only need to find theirs through a search. My motto is to use what other people have already made as often as you can. That is, when in doubt, take the lazy way out.
Featured image: Author: Joseph A. Carr, Jersey Telecom telephone operator at switchboard, 1975, source: http://www.JoeTourist.net/, Wikimedia Commons
The word “variable” sounds intimidatingly technical but it’s really just something that, well, varies — or, at least, it can vary. Let’s say you’re starting an exercise routine. You’ve gotten flabby and out of shape and your weight is up in the 230 pounds range (damn this scale!). So, you assign a number to your weight as follows:
weight = 230
Type that into your Shell and hit return. Now, if you type the word weight into your shell and hit return, you should get the number 230.
Let’s say you go on an exercise program and lose a little weight, then a little more, then maybe gain some weight back (the story of my life), and then lose some more again. You can keep assigning different numbers to the variable called weight. Therefore, you’re using the same word but assigning a variety of numbers to it. Variable…vary. Very logical.
See the below for an example of how this works as you assign different numbers to the variable we call weight:
Now, let’s say you’re talking about the cost of a tablet computer. When you buy it, it’s worth $800. A couple of year later, it’s worth about $300. And a year after that, you can only get $100 for it on eBay. So, our variable called tablet could be assigned various values depending on its age.
And, indeed, “value” is what we call the numbers that we assign to variables. Therefore, the last value of weight was 205 in the first example above. The last value of tablet we discussed was $100. The value of variables (just like human values) can shift over time.
I’ve been using a bit of extra jargon in this particular post: that is, the word “assign.” When you assign the value $100 to the variable tablet, you write it like this:
tablet = $100
You’re using the equals sign on your keyboard to assign a value. That would all be fine and dandy if there weren’t any math in computer programming. But there is. Sometimes you want your equals sign to actually mean “equals” rather than “assign.” When you add a couple of numbers in the real world, for example, you typically use an equals sign, as in 2 + 2 = 4.
Just for giggles, go ahead and put this into your Shell:
>>>2 + 2 = 4
Now, hit Enter. If you’re doing it right (or, in this case, wrong), you’ll get another error message:
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
Thanks for the hint, Python! Indeed I did! So, let’s try putting this into the Shell:
2 + 2 == 4
Now hit your Enter key again. This time, Python should spit out the word True. You see, Python refused to use the single equals sign for math. It always wants the double equals sign if you’re doing math.
This can get annoying, but you’ve just got to live with it a while and allow it to become second nature. Think of it as one of those vexing habits of someone you love. You live with it because you love them. That habit still annoys the crap out of you until the day it becomes expected and even endearing. Welcome to Python world (or, for that matter, the world of programming).
At times, you can lose track of your variables. You think you’ve assigned some value to a variable and then you plug it into your code. Python, however, disagrees. It thinks you haven’t assigned a value to that variable yet. So, you get into a spat. Python always wins those spats, of course, because it is more logical and stubborn than you are.
You can get feel for Python literalness by looking at this:
You can see I’ve assigned the number six to Joe. If I type in Joe, Python spits out the number six. But then I type in Jo, and Python throws up an error message called a NameError. This time, it helpfully asks “did you mean: ‘Joe'”?
Which is groovy because when I first learned Python, I did not get those kind of helpful hints. Python has gotten a little smarter and more civil in recent years as it has mellowed.
The bottom line, however, is that should try to avoid losing track of your variables. If you’re programming, you’re going to need them.
In Python, if you want to say something that the computer doesn’t need to know but your fellow programmers do – such as “If you change any characters in this line of code, the whole program goes kablooey” – then you need to stick in a pound sign (#) or put your comments into triple quotes. Try this in your Shell:
>>>print ("Hello, world!") #This line says hello
You should see Hello, world! without all the verbiage to the right of the pound sign. That message to the right of the sign is only for your self, or your fellow programmers. Now, try this (but in your Text Editor rather than the Python Shell):
print ("Hello, world!")
This is a verbose comment to you, the programmer. I wanted
to mention that this line provides an existential salutation,
a signal of optimism to an oft-hostile universe via a medium
that is also a message
Here’s how it would look in your Text Editor:
Go ahead and run it and you’ll see that the comment never shows up but “Hello, world!” does (except without the quotation marks).
Remember: that verbose comment needs to go below the first line. The triple quotations marks (outside the holy confines of the parentheses, that is) allows you to leave a multi-line comment to whomever will be seeing your code.
Also remember that Python is sensitive to indents, so you won’t want to mess around by indenting your comments.
If you’re thinking that you will just remember how your code works, then you’re badly, sorely, laughably mistaken. It’s amazing how quickly you forget how your code is supposed to work. Leave reminders even if it’s a pain in your rump. You won’t regret it.
Strings are the things stuck between quotation marks. It’s like dialogue in a book, except a bit knottier. So, “Hello, it’s me” is a string. Using IDLE (see previous post), try printing that out in Python 3 like this:
>>>print (“Hello, it’s me”)
It should work like a charm. Now, try this:
>>>print (Hello, its me)
This time, I’ve set you up for failure. You should have gotten the annoying message: SyntaxError: invalid syntax. That’s because Python is looking for a string here and won’t accept it without some quotation marks. It’s like having a super strict elementary school teacher who will not cut you any slack (yes, I’m looking at you, Mrs. Decker!). But Python will also accept some other versions of quotations marks to make a string. Try these two versions in your Shell:
>>>print ('Hello, it is I')
>>>print ('''Hello, it is I''')
Those should work. Bottom line: you can use single, double, or even triple quotation marks to make a string. (Mrs. Decker would have hated that.) Now, try this:
>>>print ('Hello, it's me')
That should give you another error, this time a “SyntaxError.” That’s because Python can’t tell the difference between a quotation mark and an apostrophe. In its little literal mind, it sees three quotation marks and so can’t tell where the string is starting and ending. So, it’s not quite a string. It’s more of a knot. And knots will tangle you up. Kind of like a real python will. Beware.
PS – There are about a bajillion ways of messing around with strings. For a long list of ways of playing with string, I recommend you have a look at the official list of string methods. Just don’t let the list intimidate you. For most folks, only a handful of these are used on a day-to-day basis.
The following post is part of a series. Although written in an idiosyncratic manner mostly for my own edification and amusement, collectively they amount to a kind of quick and quirky basic primer on Python 3. It’s geared toward true coding beginners (of which I remain one) who want a short tutorial before delving into the more complex worlds of online interactive platforms, 800-page books, Ivy League MOOCs, and the plethora of other learning resources both on and off the Web. I hope a few others may find the posts useful or, at least, moderately amusing.
Basking in Basics: First Steps (How to download Python and IDLE to get started)
Basic One: Where Do You Get Your Python?
Some version of Python might already be on your computer. Have a look. If it’s not there and you’re using Windows, use your Web browser to go to https://www.python.org/downloads/ in order to download Python. If you don’t have Windows, there are links there to versions for other operating systems. It should be fairly easy to download from one of these pages.
Once it’s downloaded, install it, of course.
By the way, you can get “documentation” — aka, stuff you sometimes need to know about Python — at http://www.python.org/doc/. I have found that some of the explanations of how Python 3 works are comprehensible but some read like the glossolalia to me. Luckily, there are other places to look for help if you’re having issues. I covered some of them in my previous post on Python.
Basic Two: Why Should You Get IDLE?
I think the easiest way to get started with Python coding is by launching “IDLE”. Once you’ve downloaded Python, look around for the IDLE file. On my computer, it’s in the following subdirectory:
But the first time I downloaded Python, I found it just by searching for “idle” using Windows Explorer.
IDLE stands for the Python “Integrated DeveLopment Environment” and also is a reference to Eric Idle, one of the founding members of the Monty Python comedy group (Python is name for them). When you first click on the IDLE file, it’ll launch the Python Shell. Here’s what it will look like if you maximize it.
IDLE is just one of many possible integrated development environments (IDEs) you can use, but I found it to be a good place to start. As you work with various Python tutorials, their authors may point you in the direction of other IDEs that have different (and often more sophisticated) features. For a list of some other IDEs, have a look at the Python wiki. Another source on IDEs can be found here.
You can type your first commands directly into the this Shell if you want. Write the following in IDLE and then hit return. (Just remember that the >>> symbols are not something you need to type. They are already in IDLE.)
>>>print (‘Hello, world!’)
You should now see ‘Hello, world!’ pop up. (It’s tradition to use that phrase when starting a new language, so now you’re part of the grandish tradition.)
Anyway, that’s coding, sort of, so now you can say you’ve done it. But, obviously, that’s like saying that you know how to speak Spanish if you’ve only mastered “Hola.” Over time, you’ll pick up the language, but you’ve got to get in there and start plugging away, not caring if the locals are snickering at your weird syntax and lousy grammar at first.
(Don’t worry. At least at first the “locals” are just the programming language and IDLE itself, so there won’t be any actual human scorn involved. Feel free to make as many mistakes as you like. If you have patience and a sense of humor about yourself and Python, it can be a lot of fun).
How Do You Get Out of Your Shell?
From the Python Shell, you can go to the pulldown menu “File” and click on “New File”. It should open up a window that looks like this if you maximize it:
That’s your Text Editor. You should save this window as a file, calling it whatever you want and storing wherever you won’t lose it. Then type in the following once again:
print ('Hello, world!')
Then go to the “Run” drop-down menu, and choose “Run Module.” With any luck, you’ll then see Hello, world printed in the Shell. It’ll go something like this:
First, you’ll type in your code:
print ('Hello, world!')
Then you’ll run the module:
And then the words will be printed in your Python Shell:
In case this wasn’t clear, keep in mind that the Text Editor and the Shell are two different things. You can put commands into your Shell but mostly you’ll be coding in your Text Editor and then running the code. The outcome of that code will show up in the Shell.
I’m hoping that’ll work for you. If not, keep playing around with it, and find other sources of information. Persistence counts in this biz.
PS – If you need it, another step-by-step can be found at RealPython.
Featured image: Group shot of the Monty Python crew in 1969, Back row: Graham Chapman, Eric Idle, Terry Gilliam; Front row: Terry Jones, John Cleese, Michael Palin https://en.wikipedia.org/wiki/Eric_Idle#/media/File:Flyingcircus_2.jpg
Note: I originally wrote this post over half a decade ago but have just gone through and rechecked/updated the links. The graphic shows some sources (thinking about you, Google+) that no longer exist, but I figured the concept itself was still valid enough to leave it. This post is not about networks per se but it points a small portion of the deeply networked coding sites on which we've all come to rely since the advent of the Internet -- Mark in December 2021
For the beginner coder, there are lots of different paths to programming proficiency. Some people will start with college courses, boot camps, or books. But it’s easy to lose your way, running out of time or patience as you struggle through the dense undergrowth of learning possibilities. This might provide a bit of guidance for those willing to generalize the lessons in finding their own paths.
To one degree or another, of course, all learners are going to blaze the path that best meets their unique needs, and a linear representation like this one can never do justice to fact that many people will engage in a lot of these activities simultaneously (e.g., have a book going while taking a MOOC and playing a Python-learning game). So feel free to devise other paths. We all learn from one another in this area. Below I have elaborated on resources available to travelers along the pathway suggested above.
At one time, I created a primer I was calling Quick and Quirky Python 3, but I’ve since removed it since I needed to refine it. But there is an assortment of other sources. One nice one is How to Use Python: Your First Steps. Another (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. I also like A Beginner’s Python Tutorial, and After Hours Programming is useful. In addition, there are various Python tutorials (which we’ll discuss below) that could be viewed as primers.
Resources for Kids (or the Young at Heart)
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 of all ages (but especially children) can go to get a feel for how to code. Among them are MIT Scratch, Code.org, and Google Blockly. There’s a blurred boundary between these types of sites and sites that teach via gamification, which I will discuss below.
Virtually anything on the Internet can serve as an online reference, so this is a catch-all and poorly defined bucket. But what I’m really referring to are the references you go to when you have a specific question about Python. Very often, you start just by plugging your specific question/subject matter into Google (or your search engine of choice) and seeing what comes up. Quite often, you’ll wind up in StackOverflow, where both beginners and experts have gone (and still 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 before. When Web searching, you may also wind up in an online tutorial of some sort, whether it’s in the official Python documentation or something like TutorialsPoint.
With the advent of iTunesU and MOOCs (for massive open online courses), there’s now a plethora of university-level online courses that teach Python. In fact, since Python has become the introductory language of choice at universities, the average Python beginner has access to an embarrassment of riches in this area. A beginner could, of course, start with one of these courses as his or her first stop on the way to learning to code. My experience, however, is that it helps to go into those courses with at least a little knowledge about Python. That way, you can focus on the broader concepts (such code efficiency and the various types of algorithm) rather than scrambling just to keep track of Python vocabulary and syntax. I have had most experience with Hands-on Python (particular good for beginners), Udacity’s Programming Foundations with Python, and MITx: 6.00x Introduction to Computer Science and Programming. I like them all, but there are plenty of other choices available these days, including a number from Coursera.
Game-based learning is not just for kids, though some game-based Python learning experiences are geared that way: e.g., CodeCombat, Codingame, and Code.org. Other games or gamified challenges are more geared toward adults. Among them are Checkio (with which I’ve had most experience and can recommend), PythonChallenge and the pretty-darn-serious Exercism.io. The great thing about Checkio and Exercism.io is that A) you must do a lot of practical coding to make headway, and B) there are opportunities to interact with other coders and (at least for Checkio) get a good look at how good programmers solved the same problems as you just did.
Online Community Q&A
You can join Python communities, such as those on Google+, and ask your questions there. You’ll often get quite a few knowledgeable responses in just a few hours’ time. The same can apply to StackOverflow, which is not only a great reference but a great online community. There are also communities attached to online tutorials, such as those at Codecademy. And there are services such as Codementor where, for a fee, you can connect with “experienced mentors for instant help via screen sharing, video, and text chat.” There are also Internet Relay Chats devoted to Python.
Meetings and Hang Outs
Then there are virtual communities where people “hang out” while studying, discussing or reading a book together. One option for this is Codebuddies. There are real, face-to-face communities as well. Many cities now have makerspaces/hackerspaces where people congregate to make stuff, teach one another to code, and otherwise fly their geek flags. There are also meetups and user groups in which people come together just to discuss programming in Python. And there are a number of Python-focused conferences in a given year.
Intermediate Books and Blogs
Once you’re past the rank beginner phase, there are many books and blogs geared to intermediate levels of Python knowledge. Among the not-strictly-for-beginners books I have on my bookshelf are the (very heavy) Learning Python by Mark Lutz and the (less heavy) Python Cookbook by David Beazley and Brian Jones. The former is a soup-to-nuts manual and the latter is great for teaching you how to write in a more Pythonic, elegant way (something I’ve not yet mastered). Online is the book Problem Solving with Algorithms and Data Structures Using Python, which provides the kinds insights into algorithm writing that are seldom in books for beginners. And the official Python website has advanced books “for when you don’t want gentle.” There are also higher level blogs such as Pythonic Perambulations once you get past the beginner phase.
Write Real Code
Writing useful code is the best learning experience of all. There are lots of ways to do this. If your employer is already paying you do write in Python, then problem solved. But even if you’re not a paid programmer/developer, there are plenty of other opportunities to write “real code.” For example, you can write your own app or game, or code up a raspberry pi project, or get involved with a Github project. The truth is, there are nearly an unlimited number of ways and reasons to write your own code, from competing in a coding challenge to helping a non-profit produce the code it needs to run its business. The world is your coding oyster.
Note: Featured image is from Andrew Cattoir (Lake Mead National Recreation Area). See https://commons.wikimedia.org/wiki/File:Scenery_at_Bluffs_Trail_-Las_Vegas_Bay_Campground(802dd631-e46a-46e5-92dc-b1a6915a61ce).jpg