Are you an experienced PHP developer who needs to learn Python? This article approaches the world of Python development from a PHP developer's perspective, translating familiar PHP concepts, such as variables, lists, and functions, into their Python equivalents.

Share:

Thomas Myer, Principal, Triple Dog Dare Media

author Thomas Myer is a consultant, author, and speaker based in Austin. He runs Triple Dog Dare Media and tweets as @myerman on Twitter. You can reach him at tom@tripledogs.com.



09 February 2010

Also available in Japanese

You're a PHP developer. You've probably been writing applications for the past five years (or longer), and you've built just about everything imaginable — e-commerce systems, simple content-management systems, Twitter and Facebook integrations, and a host of custom utilities. You've probably maintained a lot of code, too — everything from simple display pages to custom applications with tens of thousands of lines somebody else wrote.

Frequently used acronyms

  • Ajax: Asynchronous JavaScript + XML
  • XML: Extensible Markup Language

Because you've spent so much time working in PHP, it's doubtful that you're going to jump ship to another language. But you also know that standing still is the one sure recipe for disaster in this field. If nothing else, learning a new language is like traveling overseas: You get to see new things, taste new food, enjoy a different culture, have stimulating conversations with different people, see neat stuff, then come back home to re-evaluate your usual surroundings.

This article gives you a bit of exposure to Python. It assumes that you have no knowledge of that programming language, so some of what you read here might seem a bit basic. It focuses on comparing and contrasting Python with PHP — not because one language is better than the other but because of a simple truth: It's often easier to learn new things by referring back to something you already know.

The goal of this article is simple: to give you a quick working knowledge of Python in the hope that you'll dig a little further on your own. With luck, you'll see that Python isn't really that different from what you're used to. To extend the travel metaphor, you aren't really going to a distant foreign land, just the country next door where everyone speaks the same language as you.

What is Python?

Python is classified as a "general-purpose, high-level programming language." It is best known for being incredibly clean and easy to read, and it is one of the few languages you'll encounter in which white space and indentation actually matter. Python's principal author, Guido Van Rossum, is still very active in the community and has been bestowed the tongue-in-cheek title of "Benevolent Dictator for Life."

One of the nice things about Python is its flexibility and compactness. It supports object-oriented, structured, aspect-oriented, and functional programming, among other approaches. Python was designed with a small core and a large set of extension libraries, making the language extremely compact and flexible.

From a syntax point of view, you'll find Python very clean — almost monastic and Zen-like in its sparsity. PHP developers will either have a great deal of affection for this approach, finding relief in the syntactical discipline, or find it restrictive. It just depends on your outlook. The Python community is clear about promoting this particular aesthetic, valuing beauty and simplicity over clever hacks. Those PHP developers (like myself) who came out of the Perl tradition ("There's more than one way to do it") will be confronted with the total opposite philosophy ("There should only be one obvious way to do it").

In fact, the community has a term for code that follows a preferred style: pythonic. To say that your code is pythonic is to say that is uses Python idioms well or that you're showing natural fluency in the language. This article doesn't bother trying to be a Pythonista (or Pythoneer), but it's something you need to be aware of if you want to continue down the Python path. Just as there are certain PHP-ish ways to work and Perl-ish ways to do things, taking on Python means that eventually, you need to start thinking in that language.

Another quick note: Python was up to V3.0 at the time of writing, but this article focuses on Python V2.6. Python V3.0 is not backward-compatible with earlier versions, and it appears that V2.6 is the version most commonly in use. You are free to use whatever you need, of course.


How does Python differ from PHP?

Generally speaking, PHP is a Web development language. Yes, it has a command-line interface and can even be used to develop embedded applications, but for the most part, PHP is for Web development. In contrast, Python is a general scripting language that can also be used for Web development. In this way — and I know I'll be yelled at for this — it's closer to Perl than PHP. (Of course, in all other ways, it couldn't be more different, really. But let's move on.)

