Programming Python, Part II
One of the Python's looping constructs is for. It is designed to iterate over lists, sets, maps and other iterable objects. In this case, it takes all the items in self._posts and, one by one, assigns them to the variable post. In the body of the for, which is executed on each iteration, we can use the variable post.
The body of the for, as with other constructs that need a piece of code, is delimited by nothing more than the indentation. Here's an example:
>>> the_list = [1,2,3,"a","b"] >>> for item in the_list: ... print item ... 1 2 3 a b >>>
Various tasks are solved with a loop. One such task is doing something for each member of a collection, like we did in the previous example. For those types of tasks, the for construct is excellent.
Another common practice is to perform an action a given number of times—for example, printing “Hello, world” three times. To do that we can use:
>>> a = 0 >>> while a < 3: ... print "Hello world" ... a = a + 1 ... Hello world Hello world Hello world >>>
Another loop construct is while, and it will continue to run its body until the check—that is, the expression after while and before the colon—becomes false.
We can rethink the previous loop as iterating over a list containing the numbers 0–9. There's a way to do it with a for construct:
>>> for a in range(0,3): ... print "Hello world" ... Hello world Hello world Hello world >>>>
This is shorter and arguably more readable. What is while useful for then? It is useful any time you don't really know when you are going to stop the loop. Here are some examples:
Reading characters from a file until you encounter the End of File (EOF).
Reading commands from a user until the user enters the quit command.
Reading temperatures from a sensor until the temperature is too high.
Reading events from a user interface until the user presses the X button at the top of the window to close the program.
There's a pattern forming here—doing something until something else happens. That's what while is good for.
Some time ago, when we didn't have as many choices in programming languages and we ended up using C most of the time, the while construct tended to be much more useful than the for construct. But today, with a powerful for construct, nice functions such as range and the possibility of putting an iterator around anything, for is being used much more than while.
Here's one last example for your enjoyment:
>>> for l in "Hello World": ... print l + " ", ... H e l l o W o r l d
In the fourth line of some previous sample code, if post.is_public(), we have another new construct—an if. This allows programs to make choices based on data. It needs a boolean value and a piece of code. The code is run only if the boolean is True. If you provide something that is not a boolean, Python does its best to interpret it as a boolean. For example, the number 0 is interpreted as False, but all the other numbers as True. Here are some examples:
>>> if True: ... print "It is true!" ... It is true! >>> if False: ... print "Is it false?" ... >>>
We can perform many different types of comparisons on different kinds of objects. Note that the equality operator is ==, not = (that is, two equal signs):
>>> a = 10 >>> if a == 10: ... print "Ten!" ... Ten!
There are other comparisons, such as greater than (>), less than (<) and different (!=). You can experiment with comparisons directly on the REPL:
>>> 3 == 4 False >>> 10 != 5 True >>> 4 >= 1 True
It is common to run a piece of code if something is true and another piece of code if it is false. For example, we could do the following:
if a == 10:
print "A is ten."
if a != 10:
print "A is not ten."
This has a big problem. If we change a to b in the first case, we have to remember to change it in the second. And, the same should be done for any other little changes we do. The solution is an extension to the if construct:
if a == 10:
print "A is ten."
else:
print "A is not ten."
The piece of code after the else will be executed if the first piece wasn't executed.
Another common situation is having various conditionals for different cases. In that case, we use a string of ifs:
if a == 10:
print "A is ten."
elif a == 0:
print "A is zero."
elif a != 30:
print "A is not thirty."
else:
print "Who cares about a ?"
elif is the contraction of “else if”, and indeed, the previous code could be written as:
if a == 10:
print "A is ten."
else:
if a == 0:
print "A is zero."
else:
if a != 30:
print "A is not thirty."
else:
print "Who cares about a ?"
But, that is ugly and prone to errors. If you have 10 or 15 different cases, you'll need a 29"-widescreen monitor just to view it. (Not that I have anything against such a monitor. I'd like to have one.)
If you come from other languages that have a switch or select or case construct and are wondering where they are in Python, I'm sorry to disappoint you. Python doesn't have such constructs. There's a proposal to include them, but it hasn't been implemented yet. Right now, the solution is to use a chain of ifs, elifs and elses. After you use this a few times, it's not so bad.
Now that you know about else, here's an interesting tidbit: for and while also can have elses. What do they do? Run Python, and try it out until you discover for yourself. While programming, you'll need to run a lot of code to find out how many undocumented, obscure, almost black-magic, things work, so starting with something simple will help you get some training.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Build a Skype Server for Your Home Phone System
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Why Python?
- A Topic for Discussion - Open Source Feature-Richness?
- Tech Tip: Really Simple HTTP Server with Python
- Great
36 min 24 sec ago - Reply to comment | Linux Journal
44 min 25 sec ago - Understanding the Linux Kernel
2 hours 59 min ago - General
5 hours 28 min ago - Kernel Problem
15 hours 31 min ago - BASH script to log IPs on public web server
19 hours 58 min ago - DynDNS
23 hours 34 min ago - Reply to comment | Linux Journal
1 day 6 min ago - All the articles you talked
1 day 2 hours ago - All the articles you talked
1 day 2 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
error?
cool = blog.Post("Cool", "Python is cool")
I can't get the above line to work. Is that correct?
error?
Were you using Emacs and following the instructions in part I? If so, the class "Post" will be part of the module "blog". If not, you must arrange for that yourself - the article explains.
If I understand correctly. I'm not a Python programmer. :)