Intro to Python 101 For Beginners

If you code Python already, go somewhere else. I’m only talking to complete and total newbies to the language right now. I want to show them the stuff that I wished someone had put in one nice, neat blog post for easy consumption when I got started with the language. If that’s what you’re looking for, look no further. Here’s what you need to know.

Lay of the Land

Python seems like a bit of a strange place at first. Most new programming languages do. This is because most modern interpreted languages like Ruby and Python like to “eat their own dog food”, so Ruby’s web site uses a Ruby-based CMS, and the documentation is generated with Ruby-based tools (I believe it’s all RDoc). Python’s site is written in Python, but isn’t a specific framework. The documentation is presented using Sphinx, a documentation engine written in Python.

Python, at time of writing, has a 2.x distribution and a 3.x distribution available for download. There’s a chance I’ll be flamed for saying so, but download 2.x. Most of the blog posts you’re likely to turn to for help over the course of your first year with Python are still going to be 2.x-specific, and if your code involves external modules, a good number of them haven’t ported to 3.x yet. Hang tight – 3.x is awesome, but 2.x pretty much rocks too.

Documentation for Python is pretty good, and the first bit of documentation you need (after this post) is the Python Tutorial. It’ll get you rolling with the basic syntax of the language, data types, equality operators, conditionals, the works.

With the basics of the language under your belt, you need two other bits of documentation:

You’ll want to know about the modules that are included with the Python distribution before you go out seeking external modules. You can see a complete list of built-in modules at the Module Index. It’ll give you a good idea of what you can do with the language right out of the gate without any additional downloads.

You’ll also want to bookmark the Standard Library documentation. This is the meaty stuff, and is where I spend most of my doc-reading hours. If you know the module you want docs on, just type it on the end of the base url and you’re there. So if you want to know about the ‘threading’ module, go to http://docs.python.org/library/threading

One tip about the documentation on python.org: don’t use the search box they provide. The search functionality is slow, and after all that time, it’s almost certainly *not* going to give you what you were looking for. Go to Google and search there. If you know that what you’re looking for is on docs.python.org, then append “site:docs.python.org” to your Google search term. Works like a charm.

How to do ‘x’ with Python

The first project I wanted to use Python for involved LDAP, and there’s no LDAP-related module built into Python. Finding the right module to use was my first challenge. There used to be a resource known as the ‘Cheese Shop”, but it’s now been rolled into the Python Package Index, a.k.a “PyPI”. These packages are not endorsed by python.org or anything, PyPI is just an interface to help you figure out what the available options are. The search box on this page *is* useful, but the issue then becomes which module to choose — even for a relatively obscure requirement like “LDAP” there are lots of modules.

The obvious choice for LDAP is python-ldap, and it seems to be the canonical choice for those needing this support. Also, a Google search for “python and ldap” returns several articles about, and the home page for, the python-ldap module. So, in less than five minutes you can usually figure it out, but don’t download the module yet!

You can (it’s completely optional but worth it) install “setuptools”, which gives you a tool called “easy_install” that’ll run out to PyPI and get whatever module you want, and install it on your system. I install most modules this way and don’t remember ever having any major issues with it. That said, some of the cool kids lately have taken a liking to an easy_install replacement called pip. I admit it looks very nice, but I guess until easy_install bites me I’m not going to be super motivated to switch. Pip takes some additional steps to make it more reliable and cause fewer issues in the face of spotty wireless connectivity and things like that. It also tries to make output easier to understand, it supports package uninstalls, and several other niceties. It seems to be the future.

Community Support

Python coders are a fairly outspoken, though friendly lot, in my experience. If you ask a reasonable question, you’ll get a reasonable answer, often in the form of a link to where you need to be documentation-wise, but not with the nasty RTFM aftertaste other communities leave behind. For added comfort, attach a “link to docs welcome!” to your request for help. Yummy!

There are lots of Python mailing lists, the most helpful one for beginners (and beyond) is probably the tutor list. I learn something new every day lurking on that list. The answers you get there tend to be authoritative, from folks who are working on the Python language itself, so it’s not just another ‘net forum where the blind often times are leading the blind.

Two great sources for ideas on how to put your code together or help venturing into new territory with Python are Stack Overflow and the Python Cookbook. Python Cookbook is a great source for ideas, and Stack Overflow is a really good Q&A interface where you can get good advice to hard problems (or really easy ones).

There are IRC channels for Python, and I’m a heavy user of IRC in general, but I don’t venture into the Python IRC channels much. With all of the other resources available, I don’t typically miss it.

Ok, wtf does this traceback mean?