PHP's syntax is littered with dollar signs ($) and curly braces ({}), while Python is more spare and clean. PHP has a switch and do...while construct; Python doesn't. PHP has the ternary operator (foo?bar:baz) and an enormous (and unwieldy) list of function names, with all kinds of naming conventions; you'll find Python a lot cleaner. PHP has an array type that doubles as as a simple list and a dictionary or hash; Python separates the two.

Python also has a concept of mutability and immutability: a tuple, for example, is an immutable list. You create your tuple, and you can't change it after that. This concept takes a bit of getting used to, but it's a marvelous way to avoid errors. Of course, the only way to change a tuple is to copy it, so if you find yourself making lots of changes to an immutable object, you need to rethink your approach.

As noted, indentation in Python has meaning: You'll learn this the hard way in your first few days with the language. You can also create functions and methods with keyword-based arguments — a nice break from the standard positional arguments you see in PHP. The object-oriented purists will enjoy Python's true object orientation, and "first-class" classes and functions. If you're working with non-English languages, you'll love Python's strong internationalization and Unicode support. You'll also love Python's multi-threading capabilities; this was one of the features that originally attracted me.

All this being said, PHP and Python are similar to each other in many ways. You won't have any trouble creating variables, looping, using conditionals, and creating functions. You won't even have that much trouble creating reusable modules. The user communities for both languages are active and passionate. PHP's installed base is a lot bigger, but this has more to do with its popularity on hosting servers and its Web focus than anything else.

OK — enough with the intro material. Let's get down to cases.


Working with Python

Listing 1 presents a basic Python script to get you started.

Listing 1. A simple Python script
for i in range(20):
	print(i)

Listing 2 shows the inevitable result.

Listing 2. Results of Listing 1
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Let's look at a few things before going any further, starting with variables.

Variables

As you can see, there are no special characters to denote a variable. The variable i is just plain i— nothing special. There are no special characters (like semicolons and braces) to denote a code block or an end of statement, either; just a simple colon (:) on the for line. Also note that the indentation tells Python what belongs to the for loop. For example, the code in Listing 3 prints a note after each number in the loop.

Listing 3. Adding a statement to each loop
for i in range(20):
	print(i)
	print('all done?')

In contrast, the code in Listing 4 puts a note at the end of the loop.

Listing 4. Adding a statement after a loop
for i in range(20):
	print(i)

print('all done!')

Now, the first time I looked at something like that, I thought it was sheer madness. What? Trust newlines and indents to keep my code not only structured but running? Believe me, after a while, you'll get used to it (although I have to admit that I keep reaching for that semicolon key to finish a statement). If you're working with other developers on a Python project, you'll find this readability a huge bonus. You'll have a lot fewer moments of, "Now what did this clever fellow try to do here?"

In PHP, you assign a value to a variable using the = operator (see Listing 5). In Python, you use the same operator, except that you're said to label or point to a value. To me, it's just assigning, so I don't worry too much about the jargon.

Listing 5. Creating variables
yorkie = 'Marlowe' #meet our Yorkie Marlowe!
mutt = 'Kafka'     #meet our mutt Kafka

print(mutt)  #prints Kafka

Python variable name conventions are similar to PHP: You can only use letters, numbers, and the underscore character (_) when creating a variable name. Likewise, the first character of a variable name can't be a number. Python variable names are case-sensitive, and you can't use certain Python keywords (such as if, else, while, def, or, and, not, in, and is, for starters) as variable names. No big surprises there.

Python allows you to do any number of string-based operations. Most of the operations in Listing 6 will be familiar to you.

Listing 6. Common string-based operations
yorkie = 'Marlowe'
mutt = 'Kafka'

ylen = len(yorkie) #length of variable yorkie
print(ylen) #prints 7
print(len(yorkie)) #does the same thing
len(yorkie) #also does the same thing, print is implicit

print(yorkie.lower()) #lower cases the string


print(yorkie.strip('aeiou')) #removes vowels from end of string

