Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, September 26, 2012

My 19 Days of Python: Interlude 1

OK, it happened. The engine stalled and I haven't been able to get it started again. One of the things I know about programmers is that they program all the time, whether they're at work or not. Some of them keep brutal, late-night hours banging away at the keyboard, trying to solve arcane puzzles and get their code to work.

But it's been over two weeks since my "stall" and I've been avoiding Python and this blog like cancer.

To be honest, I have also been distracted by other priorities, so it's not like I've been sitting idle, staring at a blank blogger composition page, and wishing the muse would whisper something into my little, shell-like ear.

In the meantime, I've noticed two competing philosophies that relate to my current project and dilemma: should non-programmers code or not code? Actually, opinions vary, but I guess it depends on why you're invested (or not) in non-programmers learning to program.

Don't worry. In my case, the chances of me inflicting any program I may write into a professional setting is non-existent. The only place I will (and have) publish the fruits (such as they are) of my labors is here among the millions of chimpanzees vainly attempting to recreate the complete works of Shakespeare (or maybe just a sonnet or two).

Today, I realized that I ran out of excuses reasons for not returning to this project. The only question now is if I should try to pick up where I left off, or go all the way back (not that the distance is exactly vast at this point) to Day 1 of Downey's book, and start fresh (No, I wont write "Day 1A" and "Day 2A" if I choose the latter option)?

The first step is for me to go over everything, including the comments that have been languishing, and see where I stand. Hopefully this will mean that Day 4 will be forthcoming.
"The single most important skill for a computer scientist is problem solving." -Allen B. Downey

Tuesday, September 11, 2012

My 19 Days of Python: Day 3 and I Hit a Wall

Day 3 of My 19 Days of Python introduced me to my first real challenge (in a definitely "non-trivial" way) in attempting to think like a computer scientist. I don't know if it was all the jargon or if I was having trouble connecting the concepts with actual practice. Probably both. But I could just "feel" my brain slowing down as I was reading through Chapter 3: Functions."

What I do to prepare for a "day of Python" is to read through the chapter while sitting well away from a computer. I just read the pages and plan out what I will be doing and noticing areas where I know I will struggle. That way, when I'm back at the computer with Downey's book Think Python, I know the direction in which I'll need to travel and will be aware of the potholes and speed bumps in the road.

"Math functions. Why did it have to be math functions?" Chapter 3 introduces modules, which are files that contain the definitions of the functions and variables related to the module. But while Downey includes a bit of trigonometry (well beyond my skills as a mere writer), this chapter doesn't require the reader to actually do any trig (thankfully). For the sake of "mathphobic" people like me though, it would have been nicer if Downey had inserted another module to use as an example. On the other hand, after importing math, I can use "math.pi" in a statement without having to specifically define pi.

