Wednesday, August 3, 2011

lovely Python (compared with PHP or maybe some other languages)

The Zen of Python, especially "There should be one - and preferably only one - obvious way to do it", highly attracts me. And that actually drives me to start learning Python. And once I start, I find I like it more. Just some simple examples can show how Python practise what it preaches.

Python code

name = 'henry'
if name == 'hengrui':
            print ('Hello ' + name)
else:
            print ('Is ' + name + ' your real name?')

PHP code
version 1

$name = 'henry';
if  ($name == 'hengrui') {
            echo 'Hello ', $name;
} else {
            echo 'Is ', $name, ' your real name?';
}

version 2

$name = 'henry';
if  ($name === 'hengrui') {
            echo 'Hello ', $name;
} else {
            echo 'Is ', $name, ' your real name?';
}
Found the difference in this version? Well, it is '===' not '=='.

version 3

$name = 'henry'
if  ($name == 'hengrui')
            echo 'Hello ', $name;
else
            echo 'Is ', $name, ' your real name?';

version 4

$name = 'henry'
if  ($name == 'hengrui') echo 'Hello ', $name;
else
            echo 'Is ', $name, ' your real name?';

Surely we can still have some other versions of implementation in PHP code. Like it or not? It is up to you. But for me, i don't like this kind of variations and definitely coding conventions must be set up to ensure we won't have all these different coding practices in serious projects.

In my post, http://hengrui-li.blogspot.com/2011/05/variable-assignment-inside-if.html, i believe doing assignment in if statement is a very bad practice. In Python, you just can't do that.
PHP code

function getResult()
{
                //oh, by the way, for boolean value, you can also return TRUE, True. Anyway, case insensitive
                return true;
}
//this code works in PHP
if ($result = getResult()) {
                echo 'it is true';
}

Python code
def getResult():
                #you can only use True, case sensitive.
                return True
if result = getResult():
                print('it is true')

The python code simply cannot work. It doesn't allows you to do assignment in if statement. in a if statement, the only one thing you should do and you can do is logic operation.

Another very simple example:
PHP code

//both works
print 'hello';
print ('hello');

Python code

#this is correct
print ('hello')
#this is syntax error in python 3
print 'hello'

You may say, hey in this case PHP is better because you can type less. Well, typing more or less doesn't matter here. The point is: "There should be one - and preferably only one - obvious way to do it". (Actually, in python 2, print is a statement as well and it works exactly like PHP print. But Python 3 corrects this issue, which is good!)

No comments: