Python Tutorial for PHP Developers

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

This Python tutorial is ideally suited for those PHP developers who are transitioning to Python.  If you are a PHP developer who wants to learn Python 3, here is a quick tutorial guide of Python 3.3.3 syntax in comparison to PHP syntax.

Print Statement

In PHP, you would have done …

print("Hello World");

In Python, you do very similarly but without the semicolon…

print("Hello World")

Learn more about Python strings in a separate article.

Echo Statement

If you prefer to use echo instead of print, you could do something like this in PHP…

echo "Hello", " World";

In Python 3, you still use the print and need the parenthesis and omit the semicolon.  But comma separated strings works…

print("Hello", "World")

Did you notice that you don’t need the space in front of the W as PHP does?  That is because Python print puts a space after printing the first string.

Python also puts a \n newline character after the output of the print statement.  So if you do two print statements,

print("Hello")
print("World")

you don’t need to put \n as you would have done in PHP.  If you don’t want Python to put in a \n, do …

print("Hello", end="")
print("World", end="")

Now it won’t put a trailing space either.

Learn more about the difference between echo and print in PHP.

Switch Statement

In PHP, you have a switch statement as in …

$animal = "duck";
switch ( $animal ) {
    case "duck": echo "two legs"; break;
    case "cow": echo "four legs"; break;
    default:
        echo "don't know";
}

if-elif-else

There is no switch statements in Python, but you can always use if-elif …

animal = "duck"
if animal == "duck":
    print("two legs")
elif animal == "cow":
    print("four legs")
else:
    print("don't know")

Note that there is no parenthesis and curly braces as you would do in PHP.  The indentation is important (typically four spaces), as that defines the code block (known as code suite in Python) of the if-clause.

Note that python uses the shorter keyword elif; whereas PHP uses elseif.  Python likes concise keywords.

In PHP, you would have done …

$animal = "duck";
if ($animal == "duck"):
    print("two legs");
elseif ($animal == "cow"):
    print("four legs");
else:
    print("don't know");
endif;

Note the presence of endif and that “elseif” has no space.

Or an alternative PHP form is …

$animal = "duck";
if ($animal == "duck") {
    print("two legs");
} else if ($animal == "cow") {
    print("four legs");
} else {
    print("don't know");
}

In this PHP form, you could have used “elseif” or “else if”.

Python dictionary

Instead of switch statement, you can write equivalently using Python dictionary …

animal = "duck"
legs = { "duck": "two legs", "cow": "four legs" }
if animal in legs:
    print(legs[animal])
else:
    print("don't know")

The dictionary legs can also be written as …

animal = "duck"
legs = {}
legs['duck'] = "two legs"
legs['cow'] = "four legs"
if animal in legs:
    print(legs.get(animal))
else:
    print("don't know")

The curly braces indicates to python to create a dictionary.  And here we use the get method to access the key of the dictionary.  We check if animal is in the legs dictionary before trying to get it.

Or better yet, we could have let the get supply the default value when item not found…

animal = "duck"
legs = {}
legs['duck'] = "two legs"
legs['cow'] = "four legs"
print(legs.get(animal, "don't know"))

Python Tuple

This Python code …

mytuple = 8,7,19,9
print(mytuple)
print(mytuple[0])
print(mytuple[-1])
print(len(mytuple))
print(min(mytuple))
print(max(mytuple))

will result in …

(8, 7, 19, 9)
8
9
4
7
19

The comma is what creates the tuple, but parenthesis are convenient.  You could have used this to create a tuple…

mytuple = (8,7,19,9)

To create an one-element tuple you do …

mytuple = (8,)

To create a list you use square braces …

mylist = [8,7,19,9]

and can do the same thing that tuple can and plus more.  Tuple is immutable.  List is changable.

 

Comments

PHP comments are denoted with // or with /* comment */ as multiline comment

Python uses # in front of line.  Python does not have multiline comments, but some people use the triple-quote as such (which is a bit controversial).

Docstrings are triple-quoted strings that occurs as the first statement in a module, function, class, or method definition for documentation purposes.

Integer division

In Python, integer division is // and it has divmod function that works like …

a, b = 17, 10
print ( divmod(a,b))

This returns the tuple (1, 7).

The modulo % is same as in PHP.

Python Data Types

Some basic Python data types are Numbers, String, Tuple, List, Dictionary.  The first three are immutable. List and Dictionary are mutable.  List is ordered, but Dictionary is not.

Given…

a = 17
b = 17

Both …

print ( a == b )

and

print (a is b)

will return True.  That is because

print ( id(a) )

and

print ( id(b) )

will return the same object id that refers to the object 17.

There is no === operator in Python.  It uses the “is” instead.

While in PHP, you can write TRUE or true or True, Python wants “True” and “False”.

Conditional Expression

PHP has a conditional operator that works like …

$a = 7;
$b = 10;
echo ($a < $b) ? "a is less": "not";

The Python equivalent reads more like english …

a, b = 7, 10
print ( "a is less" if a < b else "not")

Note that in Python, you can assign multiple variables in a line.

Loops

While in PHP, you would do …

for ( $i = 0; $i < 10; $i++ ) {
    echo $i;
}

In Python, the equivalent is …

for i in range(0,10):
    print(i, end="")

There is no ++ operate in Python either.  Although there is += as in …

i = 0 
while ( i < 10 ):
    print(i, end="")
    i += 1

This results in the same output using the second (lesser-used) type of loop in Python known as the while loop.  The continue and break statements works as expected in loops.

In Python, you can interate through a list like …

myList = ["duck", "cow", "sheep"]
for animal in myList:
    print(animal)

or like …

myList = ["duck", "cow", "sheep"]
for i, animal in enumerate(myList):
    print(i, animal)

Get the length of a list by len(myList)

Python import

In PHP, you use include, require, include_once, require_once to include additional PHP files.  In Python, you use import, __import__(), and importlib.import_module().

For example, to use the SQLite3 that comes with Python, you need to import the module with …

import sqlite3

See tutorial on using sqlite3 with Python.

Python has a built-in unittest module which can also be imported.

PyPI, the Python Package Index, is where you can find third-party modules that you can import.  These modules will have a setup.py which you can use to install the module by running …

python setup.py install

On Windows, this will put the module in Python33/Lib/site-packages/

Python SheBang

It is common to see the Python shebang at the top of the file with something like …

#!/usr/bin/python

or the more portable form …

#!/usr/bin/env python

At the bottom of the file, you sometime see …

if __name__ == "__main__":
    main()

Python Functions

Here is a Python script with a main() function which calls the sayHello() function that takes a person name and prints a greeting…

#!/usr/bin/python

def main():
    sayHello("John");

def sayHello(person):
    print("Hello", person)

if __name__ == "__main__":
    main()

Since this file is the main file that is run, the if __name__ == “__main__” condition is True, and main() is called at the bottom of the file.  If this file is imported via another file, main() would not be called.

By putting code in main() function that is called at the bottom of file, we are able to call “sayHello” at a line above the sayHello function definition.

You can have optional arguments in functions …

def sayHello(person, myOptional = 1, myOptional2 = None  ):
    print("Hello", person, myOptional, myOptional2)

sayHello("John", 10)

This will print out …

Hello John 10 None

Optional arguments have default values.  The third optional argument has None as its default.

null in Python?

Whereas PHP uses NULL, Python uses None which can be checked by …

if foo is None:

pass statement

For an empty function stub, you can use the no-op statement of “pass”.

Multiple and named arguments

This function accept multiple arguments

def sayHello(person, *args ):
    print("Hello", person)
    for value in args:
        print(value)

sayHello("John", 10, 11, 12)

It comes in as a tuple which you can iterate over in a for loop.

This function accepts keyword named arguments …

def sayHello(person, **kwargs  ):
    print("Hello", person)
    for key in kwargs:
        print(key, kwargs[key])

sayHello("John", one=10, two=11, three=12)

The arguments are named by the caller and it comes in as a dictionary.  Note that dictionary has no order so the output may look like …

Hello John
three 12
two 11
one 10

 

Python Class

Classes is a big topic and hence is separated into another tutorial.

Exception Handling

Exception Handling example based on A Byte of Python using try, except, finally.

import time
f = None
try:
    f = open("poem.txt")
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end="", flush=True)
        time.sleep(2) # To make sure it runs for a while
except FileNotFoundError as e:
    print("Oopse", e)
except KeyboardInterrupt:
    print("You cancelled the reading from the file.")
else:
    print("\nsuccessful read")
finally:
    if f:
        f.close()
    print("(Cleaning up: Closed the file)")

There else: suite get called if and only if none of the exceptions catches.  The finally always gets called, regardless of exception or not.  You can also raise your own exception with the raise keyword.

In Python, there is a with statement as in this example based on A Byte of Python where …

with open("poem.txt") as f:
    for line in f:
        print(line, end='')

Here, the file is always closed at the end of the with suite.