TweetFollow Us on Twitter

Mac in the Shell: Learning Python on the Mac: Code Blocks

Volume Number: 25 (2009)
Issue Number: 01
Column Tag: Mac in the Shell

Mac in the Shell: Learning Python on the Mac: Code Blocks

Aka: the big indent

by Edward Marczak

Introduction

The previous two columns have begun to introduce us to the Python scripting language, and some OS X-specific ways to start scripting, and OS X-specific issues. The first article got into the very basics of Python and the Python interpreter. The second article got into the specifics of the string collection type. This month, we'll see how Python implements flow control and how to specify blocks of code.

Get Used To It

Love it or leave it, but in any case, get used to it: Python uses whitespace indentation levels to specify blocks of code. If you're new to scripting altogether, this may not seem odd. However, if you already have experience with another language, C, perl or PHP, perhaps-a curly brace language-this will be something you need to adjust to. Whitespace isn't just used to make code readable or pretty, it's a function of the language. You'll realize this if you tried any of the samples from last month and mistakenly indented anything. For those of you who are perfect typists, though, here's the effect (note the leading space on the second print line):

#!/usr/bin/python
print "Indentation is important"
 print "in Python!

Running this code produces this error:

IndentationError: unexpected indent
Program exited.

So, what's this all about? It all comes down to flow control: choosing one path of code over another based on some comparison or value. The chosen path will run or skip a block of code. These code blocks are grouped together by a common level of indentation. Before we begin, you should understand that the whitespace used can be any whitespace - tabs or any number of spaces. However, choose one style! Choose one and stick to it. Spaces vs. tabs can become a bit of an argument. I used to be a tab adherent, but now use two spaces. Spaces are fixed in a fixed width font, display easily in a browser or on paper, and make it easy on tidy-like apps. Choose the style that suits you best; just be consistent. I'll be using two spaces in my articles. Any decent text editor (BBEdit, TextMate, Xcode, and so on) should let you set what the tab key actually inserts.

This particular column may seem to jump around a bit, but if you read through, you'll see how it builds and all ties together by the end. Let's get started with the most basic: the if statement.

if

The if statement checks a condition and if it is true, runs a block of code statements. The general form is:

if condition:

That's it. It's nicer to see in action, though. You can type this in and run it:

#!/usr/bin/python
x=5
if x > 10:
  print "The value of x is greater than 10!"
  print "Yes, it really is."
  
print "Done."

Since the value of x is not greater than 10, the two indented print lines (a code block) is skipped. All this program prints is "Done.". However, if we change x to, say, 20, and run the program again, the condition in the if statement becomes true (yes, x is greater than 10), and the two print statements in the if code block are executed.

No curly braces, no BEGIN or END statements, just the level of indentation. Code blocks can also be nested. If there is a condition that you'd like to check that only applies within a particular code block, its code will start at a new level of indentation. For example:

#!/usr/bin/python
x=55
if x > 10:
  print "The value of x is greater than 10!"
  print "Yes, it really is."
  if x > 50:
    print "In fact, it's greater than 50!"
    print "It is %s." % x
  
print "Done."

All of the print statements in this program will be executed.

Truth

Comparison operators reduce their decisions to, and act on one thing: truth. Not some philosophical, grey area truth, but a Boolean True or False. Like many other languages, "false" is 0. True, then can only be one thing: not false. While most people then interpret true as "1", it's actually any non-zero value. The following is true:

if 1:
  print "It's true!"
But be aware that this is true also:
if 18:
  print "It's true!"
and this:
if -12:
  print "It's true!"

A genuine Boolean type was added in Python version 2.3. This introduced the keywords True and False (note the capitalization). While True and False are actually just another representation of 1 and 0, respectively (Booleans are a subclass of the int class), the abstraction helps make code more readable. If you're looking at someone else's code and the value "1" is being passed into functions or returned from functions, it's tough to derive its meaning. However, "True" and "False" give a much better indication of their meaning at first look. Here's a simple code snippet that illustrates Boolean values in Python:

print_it=True
if print_it:
  print "The variable is true!"
  print "It's type is %s." % type(print_it)

This foundation will help you better understand what the comparison operators are doing.

Comparison Operators

When writing a comparison statement, you will need to use an operator that specifies the comparison to make. Here is a list of Python's comparison operators:

<   Less than   
>   Greater than   
==   Equality   
!=   Not equal   
>=   Greater than or equal to   
<=   Less than or equal to   
is   Equal   
not   Not equal/negation   

You've already seen the > operator in action. The < operator works similarly. The double equal sign (==) is used to test for equality. This is different than the assignment operator (=, or, single equal). It's a common mistake in C, C++ and PHP to use the assignment operator when you meant to use the equality comparison operator. Fortunately, the python interpreter will flag this as an error. Running this code snippet:

if x=5:
  print "x is 5"

...at runtime will yield :

SyntaxError: invalid syntax

The remaining operators are pretty self-explanatory, with perhaps the exception of the "is" operator. is tests for object equivalence, and is different than the simple equality comparison operator. As outlined in the first article in this series, everything in Python is an object. Object identifiers may be pointing to the same object, and this is what is tests. Let's take a look at an example to solidify this concept:

#!/usr/bin/python
x=5
y=x
if y is x:
  // y and x point to the same object
  print "Yes, y is x: y is at %s and x is at %s." % (id(y), id(x))
x=7
y=7
if y is x:
  // y and x both point to the same int object
  print "Still, y is x: y is at %s and x is at %s." % (id(y), id(x))
x=5
y=10-5
if y is x:
  // 5 is 5, no matter how it's derived
  print "Once again, y is x: y is at %s and x is at %s." % (id(y), id(x))
y=2
x=3
if y is x:
  print "y is now not x, so, this will not print."
Integers can be compared directly, too:
if x is not 0:
  blah

Like the Boolean class, using this style greatly increases the readability of code. However, in a future article when we get into writing our own classes and creating objects, the is operator becomes much more important than syntactic sugar.

While

The while statement also implements a type of flow control. Unlike the if statement, which decides to run a block of code entirely or not, while forms a loop, which repeatedly tests a given condition before running a block of code, and keeps running its block of code while the condition is true. Look at this common snippet of code:

the_number = 0
while the_number < 10:
  print "The count is %s." % the_number
  the_number+=1
print "Done!"

Running this snippet will print the numbers 0 through 9, and then print "Done!" When the interpreter encounters the while loop, the variable the_number meets the condition: it is less than 10, so the while code block is executed. Immediately we print "The count is..." followed by a line that increments the_number by one (the plus-equals notation is the equivalent of taking the variable on the left hand side and adding a value to itself. In other words, variable = variable + 1). When the interpreter reaches the end of its code block, it loops back to the top and runs the test again. If it is still true, the code block is run again. If the condition is now false, the code block is skipped, and execution is resumed at the statement following the while code block.

The For Loop

Another type of flow control loop is the for loop. You may have seen a for loop in other languages, but don't let those be "false friends" - the for loop in Python is different than any of them.

Python's for loop iterates over a sequence. We learned about sequences in the first Learn Python on the Mac article in the November issue. Sequences cover many of Python's data types, including lists, dictionaries and even strings. We can generate a numeric list sequence using the range function. An example using the interactive interpreter (which you access simply by typing python in a shell):

>>> print range(1,5)
[1, 2, 3, 4]

Now that we see range returns a sequence, let's look at the for loop. The generic form of the loop is:

for [variable] in [sequence]:
  code block

As a more direct example:

for i in range(1, 5):
  print i

...which outputs:

1
2
3
4

Remember that the Python for loop works with all sequences. Even strings are just sequences of characters. We can see this back in the interactive interpreter:

>>> x = "hello"
>>> for i in x: 
...   print i
... 
h
e
l
l
o

What Else?

Each flow control type presented above can have an optional else clause. The else clause code block is executed when the condition being tested is false. The easiest case to visualize is the if statement:

x = 5
if x > 10:
  print "x is greater than 10"
else:
  print "x is less than 10"

This reads in a very English-like manner: if x is greater than 10, run the first code block. If x is anything else, run the else code block. This also applies to the while loop. Modifying the while loop we used earlier:

the_number = 0
while the_number < 10:
  print "The count is %s, residing at %s." % (the_number, id(the_number))
  the_number+=1
else:
  print "running the else block"
print "Done!"

This runs the while code block, but when x is incremented to 10 and the condition is tested again, the else block will run. Unlike the if statement, in the case of the while (and for) loop, the else block will always be invoked in simple cases. The next section will describe two flow control statements that can change this.