Chapter 3 is also the first time when the reader will have to compose or put together when they've learned in previous chapters, particularly Chapter 2. After reading the chapter, I actually go through the pages sitting at my computer and practicing what I'm reading as I blog (I haven't encountered Exercise 3.1 yet) and I think this helps map the concepts to the practice somewhat. Maybe more examples or practice exercises per concept would be useful, at least to me, when trying to "glue" an idea to an action (thinking of a function vs. writing a function). As of page 27, I've got a program, if you can all it that, containing two function definitions: "print_lyrics()" and "repeat_lyrics()" (more Monty Python fun and games). Now I need to write a script containing those definitions and use the script for the first two exercises.

For the first time, Downey mentions text editors (in the Debugging section) that are "aware" of Python and its "indentation needs," but he doesn't suggest any. Fortunately, gedit, which I regularly use in Ubuntu, lets you select which program or format you need including Python, so I'm OK there...sort of, as it still doesn't do indentation automatically. But the reader who knows absolutely nothing about this will be at a loss.

I forgot to end one of my strings with a double-quotation mark and also forgot that in the shell, to execute my script, I had to type "python repeat_lyrics.py" instead of just "repeat_lyrics.py." Once I corrected those little fubars, my wee script ran. Now on to Exercises 3.1 and 3.2. I guess you can change the order of function definitions and still have the program run OK. But these two exercises were absolutely benign next to what I knew was coming later.

I think part of what makes "Day 3" difficult is just keeping concepts like parameters, arguments, variables, statements, and functions straight. A nice picture or diagram would have helped. Actually, Downey did include a stack diagram, which is how programmers graphically keep track of which variables are used where, but I think this is part of a "think like a computer scientist" thing. A "non-scientific" picture of the overall process might have been helpful. I found a handy bullet point list at chucol.mml.cam.ac.uk to organize these terms for me somewhat.

I also had a heck of a time getting the first function in the Parameters and Arguments section of the chapter to work until I defined "bruce," which wasn't made explicit in the text. I did it wrong, since I treated the parameter "bruce" like a variable, but it worked. I wasn't satisfied however, completely exited from the shell, opened a new shell, and finally got it to work. I'll never know what I did wrong the first time, though.

I mentioned stack diagrams before and they're tricky because, at least as far as the example in Chapter 3 goes, they're read from the bottom up. The natural human tendency is to read from the top down. On the other hand, I'm a highly visual person, so it does help to have a picture to follow when trying to remember lots of little details, like parameters and variables inside a function.

There were a few concepts that were introduced but I'm not sure how much I was expected to understand. Pages 30 and 31 talked about __main__ as a built-in Python function and None as a special value (None comes back to haunt me later). After this, I was "treated" to information that seemed a little more digestible such as "Why Functions?" which I thought should have been at the beginning of the chapter, and how to import from within a module such as "from math import pi" rather than importing all of the math module with, "import math".

The Debugging section primarily addressed the various problems you can run into with text editors, although it still would have been nice if Downey would have expressed a preference. Maybe he wants his readers to "think outside the book" and do that investigation themselves. I dunno. The Glossary section is especially handy for people like me who have problems connecting concepts and "jargon" with what they actually do. But then, I'm stalling, because I'm living in dread of the Exercises section. Will I be able to successfully navigate the three remaining exercises without either cheating or giving up?

No. I cheated. I found the answer for Exercise 3.3 (I won't tell you where) and the problem made a sort of sense when I saw the answer. I copied it into a script and ran it and it worked. I think most of the required information was contained in the chapter, but I obviously don't "think like a computer scientist" because I couldn't intuitively put it together, even with the clue Downey inserted in the question for the exercise.

Actually, even after looking up the answers (or what were supposed to be the answers) for Exercise 3.4, they still don't make sense. This is typically where I get stuck trying to learn to program, think like a computer scientist, or whatever you want to call it. In a classroom setting (which is where I appear to belong), I could always tuck my tail between my legs and slink off to the instructor's office to ask what I'm doing wrong, but working alone (with everyone who reads this blog watching) at home, it doesn't quite work out so well.
I always imagine that a relatively intelligent person can pick up at least the basics of a particular discipline, including programming, but this is where I've hit my wall once again. Unless I can get past this point, I'll either be stuck at Day 3 forever or my efforts to try and "think like a computer scientist" will expire. Is there something different I could be doing or is there some way of presenting this information that would facilitate learning for a newbie better? From inside the problem, I can't tell.

Allen, are you out there?

Monday, September 10, 2012

My 19 Days of Python: Day 2

I'm tempted to call Day 2 of My 19 Days of Python, "You had me at 'unladen swallow.'"

Authors like to tell their readers a little bit about themselves in their books and Allen Downey is no exception. In reading Chapter 2: Variables, Expressions, and Statements, in his book Think Python, I discovered that he likes Monty Python and particularly their Holy Grail film, he's a runner, (based on "running" related exercises in the first two chapters of the book) and he (groan) likes math word problems.

Of course the Monty Python references in Chapter 2 could also be a subtle nod to the fact that the Python programming language is named after the comedy troupe and not the snake. But I'm sure all this isn't why you visited my blog today.

One of the other things I discovered about Downey's book on Day 2 is that exercises and conceptual content are intermixed within the chapter, at least up to a point. Most books that purport to teach you programming usually tell you about a particular topic in the first 90% of the chapter and save all of the exercises for the end. This typically forces the reader to go over an exercise and then thumb back to the relevant sections of the chapter to try and acquire the clues that will let them solve an exercise (which can be a real pain in books that have chapters that are 70 pages long).

When I encountered Exercise 2.1 on pages 14-15, I thought I had a handle on what the solution might be, but I couldn't be sure. I noticed in going over the book previously that there's no "answer" section, either at the end of the chapter or at the end of the book. I know that text books won't always have the answers to the exercises, and publishers in that case, will provide an instructor's edition of the book for the class teacher. I thought that kind of lets out those of us who are working at home, but maybe I was being unfair. Sometimes the author provides a website for the book with additional material, including help with the exercises.

The good news is that Downey does have a site for "Think Python." The bad news is that it wasn't what I expected: http://www.greenteapress.com/thinkpython/. There's more and different material that I certainly want to explore at a later date, but nothing that I could immediately apply to my "Day 2" experience. Fortunately I remembered that "Google is your friend" and discovered the solution to Exercise 2.1 at stackoverflow.com. (Sorry if I'm giving too much information away, but this series is supposed to be my unabridged thoughts and feelings as I move through each of my "Python days.")

I discovered that there are things about Python that can't be crammed into 300 pages and bitwise operators is one of them. That's OK since I'm still working on riding this bicycle with training wheels attached.

Downey introduced the concept of variables and then let me explore how variables work in an elementary way on the command line. The same for operators and operands, and expressions and statements. In just nine pages, I wasn't going to get a lot of practice. This seems just enough to give the reader a taste of what a concept is, what it means, and a tiny experience on how it works (and what happens when it doesn't work).

Exercise 2.2 requires that the reader run a small bit of code, both in interactive mode and in script mode. What may not be obvious to the rank beginner is that they will need to know how to create a script using a text editor, save the text file with a .py extension, and then on the command line, navigate to the location of the .py file and run it (you can't be in interactive mode on the command line when you run a script). Downey briefly mentioned this in Chapter 1, but most other beginning programming books will make this rather overt. For the sake of the total newbie, some step-by-step instructions, either in Chapter 1 or in the Introduction would be helpful.

The Order of Operations section sent me all the way back to ancient days and Algebra (not my most pleasant memories but after all, I am a writer, not a calculator). Somewhere in the book, Downey may have mentioned that 2**3 turns out to be 23, but I don't remember where. It's important to understand this in order to perform one of exercises at the end of the book. If you suffer from chronic "mathphobia" or some similar malady, you may feel a bit of a twinge at this point in the chapter.

Looks like there will be a Debugging section in each chapter pointing to common problems or errors the reader may encounter. In the case of Chapter 2, common errors will be using illegal variable names or illegal characters. Add to that the common (for me) error of using a single quote at the begining of a string and a double-quote at the end such as, 'this is a bad string". Oops.
SyntaxError: EOL while scanning string literal
Exercise 2.3 gave me some practice with variable assignments and made me remember how to find the types of values (str, float, or int) I was working with. Exercise 2.4 contained three "evil" math word problems. I finally worked my way through the problems but it was more like a basic Algebra tutorial than learning how to program. Either the emphasis on math problems is because knowing how to solve these little puzzles is required for later chapters in the book, or because Downey just likes math word problems.

Suffice it to say that I augmented my ability to complete the exercises with a certain amount of searching on Google. Do I know more about programming at the end of Day 2? I suppose, but I still feel like I'm just skirting around the edges of Python, programming, and "thinking" computer science. Actually, I feel more like I'm back in high school, and I never wanted to take the Wayback Machine down that part of my history again.

We'll see what Day 3 brings.

Sunday, September 9, 2012

My 19 Days of Python: Day 1

Chapter 1: The Way of the Program. The title of this chapter immediately made me think of "the Way of Bushido, but my mind takes random turns and makes strange associations from time to time. Still, it's either a very dramatic way to begin the journey of learning to think like a computer scientist, or at least something that sounds vaguely mystical or philosophical. Sort of like Zen and the Art of Motorcycle Maintenance. But I digress.

This is the very first chapter of Allen Downey's book Think Python, and the very first day of My 19 Days of Python. What will it teach me?

First off, the chapter starts differently than most of the beginning programming books I've read. It starts out conceptually. OK, a lot of books start out with the concepts of programming in general and the programming language being addressed in specific, but then they drone on for 50 or 70 or 165 pages boring the reader half to death and making them beg to either be put out of their misery, or to be allowed to write the 'Hello, World!' program and then move on.

Downey starts out with a conceptual section but it has two qualities I appreciated: 1. It was brief. 2. It was useful to the beginner (me, that is). What's a low-level language and why is it sometimes called a machine or assembly language? What's the difference between a low-level and a high-level language? You might not think these distinctions are important if you're just going to learn how to program, but the goal of the book is to get the reader to think like a computer scientist, which means the reader will have to understand some basic terms and concepts.

This also helps if you plan on talking to, or maybe just listening to more experienced programmers (and at this stage of the game, that includes just about everyone). That is, if you expect to understand little bits and pieces of what they're talking about. In addition, learning these distinctions helps the reader better explain what they're doing to others, which comes in real handy for people like me who are reviewing this book.

Actually, more than anything, I really appreciated the description of natural vs. formal languages. It makes a great deal of sense to talk about programming in these terms since everyone uses a natural language with which to communicate (in my case, English). We're all familiar with one or more formal languages, such as math or chemistry, and this helps the readers build a bridge from concepts and ideas we're familiar with to the one we're trying to learn; the formal language of programming.

This could have been a real snooze but as I said, the section is relatively brief and it's presented in a way that (for me at least) is engaging and even compelling.

Guilty admission: I skipped Exercise 1.1. It's actually placed in the middle of the chapter and not with the rest of the exercises at the end, and it could be considered a "pre-programming" exercise. However, I've done enough writing and editing in my career to be able to readily picture how a sentence looks when it is constructed using invalid tokens and/or with an invalid structure. Believe it or not, it's the reader's first foray (there I go with military metaphors, again) into parsing and debugging.

The bottom of page 7 has a section called "The First Program," and so I thought, "Here comes 'Hello, World!'".

Well, sort of. Downey briefly describes a print statement and lightly touches on Python 3, though it seems the reader will won't be asked to learn programming on Python's "bleeding edge."

I was a little surprised at the Glossary section being included near the end of the chapter, (each subsequent chapter has a Glossary) but it makes sense if part of the book's intent is to be used in the classroom. This also allows the reader to have immediate access (instead of repeatedly thumbing pages at the back of the book) to the meanings of specific terms used in the current chapter.

OK, that's the "set up," but most readers by page 11 will be ready to write their (our, my) first program in Python.

But wait a minute.

Downey briefly mentions Linux (well, really the UNIX command window) on page 3, but he didn't include some information that an absolutely beginning programmer/computer scientist will need to know. How do I run Python on my computer? It's not quite the same thing using Windows vs. Linux. What do I have to do?

Since I'm using Ubuntu 12.04 (Precise Pangolin) for all of my exercises, and I've read a few books on Python before, I know that Python is already installed on my Ubuntu PC and all I have to do is open a terminal, type "python" at the prompt, and presto, I'm in interactive mode.

If a total programming neophyte wants to get past this step, they'll need to go online and look up how to install Python and then run it on whatever operating system they're using.

Hint: If you're using Windows 7, try this handy tutorial. Assuming this book will eventually go into a second edition, or better yet, a second printing of this edition, I'd like to see Downey include a little information to help the reader find out if Python is already installed on their computer (Linux, Mac, Windows), and if not, how to install it. Then, of course, explain to the reader how to start a terminal session and start Python.

If this is a beginner's book, these are beginning steps.

The exercises.

I assume Exercise 1.2 is more a "look ahead" since a "programming virgin" will be able to review the information at http://python.org/ but not make a lot of use of it right now.

I've never seen the help feature for Python in the terminal before, so Exercise 1.3 was kind of interesting. Without any experience with Python though, the reader (me) can do about the same thing as he or she could do on the Python.org site; just noodle around and poke their nose into a few corners. There's no way to really know what you're looking at until later on (hopefully).

The last exercise is a math problem but not a horribly complicated one. It's more of a "familiarity" exercise designed to let the reader actually "do something" in interactive mode with Python.

At the end of Day 1 of my 19 Days of Python, I didn't feel really challenged, but so far what I have been asked to understand and perform has been well within my grasp. But then a lot of beginning programming books start out this way. Downey's introduction to the book even said so. Chapter 2 is called "Variables, Expressions, and Statements," so I assume that's when I'll actually have to do more than convert kilometers to miles.

At this stage in my journey, I'm concerned with two things: 1. The ability to retain information as I move from one chapter to the next, so that I can use information I learned on one day when I'm performing exercises on subsequent days. 2. (this one is critical) Eventually being able to understand enough Python and to think, even a little bit, enough like a computer scientist to write simple programs in Python on my own, and not just copy them from the book or other sources.

Will I be able to get that far and will Downey's book be able to take me there? That's what we're going to find out together as I progress through the next 18 days of Python.

Friday, September 7, 2012

My 19 Days of Python: The Introduction

I recently requested (asked for; begged for) a review copy of O'Reilly's new Think Python book. Over the years, I've toyed with the idea of learning (no, actually learning) how to program in at least one language, but I never could get past a certain point. Usually, it either came down to getting stuck at a particular stage and never being able to progress forward or I just plain ran out of discretionary time and had to pursue more productive activities (write a book).

I've always felt that there should be a book "out there" that would be able to take a non-programmer and successfully lead that person (namely me) to be able to program in a particular language, as opposed to just copying exercises out of a book or from some online source. I've looked at various texts over the past several years but never found one that fit the bill. I had high hopes for V. Anton Spraul's Think Like a Programmer, but ultimately the book failed due to lack of accessibility and ease of use (in spite of the author's comments otherwise, C++ is not an ideal first language for the "learn-at-home-in-your-spare-time" student).

At about the same time I heard about Think Like a Programmer, I discovered Think Python, but Spraul's book arrived at my home first so I reviewed it first. Then Downey's book was delivered by UPS and I started peering into the first page's of his text. I found it refreshing and very honest:
In January 1999 I was preparing to teach an introductory programming class in Java. I had taught it three times and I was getting frustrated. The failure rate in the class was too high and, even for students who succeeded, the overall level of achievement was too low.

One of the problems I saw was the books. They were too big, with too much unnecessary detail about Java, and not enough high-level guidance about how to program. And they all suffered from the trap door effect: they would start out easy, proceed gradually, and then somewhere around Chapter 5 the bottom would fall out. The students would get too much new material, too fast, and I would spend the rest of the semester picking up the pieces.
Yes! In a nutshell, that's my experience with just about every book I have ever used to try to learn to program. I work with software developers every day and in listening to their conversations, they seem to be a group of people who are just "wired" to know how to learn to program. I believe that people have certain natural aptitudes that allow them to acquire specific skill sets with some relative ease, while those who are wired differently struggle and ultimately fail to acquire the same skill sets, even when generating great effort to learn them.

I don't think I'm wired to be a programmer. I don't "think like a programmer." I think like a writer, which is what I'm good at. However, I'd like to expand my areas of interest and competency and stretch myself a bit so that I could learn how to program. Not only do I need to successfully learn a programming language and to write programs in that language, I need to learn to "think" in a way that allows me to program. If Spraul's book isn't written to teach me to "think like a programmer," then maybe Downey's book is.

Certainly Python is a more "accessible" language, since it doesn't need to be compiled. Linux (specifically Ubuntu 12.04) has a Python interpreter available, so all I need to do is open a shell, type "python" at the prompt, and away I go.

Downey's goal in writing his book (the book actually has a number of contributors who have become involved thanks to the fact that it was originally released under the GNU Free Documentation License, so Downey isn't the sole creator of this product) is to provide a resource to assist students, both in class and learn-on-your-own, to "learn to program and think, at least a little bit, like a computer scientist."

It seems as if Downey should have the background to enable him to accomplish his task:
Allen Downey is an Associate Professor of Computer Science at the Olin College of Engineering. He has taught computer science at Wellesley College, Colby College and U.C. Berkeley. He has a Ph.D. in Computer Science from U.C. Berkeley and Master’s and Bachelor’s degrees from MIT.
But how can I tell if his book really does what Downey says it does? The answer is to use it to learn how to program in Python.

Here's what occurred to me.

The book has nineteen chapters. Each chapter is relatively short, maybe ten to fifteen pages per chapter, including glossary section and exercises. That doesn't seem like a lot of material, but looking at the table of contents, the book seems fairly comprehensive.

I could kill two birds with one stone: thoroughly read and practice with the book so I could write a good review, and learn to "think like a programmer" (at least marginally) and as a result, learn to program in Python. I could take a chapter a day (I'll explain this part in a minute) and see if, by the end of the book, I was where I wanted to be, not as a programming expert, but as a fairly competent "hobbyist."

So that's what I'll do. I'll write a blog post after I successfully read each chapter and perform the exercises it requires. That's nineteen blog posts or "my 19 days of Python" using Downey's book. Nineteen "chapters" on my blog to write a book review. What more could a publisher want?

As I go through each chapter, I'll post my responses, successes, frustrations, not only with the book but with the process of learning to change my thinking to adapt to "thinking Python." This is just the introduction. My next post in this series will be on my experiences with "Chapter 1: The Way of the Program."

Is Think Python really a different book? Is it the "magic text" that will teach a non-programmer like me to program? That's what I'm going to find out. That's what we'll find out together.

Wish me luck and come along for the ride.

Friday, August 17, 2012

Codecademy Revisited

I recently received an email notice in my inbox "Announcing Python at Codecademy". Well, it's about time. I reviewed codecademy's learn to program tutorial about a year ago (featuring JavaScript), but the lessons ended and there was no place to go, so I stopped visiting their site.

A year passed and I pretty much forgot about Codecademy until I received their email. Curious, I decided to browse the site.

The home page looked the same as I remembered it. "Learn to code". "Get Started (it's free)". I clicked the big, green button and the page dimmed except for the field with the active cursor and the prompt to type in your name with "quotes" around it. I was taken through the beginning of the JavaScript module, the "teaser" for the course, by putting in my name, finding out its length, and doing some elementary math computations. Once I got through the intro, I was prompted to start the next section.

What I was trying to find out is if the JavaScript tutorial had gotten past "while loops". It was difficult to tell what the whole JavaScript course consisted of since each lesson forces you to go step-by-step rather than skipping ahead. As far as I could tell, the JavaScript tutorial had been significantly re-worked and ended on variables after about five sessions.

I wasn't interested in going through the JavaScript tutorial at that point and clicked the "Learn" button at the top of the page. What I found was that after a year, Codecademy has a lot more to offer:

  • JavaScript Fundamentals
  • Python
  • Web Fundamentals
  • JQuery
  • Code Year

It didn't look like the different offerings were necessarily interdependent, but you could go through the JavaScript Fundamentals course and then hit Web Fundamentals to learn HTML and CSS, progress through JQuery as your JavaScript library, and then conclude with Code Year to learn how to build websites with JavaScript. I know Python doesn't seem to fit the path, but it is (or seems to be) the newest module as it's "beta" tag discloses.

It will take a little time go to through a significant portion of the tutorials in order to learn enough to update my original review, but I did want to let anyone reading this know that Codecademy is back on my radar after a year.

I'll post subsequent blogs and let you know what I think about the details.

Monday, August 8, 2011

The Python Standard Library by Example: A Review

Paperback: 1344 pages
Publisher: Addison-Wesley Professional; 1st edition (June 11, 2011)
ISBN-10: 0321767349
ISBN-13: 978-0321767349

Stop! If you are just beginning to learn the Python programming language, do not buy this book! This book was written for intermediate to advanced Python programmers who want to be able to put their hands on the Python standard library of modules (which is why I'd recommend buying the hard copy if you meet the qualifications). This is not a book that will teach you the first steps in programming in Python.

Another thing. Although the transition to Python 3 is coming along nicely, like the transition from IPv4 to IPv6, the future isn't here yet. This book was written showcasing the Python 2.7 library and this version of Python will likely be with us for some time. If you're looking for a Python 3 library resource, this book isn't for you.

I'm sure other books have been spawned from blogs before, but I can't recall any right off the top of my head. The book you're reading about has its origins in Doug Hellmann's Python Module of the Week series, so you can always visit his blog to get an idea of how his book reads.

Like many other programming and technical books, it's not as if this information doesn't live elsewhere, but the information isn't particularly accessible in a single location. While every copy of Python ships with hundreds of modules that span a wide field of developers, tasks, and years, the documentation for these modules isn't particularly consistent. That's where Hellmann comes in. He provides one resource for Python module documentation in a consistent "voice", and demonstrates the how and the why of these modules in a straightforward, understandable way. If you've read Hellmann's blog (and if you're an experienced Python programmer, you probably have), you'll more than appreciate his book.

The vast arena of examples are clear but the sheer volume may be a little intimidating. Hellmann's book weighs in at a robust 1344 pages, but then it is "one-stop shopping" at its finest. Programming Python "from scratch" is fine and well when you're first learning the language, but the real power of Python is in the ease of use of its library. Having all that collected in one container is a terrific advantage and, not having to search the web for specific modules, you might just come across a few that you've never heard of before, inspiring you to take a different direction to solve a problem. If you're an experienced programmer, but not in Python, you could get by with going through this book to learn the language, but as I've already said, it's really written for people who already know Python.

This is another fine addition to the Addison-Wesley Developer's Library. If you're a Python programmer, you know you want this book. Go ahead and pick up a copy of Doug Hellmann's The Python Standard Library by Example. You can't go wrong.

Wednesday, December 9, 2009

What do Interpreted Programming Languages have in Common? Part II

I begin this tutorial a few weeks ago with Part I and received some very nice comments correcting my (fortunately) minor errors. This isn't a tutorial about how to program in a specific language or even really about how to program. I wanted to show the common structure of interpreted programming languages in the hopes of revealing some common threads, rather than focusing on the ins and outs of one language. I've heard it said that if you learn one langauge, it makes learning the next one easier. My problem is I get lost in the nuances of the language in question and lose track of the basic structure of programming. I've created this tutorial series to try and correct that. This tutorial is for my education as much as anyone else's so I welcome comments but, as I said before, be polite. This is about learning.

Speaking of Languages, code examples are presented in JavaScript, Python, and Ruby. I figured this represented a healthy cross-section of commonly used interpreted languages. Now, on with the show.

Controlling Program Flow, Part I

In our last episode (sorry, couldn't resist), we left off with Arrays and Booleans. The tutorial picks up with methods of flow control. According to Wikipedia, flow control is "a statement whose execution results in a choice being made as to which of two or more paths should be followed. For non-strict functional languages, functions and language constructs exist to achieve the same result, but they are not necessarily called control flow statements." In other words, it's a way of making decisions within the program given different conditions. Speaking of which:

Conditions: These statements in a program act as a decision tree or like a set of intersections in a city. The decisions or route are dependent on what conditions are or are not true (speaking of Booleans) or where you're trying to go. The basic structure of a conditional statement looks something like this:

if (condition)
{
     conditional code;
}

That's a very general example, of course, but it gives you a place to start.

if statements:
If statements are more or less the same in all three of the languages we've been working with:

JavaScript Sample Code:

var value = 0;
if (value > 0)
{
     alert("Greater than zero");
}
Python Sample Code:

n = 0
if n > 0:
     print ("Greater than zero")
Ruby Sample Code:
n = 0
if n > 0
     return "Greater than zero"
end
Of course, that's not much of a decision tree. Each program has different conditional statements that are similar but not exactly the same, to deal with a decision that is either this or that:

if-else statements:
The following examples are equivalent and look almost the same, but not quite:

JavaScript Example Code:
var name = "Jim";
if (name == "Jim")
{
     alert("Your name is Jim.");
}
else {
     alert("You are not Jim.");
}
Python Example Code:
name = "Jim"
if (name == "Jim"):
     print ("Your name is Jim")
else:
     print ("Your name is not Jim")
Ruby Example Code:
name = "Jim"
if name == "Jim"
     print "Your name is Jim"
else
     print "Your name is not Jim"
end
That takes care of "the fork in the road", so to speak, but what if there's more than one decision to make? It can't be just "Jim" or "no Jim" all the time. What about Jim, Bill, and Heather, for example?

else-if statements:
Depending on the program, this statement is called else-if, or elif, or elsif, but you get the idea.

JavaScript Code Example:
if (name == "Jim")
{
     alert ("Good Morning, Jim.");
}
else if (name == "Bill");
{
     alert ("Good Morning, Bill.");
}
else if (name == "Heather");
{
     alert ("Good Morning, Heather.");
}
else
{
     alert ("You're not on the list.");
}
Python Example Code:

if (name == "Jim"):
     print ("Good Morning, Jim.")
elif (name == "Bill"):
     print ("Good Morning, Bill.")
elif (name == "Heather"):
     print ("Good Morning, Heather.")
else:
     print ("You're not on the list.")
Ruby Example Code:
if name == "Jim"
     return ("Your name is Jim.")
elsif name == "Bill
     return ("Your name is Bill.")
elsif name == "Heather"
     return ("Your name is Heather.")
else
     return ("You're not on the list.")
end
print name
As you can see, there really isn't much difference between now each language expresses conditional statements. The details are quite minor and I hope this all illustrates the common factors in such statements, which is the important piece to learn in this lesson.


Time limitations are forcing me to make Part II shorter than I originally intended, but at least I've got it up and on the blog. Pick through everything and see if I left any holes. If so, let me know. If not, then all is good, at least for Part II. See you next time for Part III: Loops.


Share/Bookmark

Sunday, October 11, 2009

Python: Converting from one temperature scale to another is easy, but what about eight?

In just about any class or set of tutorials involving beginning programming, there's usually a problem or set of problems having to do with converting temperatures. Just about everyone has had to write a wee bit of code to convert Fahrenheit to Celsius or vice versa. That's not much of a chore. However, there are eight major temperature scales available (though some are around now only for their historical value), according to wikipedia. What if you had to write a program that let a user convert a temperature from any of these scales to any of these scales?

Do you have any idea how many if statements you'd have to write? On the previously referenced wikipedia page, there are eight tables (one for each temperature scale) so converting from any of scales to any of scales would, in theory, require 8 times 7 or 56 if statements (it wouldn't be 8 times 8 because you wouldn't convert from a scale to itself). That's an awful lot of coding and there's got to be an easier way.

Actually, there's more than one way to make it easier, but this is a tutorial that is, or should be, within the grasp of a relative newbie to Python. I took a stab at it and came up with what I think is a pretty straightforward bit of programming that doesn't require a lot of typing.

Oh. I forgot. There is a specific requirement for the solution to the problem. The code must convert from the source scale temp to central or canonical scale, such as Celsius, and then must convert that value from Celsius (for example) to the target scale temp. Here's what I came up with. I don't claim this is the best possible solution, but I don't think there's anything fundamentally wrong with it, either (I checked with a higher power to be sure). See what you think. Here it is:

t = float(raw_input("Please enter the temp: "))
source = raw_input("Please enter the source temp scale: ")
target = raw_input("Please enter the target temp scale: ")

if t < 1000000.0:
    if source == "k":
        cel = t -273.15
    elif source == "c":
        cel = t
    elif source == "f":
        cel = (t - 32) * 5.0 / 9.0
    elif source == "r":
        cel = (t - 491.67) * 5.0 / 9.0
    elif source == "d":
        cel = 100.0 - t * 2.0 / 3.0
    elif source == "n":
        cel = t * 100.0 / 33.0
    elif source == "re":
        cel = t * 5.0 / 4.0
    elif source == "ro":
        cel = (t - 7.5) * 40.0 / 21.0
    if target == "k":
        answer = cel + 273.15
    elif target == "c":
        answer = cel
    elif target == "f":
        answer = cel * 9.0 / 5.0 + 32.0
    elif target == "r":
        answer = (cel + 273.15) * 9.0 / 5.0
    elif target == "d":
        answer = (100.0 - cel) * 3.0 / 2.0
    elif target == "n":
        answer = cel *  33.0 / 100.0
    elif target == "re":
        answer = cel * 4.0 / 5.0
    elif target == "ro":
        answer = cel * 21.0 / 40.0 + 7.5

print answer
I found all of the formulas for conversions at wikipedia, too. You can copy this code into a text editor and save it as something like covert.py, then run it to see how it works for you. Share/Bookmark

Monday, October 5, 2009

Python: input, raw_input, and inadvertently treating integers as strings

This is a "newbie" mistake, but these little details do tend to get in the way, which is why I'm posting my wee Python tutorial. If you know Python or programming, even reasonably well, this will probably seem way too simple to you. Just giving you a "heads up" so you don't waste your time.

I encountered a lesson that teaches storing conditionals using booleans. The code was presented like this:

young = age < 45 

slim = bmi < 22.0 
if young and slim: 
risk = "low" 
elif young and not slim: 
risk = "medium" 
elif not young and slim: 
risk = "medium" 
elif not young and not slim: 
risk = "high"
Of course, you can't really run this. If you try, you get this:
Traceback (most recent call last): 
File "assign_bool.py", line 1, in  
young = age < 45 
NameError: name 'age' is not defined 
I figured the solution was to modify the program to let me input the age and bmi, then print the results. I modified the code like this:
age = raw_input("Please enter your age: ")
bmi = raw_input("Please enter your bmi: ")

young = age < 45
slim = bmi < 22.0
if young and slim:
    risk = "low"
elif young and not slim:
    risk = "medium"
elif not young and slim:
    risk = "medium"
elif not young and not slim:
    risk = "high"

print risk
Like I said, if you have any real programming experience at all, you can already see my mistake. If not, read on. My modified code happily returned prompts for my age and bmi. Being scrupulously honest, I entered my correct age. I have no idea when my bmi is, so I made up a value. When I pressed enter, the value returned was "high". Just to make sure the program was working properly, I entered a young age and a low bmi. Egad! The return value was still "high". In fact, no matter what values I entered, "high" was always returned. This wasn't right. On the fly, I tried this change:
age = input("Please enter your age: ")
bmi = input("Please enter your bmi: ")
It seems very simple (and it is). Using raw_input, the data is always interpreted as a string, rather than the INT type I needed for the program to work. Since strings, rather than integers where input, Python worked it's way through the various tests and, since none of the other conditions matched, printed the result of the final clause which of course, was "high". input interprets what you enter as a python expression, which works, but isn't the best solution, since it can return a wide variety of object types. What's really needed is a way to input something that's always interpreted as a number. I did a bit of research and came up with the following solution, changing the first two lines of my program accordingly:
age = int(raw_input("Please enter your age: "))
bmi = int(raw_input("Please enter your bmi: "))
Now the program will always expect integers to be input for age and bmi. If you try to enter a string now, you'll get something like this:
Please enter your age: Fred
Traceback (most recent call last):
File "assign_bool.py", line 1, in 
age = int(raw_input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'Fred'
Play with the different input types and see for yourself. Share/Bookmark

Sunday, August 9, 2009

Python Essential Reference, 4th Edition (Developer's Library)

Author: David M. Beazley Format: Paperback, 744 pages Publisher: Addison-Wesley Professional; 4th edition (July 19, 2009) ISBN-10: 0672329786 ISBN-13: 978-0672329784 The key feature of this edition of the reference guide, is the presence of both Python 2.6 and 3.0. If you're savvy enough to be reading a review about a Python reference text, you know that Python 3.0 breaks backwards compatibility. This is a big deal in terms of how Beazley chose to update his book. To quote, "...I have chosen to omit features of Python 2 that have been removed from Python 3". Beazley also doesn't include those features in Python 3 that haven't been back-ported. This approach is the author's attempt to make the book equally serve programmers using 2.x vs. 3.0. Not that this is the only update the text has to offer. Beazley includes Python's newer features, particularly related to functional and meta-programming, resulting in the expansion of the chapters on functions and object-oriented programming, covering, for example, coroutines, decorators, and generators. The library chapters have also been updated to include modern Python modules, and the code examples and fragments reflect these upgrades. The book doesn't reinvent the wheel (just about a ton of documentation on Python already exists), but the advantage of this book is its organization, and the fact that all the data is located in the pages between the book's two covers. Keep in mind, that this isn't a tutorial, but a reference guide. While an experienced programmer could probably learn how to program in Python from this book, someone just learning programming probably could not. Chapter 1 is a self contained Python tutorial, but it's less than 20 pages long, and meant to bring an experienced programmer who's not experienced with Python up to speed. There are plenty of other good books on the market that teach Python, such as Practical Programming: An Introduction to Computer Science Using Python and Programming in Python 3 (depending on your perspective and requirements), so don't rely on Beazley's book to teach you Python from scratch. Actually, one of the few disadvantages of a hard copy book, is that it's not searchable the way the web is searchable. That said, you can still reasonably expect to hone in on what you're looking for, thanks to the excellent organization of the book. You do however, have to depend on the TOC and index. The only appendix in the book is Python 3. As appendices go, it's not too long, at just under 20 pages. It starts out with the $64,000 question: "Who Should Be Using Python 3?" Some Python programmers might be asking questions like, "if it ain't broke, why did you fix it?" With documentation still a bit lacking for Python 3, and major Python libraries and frameworks not yet ported to the latest version, using Python 3 might seem more of a "broken" than a "fix". While these issues are likely to be remedied with the passage of time, is there a justifiable reason to use Python 3 now? According to the author, in its current state, Python 3 is suitable only for experimental use by veteran programmers. For stability and usability, Beazley recommends sticking with Python 2.x in production environments. While the main body of the book attempts to blend the features that are workable in both versions, the appendix lists those features that are only supported in Python 3. This is just a brief introduction to Python 3. For more details, see Programming in Python 3. The ultimate strength of this book isn't just what's been updated, but what has stayed the same. Beazley writes and maintains a really great Python reference. The reviews for the 3rd edition are off the charts, and there's no reason to believe that the current edition won't garner the same accolades. Programmers who are heavily into Python or are trying to learn, will find themselves thumbing through this text often, to put their fingers on this particular detail or that. Time to put away your dog eared copy of the 3rd edition. The new replacement is here.

Tuesday, June 30, 2009

Practical Programming: An Introduction to Computer Science Using Python

Authors: Jennifer Campbell, Paul Gries, Jason Montojo, and Greg Wilson Format: Paperback, 350 pages Publisher: Pragmatic Bookshelf; 1st edition (May 28, 2009) ISBN-10: 1934356271 ISBN-13: 978-1934356272 According to wordnetweb.princeton.edu, Computer Science is "the branch of engineering science that studies (with the aid of computers) computable processes and structures". It's the study of computer architectures, languages, and mathematical structures as applied to the process of computing. So what have Campbell, et al produced in this book...a Computer Science textbook that teaches Python? Kind of. Imagine you wanted to learn how the computer is used in the various scientific disciples. Further, you wanted to learn how computer programs and programming is used in this context to construct tools, perform investigations, and to solve problems. You also want to use a single programming language as your example. Welcome to "Practical Programming: An Introduction to Computer Science Using Python". Not a book about learning Python as such, but an introduction to the discipline of Computer Science with Python as your guide. Yes, it is a text book. Page 5 in the Introduction has a For Instructors section which should be a clue. Code samples and installation instructions for the class are available for download at the book's website. New as this book is, there's already entries in the Errata section, and as with other Pragmatic books, there's a discussion forum available for questions and comments, which will come in handy for teacher and student alike. This really is a book that starts at the beginning, even to the point of describing a prompt in a python shell on page 9. Sections in Chapter 2 include Expressions and What is a Type, so the reader isn't presumed to know Python or programming at all. Like any other textbook of worth, there are exercises at the end of each chapter. Also like many textbooks, the information is presented in a rather "dry" manner, so don't expect to be entertained. Please keep in mind that this is a textbook and the target audience is a beginning Computer Science class. Class instructors are the most likely subset of the audience to be commenting about the book at this point, since they are using the book to educate their students in the fundamentals of Computer Science (which leaves me out since I'm not an instructor, but I'll do the review anyway). The book doesn't contain any surprises. Ultimately, it teaches beginning concepts in computer programming and as such, takes the reader along the elements of learning programming. As I mentioned before, Python is the "example" language, but the student is really supposed to be learning programming principles in general, not just Python programming principles. I must admit that Python was a good choice for this task as a language to learn from, plus it has a great deal of power and scalability. Thus the Python skills learned by the student will serve him or her in future classes and in a programming career. If you want to buy this book as an individual to teach yourself the content, it will still work, but you won't have the support of an instructor or a class. You can use the aforementioned discussion group at the Pragmatic site to ask questions and review any issues or shortcomings you discover (such as packages requiring Python 2.5 be installed on your computer in order to work). Many of the programming books I review contain at least a little humor to help break the monotony of the topic being taught, but don't expect to get any laughs out of this book. Campbell and company have written this text to be "all business". If used in the classroom, the instructor or the resident "class clown" will need to provide any required distractions or levity. Perhaps this is because this book is for a beginning Computer Science class and needs to take itself very seriously. I suspect that the publisher imposed this style of writing as part of the requirements for this series. In real life, in sure the authors are very funny. This is a beginner's book, so don't expect to learn everything there is to know about Computer Science or the Python programming language. It's just one class, intended to be taught in semester one of year one of a university student's academic career (though it could also be used in a High School class of similar nature). The later chapters do touch on Object-Oriented Programming, Graphical User Interfaces, and Databases, so by the end of the course, the student should be prepared to move on. Appendix A is the book's Bibliography, so you can see the sources drawn upon and, if you're using this book independently, determine what other books you might want to add to your library. Many of the sources are other traditional textbooks, but a few are more widely used references such as O'Reilly's Learning SQL. If you don't anticipate using this textbook in an Introduction to Computer Science class, but are intending to enter into such a program, this book would fit nicely in your summer reading list, giving you a leg up on the course work. Since a large part of what you are supposed to be learning is the process of computing, exposing yourself to the principles early can only help. That, and as a standard classroom textbook, is the best use I can think to make of "Practical Programming: An Introduction to Computer Science Using Python".

Sunday, March 8, 2009

Review: Python Fundamentals (Video Training) (LiveLessons)

Author: Wesley Chun Format: Hardcover, 112 pages Publisher: Prentice Hall PTR; 1 DVD/Pap edition (January 2, 2009) ISBN-10: 0137143419 ISBN-13: 978-0137143412 Update: 2009/3/13 I finally tried out the suggestion from Pearson about getting the DVD to play on Ubuntu. Read the full update in the comments section for this blog post. Thanks. I've had bad experiences with training videos before, so I tend to shy away from them. Also, I can read much faster than a person can speak (that's not bragging, it's true of virtually anyone who can read normally) so in the same amount of time it takes to view a video training, I can read and (hopefully) absorb much more content. So what about Wesley Chun's Python Fundamentals videos? Let's have a look. As the list at the top of this blog attests, there is a book involved that's 112 pages long, but it only functions as an accompaniment to the DVD, which contains over 7 hours of video teaching by Chun. Actually, in a truer sense, the DVD should accompany Chun's book Core Python Programming (2nd Ed), also published by Prentice Hall. The DVD doesn't contain any new content but rather, presents the core concepts of the "Core" book in video, rather than text format. This is a matter of preferred learning style, not accessing video to access new information. In other words, if you have Chun's "Core" book (I do), then you have what's on this video. The blurb on the back of the DVD's packaging suggests that this video will work best with those who already have some Python experience. For you beginners, it does start with the fundamentals of Python syntax, standard types, and operations. The accompanying book is a distillation of the massive "Core" tome, formatted to fit the lesson plan on the DVD. Again, nothing new is presented. It's previously published content reworked to fit video. Frankly, after having gone through some of the lessons, I don't see why a person with virtually no Python experience wouldn't also be served by this product. Then again, keep reading to see if this video tutorial will work for you. Do I sound like I think Chun is "cheating" by recycling previously used content? In one way, it does involve only a little more work on the author's part, since all he has to do is adapt what he's already written. On the other hand, Chun has to shoot the live videos and the slides. I did this exactly once and I didn't think it was fun at all. Relating to a live class of real people is one thing, but talking to yourself as you're shooting little movies on your computer is (at least for me) darn awkward. Doing the "head shots" is the last step of making an instructional video (at least from the author's perspective), so don the neutral, short sleeved polo shirt, have a seat in the video studio, and start doing "takes". But enough of the process of making a video guide. How does this particular set of DVD lessons stack up? Some negatives immediately occurred when I slipped the DVD into my Ubuntu machine. It didn't play. Turns out that the disc is formatted to play on Windows and Mac only. Linux users need not try. Bummer, Prentice Hall. Fortunately, I keep a Windows computer around for just such an eventuality. The next "bummer" moment came when I was informed that the video plays best at a screen res much higher than is supported by the video card in my (older) Windows PC. It will still play, but you have to click past the prompt telling you to change the res to 1280 x 960. Ironically, Chun mentions towards the beginning of his lesson, that the student probably has Python on their computer if they have a Mac or UNIX-like machine such as Linux (though, he pronounces it "lee-nix" as opposed to "lin-ux"). There are 10 separate lessons contained on the DVD, but even the first or introductory lesson, is really made up of many, small movies that are only a few minutes long. You'll need to continue to click "next" after each small movie. This is probably a good idea if you plan on toggling back and forth between the video and practicing python. Of course, you can always pause the video to try something out. In my case, it would actually be better to run the video on my Windows machine and to practice on my Ubuntu (Linux) machine sitting next to it. In order to be understood by the maximum number of people, Chun was likely instructed to speak more slowly than he probably does in actuality, which gives his voice a slightly "unreal" presentation. It also makes everything go really, really slow...at least for me. Like I said, I can read much faster than a person can speak. While each lesson has an Exercises section in the accompanying book, there's nothing in the video that takes the student through the exercises. The video is pretty "static" in the sense that all it really offers the majority of the time is Chun's voice and a series of slides. It would be like watching a long series of small PowerPoint presentations while listening to the presenter on a speaker phone. Not quite what I was expecting. I was hoping to see Chun actually demonstrate using and developing with Python, which wouldn't be hard. All he'd have to do is take movies of his computer screen with him using the command line while explaining what he was doing. The DVD does contain an "Extras Folder" holding each chapter's sample code. so you don't have to write it all out yourself. Of course, most books have an accompanying website which usually holds sample code, so the only "value added piece" is that you don't have to download the code from the web. I know that one of the real markets for video training are classes given by companies who want to bring their staff up to speed on a particular topic. Such classes may or may not be used with a live instructor. I really didn't see why I'd use this DVD to learn Python as an individual if I had a good book at my side. I also don't see developers using this video in a classroom setting. For me, the only thing I'd like to add to learning Python from the "Core" book is the ability to either email or IM an instructor (Chun would be ideal, but I know he's busy) if I had a problem or question. Of course, there are plenty of programming discussion boards on the web available for this sort of "support". I like the people at Prentice Hall and their books. I like Chun, at least relative to his writing and knowledge of Python (I've never met him, so I can't say I "like" him as a personality, though I'm sure I would). I like Core Python Programming which I previously reviewed for Linux Magazine. I guess I'm not the kind of person who learns better using videos, at least not videos formatted as this one is. Unless you really hate using books and are completely addicted to video as your learning medium, you'll be better served learning Python from Chun's aforementioned text.

Monday, February 23, 2009

Review: Python Web Development with Django

Authors: Jeff Forcier, Paul Bissex, and Wesley Chun Format: Paperback, 408 pages Publisher: Addison-Wesley Professional; 1st edition (November 3, 2008) ISBN-10: 0132356139 ISBN-13: 978-0132356138 I have something of a relationship with both Python and Django, the latter because I use Django more or less regularly to contribute my portion of an application (which shall remain nameless for the moment) that my company ("my" in the sense that I work there, not that I actually own anything) is developing. I'm already sold on the relative simplicity and power of Python based on my attempts to hammer away with the language, so this book, at least as far as the topic is concerned, is everything I could ask for. But can the same be said for the content of the book? I was going to say "first things first" and then proceed to the target audience for the book, but there's another point to make before that. The little "button" on the front cover says "Covers Django 1.0". I visited the Django Project and on the download page (as of this morning, February 23rd) it says, "The latest official version is 1.0.2. Here's how to get it". Assuming you want to use the latest version of Django, having a book that presents the latest information (well, as recent as any print documentation can be) is an enormous advantage. As a small aside, the download page also states, "Python version 2.3 or higher" is required, so you don't have to be using latest version of the non-backward compatible Python 3 to use the latest version of Django (of course "or higher" can be interpreted more than one way). The second page of the Preface does something cool, if you aren't sure how much of this book applies to you. There's a little diagram that outlines the four skill/experience levels for readers, and which chapters are relevant to you depending on which level applies to you. "Brand New to Django and Python" starts you off at Chapter 1 which is to be expected, but some Python experience (but no Django) gets you going, starting at Chapter 2. Some experience with both puts you beginning at Chapter 4, and advanced learners can skip ahead to Chapter 11. At least as far as the authors' predictions go, this book has something for everyone. The book has a website, which is more or less expected these days. http://withdjango.com/ contains "auxiliary material" that is referenced in different sections of the book. Click the "Material for Readers" link and you're taken to links called "Extra resources" and "Source code downloads"; the meaning of the latter link being quite obvious. The page that becomes available by clicking the former link is a "linkfest" of Python and Django resources of every conceivable type, even if they are only barely related to the topic at hand (such as links to the official Firefox, jQuery, and Vim websites). However, back to the book. As previously mentioned, this book has something for everyone, even if you aren't familiar with Python. I say "everyone" in the context some people who have some coding experience and frankly, I wouldn't recommend this book as your first experience with Python if you hope to really learn the language. As author Wesley Chun can attest, entire books have been written on Python, so please don't assume that a single chapter will tell you all you'll need to know. That said, it should teach the experienced programmer what they'll need to know as far as a foundation for working with Django. I do recommend picking up a Python tome of some sort to strengthen that foundation, however. The 56 pages comprising Chapter 1 are just enough to whet the appetite. Chapter 2 is aptly named, "Django for the Impatient: Building a Blog". Most people learning a new technology, myself included, want to get at it right away. Few things are more frustrating than picking up a book expecting to learn to actually do something, and then discovering you have to wade through 200 to 300 pages of concept and theory before you learn to even say "Hello World!". In fact, this chapter almost literally has the reader "hitting the ground running" by putting him or her on a "deadline" to see how fast they can build a simple blog using Django. You've only got 19 pages, so you'd better hurry. Only when you've accomplished this task are you ready (according to the book) to really get started using Django as Chapter 3, "Starting Out" testifies to. You might think it's a step back, because the chapter is mostly concept, but hopefully you'll still be basking in the glow of building that first blog with Django, so moving through a concept chapter won't be as much of a chore. With the foundation now firmly laid, the book proceeds to more in-depth information. The book tries to create a balance between concept and practice and it's a delicate balance indeed. I'm not sure it's entirely successful, but it does its best. If you're looking for a simple "how to" book, this might be a disappointment. The book presents both the "how" and the "why" of Python and Django. Also, although some "beginner" information is presented early in the book, as I said before, don't let this book be your first and only Python learning experience. Without some additional background, you are going to become quickly lost as you advance through the latter pages of this text. At only 408 pages including the appendix sections, you dare not blink while reading this book. All of the relevant information is present and accounted for, but there's no fluff or padding to cushion you. Section Five is complete with a number of "Appendices" (or "Appendixes", take your pick) including "Command Line Basics", the obligatory "Installing and Running Django", and so on. This should help the beginner become reoriented, if they've lost their course somewhere in the book. If you have some programming and web development background, even if Python and Django are new to you, this book should be very helpful, as long as you can tolerate it's laser-like focus and intensity. If you have Python experience, so much the better. If you find yourself slowly getting in over your head, try reading books like Chun's Core Python Programming (2nd Ed) or Mark Lutz's Learning Python before proceeding with the Django book. Whatever you do though, have fun.

Sunday, January 25, 2009

Programming in Python 3: A Complete Introduction to the Python Language: A Book Review

Author: Mark Summerfield Format: Paperback, 552 pages Publisher: Addison-Wesley Professional; 1st edition (December 26, 2008) ISBN-10: 0137129297 ISBN-13: 978-013712929 I wasn't particularly happy when I heard that Python 3 wasn't backwardly compatible with previous versions of Python, but I tried to keep an open mind about this. When I heard that Programming in Python 3 was being published in Addison-Wesley's Developer's Library series, I saw a chance to get up to speed quickly with what had changed. I don't code on a daily basis, so my skills wax and wane, depending on how often I get the time to work with a programming language and, unfortunately, it doesn't take long for me to become "oxidized". I was interested to see how Summerfield would approach this book, published just barely a month after Python 3 itself was officially released. Would the approach be as a strict reference guide for the experienced Python user looking for what had changed, or would there be something within the pages for people trying to learn Python for the first time? The answer, or at least part of the answer, was found in the first few pages of the Introduction. Experienced Python users will be happy to know that the book works to explain what practices they may be accustomed to using in Python 2, will no longer be necessary (or productive) in Python 3. New Python users will be happy to know that the author's intent is to completely teach the Python language, rather than just offer information on what has changed in the latest version. I say "complete" with the caveat that not all of the Python libraries are represented in this book. Hopefully, that won't short circuit even the complete Python newcomer since, once they've gotten some experience in that arena, the reader will know how to access and use any of the standard Python libraries. Summerfield and Addison-Wesley have thrown a really wide net over the entire topic, and the book claims to have something between its covers for everyone, from the curious student to the most experienced developer. That's a pretty tall order, and every book that says it is all things to all people, runs the risk of having to prove it. Many times, books that say they cover "everything" are found to cover certain areas well while other areas are only sparsely presented. One thing I was looking for from this book in particular, was the ability to write some productive, or at least emotionally satisfying scripts, fairly quickly. Nothing is more frustrating when trying to learn a language from a book, than to be able to do no more than echo back "Hello World!" when you're 140+ pages into the book. I'm all for learning concept and agree that you can't be very productive with a language if you don't understand what's under the hood, but on the other hand, programming is about making something happen. That said, the first thing you learn after finding out how to install Python 3 (not as easy as you might imagine, depending on your OS platform), is learning "Hello World!". Once past that, Chapter 1 does a couple of nice things. First, it introduces the reader to the basics of programming which is a plus for the new learner (though will likely bore the experienced coder to tears), and starts the reader out right away with using Python 3. The differences aren't earth shattering, but they exist and, if you are going to learn the latest version, you should learn it from the ground up. The end of each chapter does what I wish more "learning" books would do; presents a series of exercises for the reader to reinforce the material presented in the chapter. You'll never learn a programming language unless you get your hands dirty, hit a few dead ends and, occasionally want to beat your head against the wall (but only a little). The other thing that learning books need to do is provide the answers to all exercises somewhere at the end of the book, just in case the reader gets stuck. Fortunately Summerfield and the Developer's Library series does both of these things. Another nice little feature about the book is that, if a topic is mentioned on a particular page, there's a reference to where else in the book you find information on that topic. That saves a lot of page turning and frustrated index consulting. The writing is linear and progressive, which is exactly what I need as a learner. Summerfield isn't going to win awards for comedy writing, but he's not amazingly dry either, so the 552 pages of this text are quite readable. Beyond the introduction to programming in Python 3 in the first chapter, if you progress through the first six chapters in sequence, you'll be well on your way to taking off with using Python independently. Actually, I'd recommend going up through at least Chapter 8 before taking off into the "wild blue yonder" of Python programming, to get more experience using with statements and context managers. Of course, I'm not saying to abandon the book after the eighth chapter, but I am saying that you should be a fairly competent Python programmer at that point. The rest of the book's content tends toward specialty topics. An example of a "specialty topic" is Chapter 12, which presents the Python Regular Expression language and, to get a preview of what this chapter contains, you can visit InformIT.com and read the chapter excerpt for free. Definitely a plus if you want to get more of an idea of what the book contains before committing to spending your hard earned green buying this text. A few caveats. I run Ubuntu Hardy Heron and had a heck of a time trying to figure out the correct repository to add to /etc/apt/sources.list. I finally took the advice I found at this blog, though I much prefer letting the apt system manage my software. The Intrepid Ibex's repos have Python 3 already, so If you're an Ibex user, you're all set. I mention this only because the book isn't going to be able to give you every possible method of installing Python 3 for all conceivable operating system platforms and their versions. Believe me, I worked Google to the bone before going with an installation option that didn't start out with sudo apt-get install. The other important thing to note is that, if you have programs running on your computer or server using earlier versions of Python, don't make Python 3 the default. You'll want to run both versions of Python side-by-side to avoid breaking anything (that is, unless you don't mind rewriting everything in Python 3). If you're the proud owner of this book, comment back here on my blog and let me know what you think. Update: If you want Python 3 on Ubuntu Heron, you'll have to install it via the link I posted in the review. Only the Ibex repositories will have it available. Looks like it's time for me to upgrade.