print(mutt.split('f')) #splits "Kafka" into ['Ka', 'ka']

print(mutt.count('a')) #prints 2, the number of a's in string

yorkie.replace('a','4')  #replace a's with 4's

Conditionals

You already know how to use a for loop. Now let's talk about conditionals. You'll find that conditionals are pretty much the same as in PHP: You'll have access to the familiar if/else-type structures shown in Listing 7.

Listing 7. A simple conditional test
yorkie = 'Marlowe'
mutt = 'Kafka'

if len(yorkie) > len(mutt):
	print('The yorkie wins!')
else:
	print('The mutt wins!')

You can also build more complex conditional tests using an if/elif/else (elif being the equivalent to PHP's elseif), as shown in Listing 8.

Listing 8. A more complex conditional test
yorkie = 'Marlowe'
mutt = 'Kafka'

if len(yorkie) + len(mutt) > 15:
	print('The yorkie and the mutt win!')

elif len(yorkie) + len(mutt) > 10:
	print('Too close to tell!')
else:
	print('Nobody wins!')

As you can tell, so far there's nothing too exciting here. It's all pretty much what you would expect. Now look at how Python handles lists; you'll see quite a bit of difference between the two languages.

Lists

One common type of list is called a tuple, and as noted, it's immutable. Once you load a tuple with a series of values, you can't change it. Tuples can contain numbers, strings, variables, and even other tuples. Tuples are 0-indexed, as you'd expect; you can access the last item using the -1 index. There are also quite a few functions you can run on tuples.

Listing 9. Tuples
items = (1, mutt, 'Honda', (1,2,3))

print items[1]  #prints Kafka
print items[-1] #prints (1,2,3)

items2 = items[0:2]  #items2 now contains (1, 'Kafka') thanks to slice operation

'Honda' in items #returns TRUE
len(items) #returns 4
items.index('Kafka') #returns 1, because second item matches this index location

Lists are like tuples, except that they're mutable. Once you create them, you can add, subtract, and update the values in the list. Instead of parentheses (()), you use square brackets, as shown in Listing 10.

Listing 10. Lists
groceries = ['ham','spam','eggs']
len(groceries) #returns 3
print groceries[1] #prints spam

for x in groceries:
	print x.upper() #prints HAM SPAM EGGS
	
groceries[2] = 'bacon'
groceries #list is now ['ham','spam','bacon']

groceries.append('eggs')
groceries #list is now ['ham', 'spam', 'bacon', 'eggs']

groceries.sort() 
groceries #list is now ['bacon', 'eggs', 'ham', 'spam']

A dictionary is like an associative array or hash: It uses key-value pairs to store and retrieve information. But instead of brackets or parentheses, you use curly braces. Like lists, dictionaries are mutable, which means you can add, subtract, and update values in them.

Listing 11. Dictionaries
colorvalues = {'red' : 1, 'blue' : 2, 'green' : 3, 'yellow' : 4, 'orange' : 5}

colorvalues #prints {'blue': 2, 'orange': 5, 'green': 3, 'yellow': 4, 'red': 1}

colorvalues['blue'] #prints 2

colorvalues.keys() #retrieves all keys as a list: 
				   #['blue', 'orange', 'green', 'yellow', 'red']
colorvalues.pop('blue') #prints 2 and removes the blue key/value pair

colorvalues #after pop, we have: 
			#{'orange': 5, 'green': 3, 'yellow': 4, 'red': 1}

Creating a simple script in Python

Now that you've had a bit of exposure to Python, let's build a simple Python script. This script reads the number of PHP session files in your server's /tmp directory, then writes a summary report to a log file. In this script, you're going to learn how to import modules for specific functions, how to work with files, and how to write to a log file. You'll also set a number of variables to keep track of the information you've gathered.

Listing 12 shows the entire script. Open an editor, and paste the code into it and save the file as tmp.py somewhere on your system. Then run chmod + x on that file to make it executable (assuming you're on a UNIX® system).

Listing 12. tmp.py
#!/usr/bin/python

import os
from time import strftime

stamp = strftime("%Y-%m-%d %H:%M:%S")
logfile = '/path/to/your/logfile.log'
path = '/path/to/tmp/directory/'

files = os.listdir(path)
bytes = 0
numfiles = 0

for f in files:
	if f.startswith('sess_'):
		info = os.stat(path + f)
		numfiles += 1
		bytes += info[6]
		

if numfiles > 1:
	title = 'files'
else:
	title = 'file'


string = stamp + " -- " + str(numfiles) + " session " \
+ title +", " + str(bytes) + " bytes\n"

file = open(logfile,"a")
file.writelines(string)
file.close()

On the first line, you see what's called the hash-bang line, which identifies the location of the Python interpreter. On my system, it's at /usr/bin/python. Adjust this to the needs of your system.

The next two lines import specific modules that help you do your job. Given that the script needs to deal with folders and files, you need to import the os module, as it contains various functions and methods that help you list files, read files, and work with folders. You'll also be writing to a log file, so it's a good idea to add a timestamp to entries — hence, the need for the time functions. You won't need all of them, so just import the strftime function.

In the next six lines, you set variables. The first, called stamp, contains a date string. You use the strftime function to create a timestamp with a specific format — in this case, a stamp that looks like 2010-01-03 12:43:03.

Next, create a variable called logfile and put in a path to a file (it doesn't need to exist yet) where you'll actually store log file messages. For simplicity, I put log files in a /logs folder, but you could put them anywhere. Similarly, you need a variable called path that contains the path to your /tmp directory. It can be any path you want as long as you end it with a trailing slash (/).

The next three variables are just as simple: a files list that contains all the files and folders located at your designated path and two variables called bytes and numfiles. Both of those variables are set to 0; the script increments those values as it processes files.

After all that comes the heart of the script: a simple for loop that processes each file in the files list. Each time through the loop, the script evaluates the file name. If it begins with sess_, then the script runs os.stat() on the file to pull out data about the file (such as creation time, modify time, and size in bytes), increments the numfiles counter, and adds the number of bytes for this file to a running total.

When the loop completes its run, the script checks to see whether the numfiles variable contains a value greater than 1. If so, it sets a new variable, called title, to files; otherwise, the title is set to the singular form file.

The final part of the script is simple: You create a final variable called string, and inside that, you place a single line of data that starts with the stamp and proceeds with numfiles (converted to a string) and the bytes (also converted to a string). Notice the continuation character (\); it allows the code to run to the next line. It's a good trick to know for readability.

Then you use the open() function to open the log file in append mode (you want to keep adding lines to the file, after all), the writelines() function to add the string to the log file, and the close() function to close the file.

You've now created a simple Python script you can do anything with. For example, you could set a cron job to run this script once per hour to help you keep track of how many PHP sessions are being used around the clock. You could also use jQuery or some other JavaScript framework to hook this script up using Ajax to give you a log-file feed (if so, you'd need to use the print command to return data).


Conclusion

As developers, we spend a lot of time investing ourselves with knowledge about specific languages and approaches. Sometimes, doing so leads to debates about the superiority of one language over another. I've participated in many of these debates, as have some of you. I have to admit that most of these discussions tend to fall into the same old rut — "anything you can do I can do better" — which doesn't serve any good purpose.

However, once you start looking closely at another language, you find that most languages have similar tools, philosophies, and approaches. Learning your first language can be difficult, but taking what you know and applying it to another language can make the learning experience a lot easier. Even if you don't really take up the second language, you increase your exposure to ideas and methods that will improve your craft.

With any luck, this article has provided you with some insight into Python. My hope is that you'll continue your learning and keep looking into this great language. You may never leave the world of PHP (after all, it's what probably puts food on the table), but it never hurts to keep learning.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=466765
ArticleTitle=Python basics for PHP developers
publish-date=02092010