Continue and Break

For one reason or another, you may want to skip a particular iteration of a loop, or, end it early. The continue and break statements, respectively, do just this.

continue stops running the code block that it's in, and starts the loop again at the top. For example, this code snippet will output odd numbers:

for i in range(1, 11):
  if i % 2 == 0:
    continue
  print i

Inside the loop, the first statement decides if i is even. If it is, we simply continue - skipping the remainder of the code block and starting the loop from the top.

The break statement breaks out of the code block it's in and terminates a loop.

the_number = 0
while True:
  print "The count is %s" % the_number
  the_number+=1
  if the_number > 10:
    break

This is a contrived example, but nicely illustrates the break statement. A while statement with a condition of True would normally never terminate. Inside of this loop, however, we test the value of the_number. If the_number is greater than 10, we issue break and terminate the loop.

As alluded to in the previous section, the break statement entirely breaks out of a loop. This means skipping the loop's else portion as well.

Whew

We covered a good amount of ground this month. Flow control is really the brains behind any code. Python has everything one would expect from a language. The if/else, while/else and for/else loops, crafted wisely, lead your code down the right path. From the beginning of this series through now, you can write some very basic (command-line) applications with logic. Next month, we'll get into Python functions and libraries.

Media of the month: Martin Luther King Jr.'s, "I have a Dream" speech. Read it here: http://www.usconstitution.net/dream.html, or possibly more powerful, listen to it here: http://video.google.com/videoplay?docid=1732754907698549493. It's an amazing speech, good to be familiar with.

Hopefully, you're reading this at Macworld and/or you have paid us a visit at the MacTech booth! Enjoy the show, and see you next month.


Ed Marczak is the Executive Editor of MacTech Magazine. He lives in New York with his wife, two daughters and various pets. He has been involved with technology since Atari sucked him in, and has followed Apple since the Apple I days. He spends his days on the Mac team at Google, and free time with his family and/or playing music. Ed is the author of the Apple Training Series book, "Advanced System Administration v10.5," and has written for MacTech since 2004.

 
AAPL
$118.72
Apple Inc.
+1.12
MSFT
$47.50
Microsoft Corpora
+0.03
GOOG
$539.23
Google Inc.
-1.85

MacTech Search:
Community Search:

Software Updates via MacUpdate

RapidWeaver 6.0.3 - Create template-base...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
iPhoto Library Manager 4.1.10 - Manage m...
iPhoto Library Manager lets you organize your photos into multiple iPhoto libraries. Separate your high school and college photos from your latest summer vacation pictures. Or keep some photo... Read more
iExplorer 3.5.1.9 - View and transfer al...
iExplorer is an iPhone browser for Mac lets you view the files on your iOS device. By using a drag and drop interface, you can quickly copy files and folders between your Mac and your iPhone or... Read more
MacUpdate Desktop 6.0.3 - Discover and i...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
SteerMouse 4.2.2 - Powerful third-party...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
iMazing 1.1 - Complete iOS device manage...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
PopChar X 7.0 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
Carbon Copy Cloner 4.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
ForeverSave 2.1.3 - Universal auto-save...
ForeverSave auto-saves all documents you're working on while simultaneously doing backup versioning in the background. Lost data can be quickly restored at any time. Losing data, caused by... Read more
Voila 3.8.1 - Capture, annotate, organiz...
Voila is a screen-capture, recording, and annotation tool that is a full-featured replacement for Mac's screen-capture and screen-recording capabilities. It has a large and robust set of editing,... Read more

Latest Forum Discussions

See All