Tracebacks can look daunting if you’re new to the language (unless you come from a Java background). They’re not all that tough. Here’s some output from a Python interpreter interactive session (which you’ll learn about if you read the tutorial linked above):

>>> d
{'China': 'Shanghai', 'USA': 'NY'}
>>> d['USA']
'NY'
>>> d['foo']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>>

This is a short traceback, but you parse them in the same basic manner as long ones 90% of the time. The first thing I look at is the last line of the traceback, which tells me the kind of error that was encountered. In this case it was a KeyError. I’ve seen error at least once for every hair left on my head, but if you don’t know what it means, check out the handy dandy page that describes all of Python’s built-in exceptions! Exceptions are just Python code themselves, and you can create your own for your own use in your own code, by extending one of the existing exceptions, or the base Exception class.

After about a month of coding in Python regularly, your eyes will start to jump to the right places in a Python traceback, and you’ll find that the exception names actually are pretty intuitive, and since you can employ them yourself or extend them, you’ll probably get to know them quickly without using a reference.

Really? Whitespace?

You’ve probably heard about Python’s treatment of whitespace before. Its reputation for placing significance on whitespace in source code precedes the language, and I guess it turns some people off. I actually didn’t care, because I figured as long as I indented my code the way I normally did, the whitespace issue wouldn’t bother me much, and I was right.

If you code in Perl, C, or Java, they don’t require indentation, but you almost certainly indent anyway because the whitespace is significant to *you* even if it’s not significant in the language. If you write readable code, nicely indented, you’ll probably forget about Python’s whitespace requirements after your first hour coding in it.

The rules aren’t all that stringent either. This code works fine:

def foo(c):
                     return c**2

if __name__ == "__main__":
         print foo(2)

There’s no consistency in this code: my function indents like 16 spaces or something, and then my if statement at the bottom doesn’t. All Python wants you to do is be consistent: if line 1 of your function is indented 4 spaces, indent the rest of them 4 spaces. Now you’re probably thinking “Well who doesn’t do that?” Exactly. It’s not draconian, it’s practical. You could think of Python’s whitespace requirement as filtering out people you’d rather not code beside anyway :)

Books

I feel like I own most of the Python books in existence through 2008. I bought the printed library reference in (I think) 2000. The best ones?

The one that really got me going with Python was Dive Into Python, which is available free and readable online. I bought the printed book just to support the author’s work. Mark Pilgrim writes using a style that makes you feel like you’re sitting next to him at a conference in a really lame talk and he’s whispering all kinds of programming goodness at you and showing you programming porn on his laptop screen. He’s excited to be talking to you about Python in that book. Truly inspired.

Perhaps my favorite “huge tome”-style book that covers pretty much everything from beginning to advanced material is Core Python by Wesley Chun. He covers more topics more deeply than most other books. I half expected this to be very broad and not very deep coverage, but I still pick that book up quite often when I want to understand some feature of the language better. His explanations are, for some reason, more clear and concise than most. Maybe they just fit my brain better.

After that I went straight into the more specialized Python books, but those are mostly dated now (Python Network Programming, for one, could use an update. I’d buy it again, probably), though I did purchase Programming Python, and Python Cookbook as a sort of quick reference for doing things I’d never done before. I don’t use them much, to be honest.

The only other book I really got excited about was Tarek Ziade’s Expert Python Programming. It’s not a beginner’s book, but it has a lot of really great material in it for those building larger applications with Python. Highly recommended.

Must Read

If you’ve worked in another language, it probably goes without saying, but you’ll learn much more quickly if you can read some source code, and/or work on a project with more senior coders than yourself. Reading code and tweaking it is probably the fastest way to learn about any language.

Move Forward

I hope this puts you in the right direction with Python. Bookmark all of those links, follow the tutorial, and before you know it you’ll be master of all you survey.