Tales from the Borderland​s Will be Comi...
Tales from the Borderland​s Will be Coming to iOS by the End of the Year Posted by Jessica Fisher on November 26th, 2014 [ permalink ] Telltale Games has announced | Read more »
Sunburn! Review
Sunburn! Review By Campbell Bird on November 26th, 2014 Our Rating: :: DON'T DIE ALONEUniversal App - Designed for iPhone and iPad Platform through the depths of space to make sure your entire crew dies together in this satisfying... | Read more »
Black Friday has Started Early – Lots an...
It’s almost turkey time! Which means lots and lots of food but also lots and lots of sales. Some sales have even started a few days early, which is why we’ve put together a list of iOS games that are currently discounted (sometimes by a lot).... | Read more »
Loose Leaf Review
Loose Leaf Review By Jennifer Allen on November 26th, 2014 Our Rating: :: SIMPLE SKETCHINGiPad Only App - Designed for the iPad Sketch out ideas with simple drawing tools, courtesy of Loose Leaf.   | Read more »
Screeny (Utilities)
Screeny 1.0 Device: iOS iPhone Category: Utilities Price: $.99, Version: 1.0 (iTunes) Description: Screeny is an utility app that helps you save space consumed by screenshots. It screens your camera roll and helps you to filter and... | Read more »
Tilt to Live Bundle Set to Arrive This T...
Tilt to Live Bundle Set to Arrive This Thanksgiving Posted by Ellis Spice on November 25th, 2014 [ permalink ] One Man Left has unveiled an upcoming Tilt to Live bundle, allowing players to get the series for a di | Read more »
BattleLore: Command (Entertainment)
BattleLore: Command 1.0 Device: iOS Universal Category: Entertainment Price: $9.99, Version: 1.0 (iTunes) Description: ***NOTE: Compatible with iPad 2/iPad mini, iPod touch 5 and up and iPhone 4S and up – WILL NOT RUN ON EARLIER... | Read more »
Weather Or Not Review
Weather Or Not Review By Jennifer Allen on November 25th, 2014 Our Rating: :: STYLISH WEATHER REPORTINGiPhone App - Designed for the iPhone, compatible with the iPad Check the weather quickly and conveniently with Weather or Not... | Read more »
The All-New Football Manager Handheld 20...
The All-New Football Manager Handheld 2015 is Available Now Posted by Jessica Fisher on November 25th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Six iOS Games to Get You Ready for Thank...
Image Source: Friends Wiki At this point in the month, you or at least a few people you know are probably getting ready to scramble around (or are already scrambling around) for Thanksgiving Dinner. It’s a hectic day of precise oven utilization, but... | Read more »

Price Scanner via MacPrices.net

Why iPhone 6 Tablet/Laptop Cannibalization Is...
247wallst.com blogger Douglas A. McIntyre noted last week that according to research posted on the Applovin blog site the iPhone 6 is outselling the iPhone 6 Plus by a wide margin . Hardly a surprise... Read more
Worldwide Tablet Growth Expected to Slow to 7...
The global tablet market is expected to record massive deceleration in 2014 with year-over-year growth slowing to 7.2%, down from 52.5% in 2013, according to a new forecast from International Data... Read more
Touchscreen Glove Company Announces New Produ...
Surrey, United Kingdom based TouchAbility specializes in design and manufacture of a wide variety of products compatible with touchscreen devices including smartphones, tablets and computers. Their... Read more
OtterBox Alpha Glass Screen Protectors for iP...
To complement the bigger, sharper displays on the latest Apple devices, OtterBox has introduced Alpha Glass screen protectors to the iPhone 6 and iPhone 6 Plus. The fortified glass screen protectors... Read more
Early Black Friday Mac Pro sale, 6-Core 3.5GH...
 B&H Photo has the 6-Core 3.5GHz Mac Pro on sale today for $3499 including free shipping plus NY sales tax. Their price is $500 off MSRP, and it’s the lowest price available for this model from... Read more
Early Black Friday sale price: 15-inch 2.2GHz...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale today for $1699.99. Shipping is free, and B&H charges NY sales tax only. Their price is $300 off MSRP, equalling Best Buy’s price... Read more
13-inch 2.5GHz MacBook Pro (refurbished) avai...
The Apple Store has Apple Certified Refurbished 13″ 2.5GHz MacBook Pros available for $170 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz... Read more
Early Black Friday iPad mini 3 sale: $75 off...
 Best Buy has iPad mini 3s on sale for $75 off MSRP on their online store for a limited time. Choose free shipping or free local store pickup (if available). Sale prices available for online orders... Read more
Early Black Friday MacBook Pro sale: 15-inch...
 Best Buy has posted early Black Friday prices on 15″ Retina MacBook Pros, with models on sale for $300 off MSRP on their online store for a limited time. Choose free local store pickup (if available... Read more
A9 Chips Already?
It’s barely more than a couple of months since Apple got the first A8 systems-on-chip into consumer hands, but rumor and news focus is already turning to the next-generation A9 SoC. Apple Daily... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.