Enjoy!

  • Pingback: Tweets that mention Intro to Python 101 For Beginners | Musings of an Anonymous Geek -- Topsy.com

  • http://drazick.blogli.co.il Drazick

    Let’s say I know Matlab.
    I want to move to Python.
    Is there a book (Recommended by you) for this?
    Moreover, I do mainly because I heard I could get much better performances with Python.

    Thanks.

  • http://dougalmatthews.com/ Dougal Matthews

    “There’s a chance I’ll be flamed for saying so, but download 2.x.”

    I would certainly hope not. 2.X is the only realistic version at the moment really. The python website gives the same advice; http://python.org/download/

  • Benjamin

    Drazick, if you know Matlab, you want to check out http://www.sagemath.org if you haven’t already. Both the notebook and interactive shell are python. Sage includes most or all of the python packages that provide that performance you’ve heard of.

    Also, minor typoe in the article: “I’ve seen error at least once…”

  • Mike.G

    I wish you would elaborate on how you define – beginner. I’m a beginner to Python (specifically) and programming in general. I have tried multiple times to get through the so-called “Python Tutorial” and it has accomplished one thing only, to thoroughly discourage me – too long, too comprehensive – sorry, not for a beginner. Is this the only way to get going in Python – there has to be a better way for real beginners?

  • m0j0

    @Mike.G — anyone who has used any technology for some time eventually falls out of touch with what it’s like to be completely new to it. And since newcomers are, by definition, new, they don’t always even know what questions to ask. This forms a bit of a chasm between those that could help and those that need it, but I do my best by putting as much information out there as I can. So there’s my offering. If it doesn’t suit you, then you need to do *your* part and let me know where things fall short.

    This blog post was based on my own experiences being a newbie. When I was a newbie, I inserted myself into email threads and irc conversations, read everything I could about Python, and most importantly I hacked continuously and broke things mercilessly. From those experiences I was able to form questions that actually furthered my knowledge of Python, and I fed that new knowledge back into my hacking. That process basically still continues today.

    So what are your questions? What have you tried? There are lots of resources out there which contain answers, but you still are ultimately responsible for the question!

  • Mike.G

    @m0j0 – I hope you don’t think I was criticizing you, I simply said that the tutorial (IMO) is a far cry from a beginner read – that’s all. What have I tried, well, I have read anything that Google pulls up – you know the links, anyone who does a search for Python will see them. My main complaint is the offerings are either too simple or too complicated, ‘hello world’ with a widget or developing emol!.

    My ‘wish’ – the people who are truly interested in recruiting newcomers to the world of programming would help in clearing away some of the clutter, not add to it – there is too much info to siphon through – have you looked at the package index lately? I’m not sure anyone with zero experience would know what package they may want to use in a new (first) app, and I don’t believe I have read anything that helps with assembling the right tools or making this kind of decision, of course if you have experience then “they” send you to the ‘package’ index, btw, it may be larger than the Library of Congress.

    I read a bit about GUIs, both PyGTK and Boa Constructor were mentioned, but it looks as if they have been abandoned, as far as I can tell there hasn’t been news for either in a few years – I see this a often, abandoned efforts.

    I have seen in the MS VS world efforts to include newbies into a project from scratch, so they can be in on the creation of a new app, from ‘idea’ to ‘end user’ – I wish an effort like this was available to a person with zero experience – using Python. I do like the wxPython crowd, the IRC channel is great, also, the blogs (including yours) are helpful. I recently registered for the Python Tutor mail list.

    Bottom line, there are millions of bits and pieces that one can read and glean the greatness and usability of Python, but putting it together, the newcomer is left awash in a thousand options and no clue where to start – well, ‘hello world’ – of course.

  • http://www.anildewani.com dewani

    This guided me to accomplish my work with fun :D

  • badmash

    I just signed up to your blogs rss feed. Will you post more on this subject?

  • Jrushel

    Well, I have read a fair bit about python and like the sound of it. I am virgin to programming and haven’t looked into learning a language before. I have done some work in “scratch” before, so I know about ifs,elses, ifelses etc. but I have no idea how to code them. I was wondering if you know of a resource for COMPLETE beginners that could give me the basic information needed for “beginner” tutorials.

  • Komodo

    I wanted to connect my Labjack DAQ to Linux. In Windows, I can make this work beautifully in VB for Excel (now of course VB has been buggered beyond recognition, but hey, I’ve still got Office 97). In Linux, Python is the manufacturer’s choice for communicating with his product. What I would like to get Python to do is repeatedly to read an input analogue voltage, and catenate it to a log file, along with the value of a counter. Do I have to learn the whole (expletive) language to get it to do this?
    I’m not a programmer. I’m a technician. I doubt if I will use Python for any other purpose. Everything I have found on it suggests that it has a vast and convoluted grammar comparable to that of Turkish, but less logical. I only need it because it has been imposed on me by a manufacturer. And I am afraid your blog didn’t help. Sorry.

  • bkjones

    @Komodo – you’re clearly frustrated at a manufacturer for imposing its will on you, and that’s understandable, but I don’t see that as a reason to direct your frustration at an innocent blog post that attempts only to help others. I’m sorry that I don’t have a post that would tell you the precise steps you need to follow to accomplish your specific task, but that isn’t the goal here. If you’re never going to use Python, and you’re a technician with no plans to write code, then the best I can say is to either buckle down and learn what you need to get your work done, or get someone else to do it. Good luck.

  • paidhi

    If you like Doug Hellmann’s “Python Module of the Week” check out his book “The Python Standard Library by Example”.