Give me an example of "elegant" code in Python versus code in PHP?

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
So I hear people say that you can code things more "elegantly" in Python than you can in PHP.

This is really difficult for me to understand since I don't have any experience with Python.

Can someone give me an example of elegant code in Python and an example of the same thing done inelegantly in PHP?
 

beginner99

Diamond Member
Jun 2, 2009
5,223
1,598
136
I'm not sure what the person you are citing means by that. You can be a lot more concise on python compared to php (or Java). A good example are list comprehensions in python. However for me they are harder to read and understand.

Example:

Python

Code:
squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

php

Code:
$squares = array();
for ($i = 0; $i < 10; $i++) {
    $squares[] = pow($i, 2);
}
print_r($squares);
Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )

php in general is considered "bad" for a lot of reasons. See

http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/

for a list of many of those. See quote from that blog at end of this post.

The thing is that python (or Java or C#) do not have this huge list of issues. I've worked in php and it has it's uses but I completely get the author. It's just nicer to work in python, Java or C#.

I can&#8217;t even say what&#8217;s wrong with PHP, because&#8212; okay. Imagine you have uh, a toolbox. A set of tools. Looks okay, standard stuff in there.

You pull out a screwdriver, and you see it&#8217;s one of those weird tri-headed things. Okay, well, that&#8217;s not very useful to you, but you guess it comes in handy sometimes.

You pull out the hammer, but to your dismay, it has the claw part on both sides. Still serviceable though, I mean, you can hit nails with the middle of the head holding it sideways.

You pull out the pliers, but they don&#8217;t have those serrated surfaces; it&#8217;s flat and smooth. That&#8217;s less useful, but it still turns bolts well enough, so whatever.

And on you go. Everything in the box is kind of weird and quirky, but maybe not enough to make it completely worthless. And there&#8217;s no clear problem with the set as a whole; it still has all the tools.

Now imagine you meet millions of carpenters using this toolbox who tell you &#8220;well hey what&#8217;s the problem with these tools? They&#8217;re all I&#8217;ve ever used and they work fine!&#8221; And the carpenters show you the houses they&#8217;ve built, where every room is a pentagon and the roof is upside-down. And you knock on the front door and it just collapses inwards and they all yell at you for breaking their door.

That&#8217;s what&#8217;s wrong with PHP.
 
Last edited:

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
That's not really an explanation or argument by that author, beyond saying "I think it's weird".

I mostly work in C/C++ and PHP seems very normal to me since it's C-like. The thing I miss most in PHP is static type checking.
 

Fayd

Diamond Member
Jun 28, 2001
7,971
2
76
www.manwhoring.com
Python
Code:
squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

php
Code:
$squares = array();
for ($i = 0; $i < 10; $i++) {
    $squares[] = pow($i, 2);
}
print_r($squares);
Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )

R

Code:
x = c(0:9)^2


 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
I don't really feel qualified to comment on the comparison, since I don't write php and only occasionally have a reason to read it. But I will say I don't know why there is this general sense that python is elegant. Before I mini-rant, let me say I've been using it more or less exclusively for a few months now, and have been trying to immerse myself as much as possible in the community of python developers. I've seen this comment about python's supposed elegance before.

Personally I don't see it. That doesn't mean I don't like using it. It's interpreted, accessible, fast-enough for most things, has tons of libraries, has good frameworks, is considered a "real" language, runs on almost anything, etc. Those are all great attributes. It's fun to develop in python.

Python also has some really compact, pretty elegant tools for manipulating lists, sets, and dictionaries, which also covers strings, arrays, and just about any other kind of object consisting of an ordered or unordered collection of things. It's arguably the language's major strong point. I happen to like list comprehensions, and I think doing new_list = [somefunc(a) for a in set_of_a] is as readable a way of expressing the intent of the statement as in any language I've used. Certainly more so than C#s LINQ-ey approach, with its lambdas and anonymous methods.

That said, the language itself is far from elegant, and a full list of why I hold that opinion is probably too much for this post. But that list would at least include reliance on block indenting, lack of real encapsulation (and the related evil of data hiding by convention), having to explicitly declare the self reference on a member, having to explicitly de-reference class members in class scope, having a convention for methods like __init__ and __new__ and __cmp__ rather than having a rational object hierarchy with a base interface, the reliance on convention to separate the declarative syntax for sets and dicts... messy.

The inelegance extends to the standard modules as well: having at least three ways to format strings, unicode support that only works reliably on Tuesdays, the whole disaster of the 2.x to 3.x migration.

None of this has a hill of beans to do with the language's utility for real projects, but if we're going to use words like "elegant" to apply to programming languages then they ought to have some aesthetic quality behind them, and I just don't think python rates very high in my own personal aesthetic scale. Of all the languages I've used the most "elegant" by far, in its entirety, is C#. Python isn't even close.
 

tfinch2

Lifer
Feb 3, 2004
22,114
1
0
A good example are list comprehensions in python. However for me they are harder to read and understand.

I can understand them as I write them, but when I go back I find I spend too much time figuring out what they are doing if they are anything more than semi-complex.

For example, last month I had to write code that would look at each word in a label, and if the word is longer than 25 characters, truncate it and replace the rest of the characters with "..".

I ended up writing this:

Code:
label = " ".join([ "%s.." % (w[:25]) if len(w) > 25 else w for w in label.split(" ") ])

When I tried to run the script on a different host, it had Python 2.4, so this turned into invalid syntax. I ended up rewriting it as:

Code:
parts = []
for w in label.split(" "):
   if len(w) > 25:
      parts.append("%s.." % (w[:25]))
   else:
      parts.append(w)
label = " ".join(parts)

I guess this would be considered less elegant that the list comprehension, but I can read it later and understand what it is doing 10x faster than the list comprehension...
 

beginner99

Diamond Member
Jun 2, 2009
5,223
1,598
136
That's not really an explanation or argument by that author, beyond saying "I think it's weird".

I mostly work in C/C++ and PHP seems very normal to me since it's C-like. The thing I miss most in PHP is static type checking.

Did you read the whole link? PHP has some very, very erratic behavior and function naming has absolutely no conventions even in the standard lib. I 100% understand PHP haters. I would never use it for anything more than a very basic web page.


That said, the language itself is far from elegant, and a full list of why I hold that opinion is probably too much for this post. But that list would at least include reliance on block indenting, lack of real encapsulation (and the related evil of data hiding by convention), having to explicitly declare the self reference on a member, having to explicitly de-reference class members in class scope, having a convention for methods like __init__ and __new__ and __cmp__ rather than having a rational object hierarchy with a base interface, the reliance on convention to separate the declarative syntax for sets and dicts... messy.

I've only really used Python for scripting. My major annoyance is the len() method. WTF. That is anything but elegant. Why not list.len() or string.len()? Just a lot more natural and OO. len() always remind be of VB6 and VBA...

Probably because I mainly use Java I prefer it. I see why it's called verbose but again, for loops are easier to get than list comprehensions...even just a week after writing it. this will however soon change with Java 8...
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
I've only really used Python for scripting. My major annoyance is the len() method. WTF. That is anything but elegant. Why not list.len() or string.len()? Just a lot more natural and OO. len() always remind be of VB6 and VBA...

Yeah there are quite a few magic methods that just appear in scope, like open() which is used to open a file. It's all really ad hoc and disjointed in a lot of ways.

To be fair some of this might have been corrected or improved in python 3, which I haven't spent any significant time with yet, but the disconnect between 2 and 3 is itself a major issue.
 

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
Hmmm.. I'm glad I'm reading this. As a beginner programmer, I don't have the luxury of perspective and how best to do certain things. And PHP just happens to be targeted directly at the beginner programmer, so that's why I began using it.

But after reading the link about all the erratic, sometimes incomprehensible behavior, of PHP, I think it would be best to focus on Python (or maybe Ruby?) and build everything from here on out in those languages instead of PHP. Unfortunately I don't understand the examples of that the author of that link gives, but I can get the gist that nothing seems to be standardized like a proper language should be.

PHP just sounds like it could bite me in the ass hard for any kind of semi-complicated project.
 

Graze

Senior member
Nov 27, 2012
468
1
0
There is not a language out there that I hate it's syntax more than Python.
PHP has it quirks but nothing that has been detrimental to me since using it.
 

uclabachelor

Senior member
Nov 9, 2009
448
0
71
So I hear people say that you can code things more "elegantly" in Python than you can in PHP.

This is really difficult for me to understand since I don't have any experience with Python.

Can someone give me an example of elegant code in Python and an example of the same thing done inelegantly in PHP?

To me, elegant code is code that gets the job done in a clean, efficient, and readable manner and that doesn't depend on what language it's programmed in.

For example, quicksort:

Code:
Quicksort(A,p,r) {
    if (p < r) {
       q <- Partition(A,p,r)
       Quicksort(A,p,q)
       Quicksort(A,q+1,r)
    }
}



Partition(A,p,r)
    x <- A[p]
    i <- p-1
    j <- r+1
    while (True) {
        repeat
            j <- j-1
        until (A[j] <= x)
        repeat
            i <- i+1
        until (A[i] >= x)
        if (i A[j]
        else 
            return(j)
    }
}

Less than 30 lines of code. Beautifully thought out, clean, efficient.

You can port that code over to the language of your choice and it doesn't matter if it's python or php or vb or java or clojure or groovy or haskell.
 
Last edited:

smackababy

Lifer
Oct 30, 2008
27,024
79
86
My only experience with Python is with Jython, and I hate it. =( Especially, since I don't know Python and have to complete scripts in a reasonable amount of time.
 

BikeJunkie

Golden Member
Oct 21, 2013
1,391
0
0
Of all the languages I've used the most "elegant" by far, in its entirety, is C#. Python isn't even close.

I have to agree with this. I enjoy writing in C# more than any other language. It's easy to write clean, compact code. I cannot stand reading PHP, and tend not to take on any projects/clients that would require me to do so.
 

Cogman

Lifer
Sep 19, 2000
10,278
126
106
None of this has a hill of beans to do with the language's utility for real projects, but if we're going to use words like "elegant" to apply to programming languages then they ought to have some aesthetic quality behind them, and I just don't think python rates very high in my own personal aesthetic scale. Of all the languages I've used the most "elegant" by far, in its entirety, is C#. Python isn't even close.

You might give Dart a shot. It gives C# a run for its money when it comes from the elegance standpoint (Though, just realize that it barely hit 1.0, so there are still pain points).

It certainly blows Javascript out of the water when it comes to elegance and usability. Which I think is their main goal.
 

Rakehellion

Lifer
Jan 15, 2013
12,182
35
91
That's not really an explanation or argument by that author, beyond saying "I think it's weird".

I mostly work in C/C++ and PHP seems very normal to me since it's C-like. The thing I miss most in PHP is static type checking.

This, pretty much:

My position is thus:

PHP is full of surprises: mysql_real_escape_string, E_ALL
PHP is inconsistent: strpos, str_rot13
PHP requires boilerplate: error-checking around C API calls, ===
PHP is flaky: ==, foreach ($foo as &$bar)

And he's right. Though I still love PHP more than Python.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
You might give Dart a shot. It gives C# a run for its money when it comes from the elegance standpoint (Though, just realize that it barely hit 1.0, so there are still pain points).

It certainly blows Javascript out of the water when it comes to elegance and usability. Which I think is their main goal.

Missed this last time around. The thing for me is time. You get older, have a few kids, get a house, and all of a sudden it's a lot harder to bury yourself in something new for thirteen hours straight on a weekend . I think that's why a lot of guys go into management. Anyway, so I tend to be pretty selective about what I invest in. On the Windows side there is no conundrum. For my open source stuff I wanted to learn a "real" server-side language that is used in production code widely enough that I could get work if I wished. At the time that basically meant Java, Python, or php, and I already knew a bunch of guys working in Python so I started there.

And then, of course, javascript went and became a server-side language.
 

Sequences123

Member
Apr 24, 2013
34
0
0
To me, elegant code is code that gets the job done in a clean, efficient, and readable manner and that doesn't depend on what language it's programmed in.

For example, quicksort:

Code:
Quicksort(A,p,r) {
    if (p < r) {
       q <- Partition(A,p,r)
       Quicksort(A,p,q)
       Quicksort(A,q+1,r)
    }
}



Partition(A,p,r)
    x <- A[p]
    i <- p-1
    j <- r+1
    [B]while (True) {[/B]
        repeat
            j <- j-1
        until (A[j] <= x)
        repeat
            i <- i+1
        until (A[i] >= x)
        if (i A[j]
        else 
            return(j)
    }
}

Less than 30 lines of code. Beautifully thought out, clean, efficient.

You can port that code over to the language of your choice and it doesn't matter if it's python or php or vb or java or clojure or groovy or haskell.

Nothing like having an infinite loop when defining elegance. :biggrin:
 

N4g4rok

Senior member
Sep 21, 2011
285
0
0
So I hear people say that you can code things more "elegantly" in Python than you can in PHP.

Just to throw out my 2 cents. I think programmers usually interpret a language as 'elegant' when the language you're using seems to have been built for the problem you're trying to solve. As noted in beginner99's post, Python can look a lot cleaner and compact when it comes to some elements of scripting.

Since it comes out looking a lot cleaner and simplistic than the PHP variation, the case can be made that it's elegant because of the reduced effort in comparison.
 
sale-70-410-exam    | Exam-200-125-pdf    | we-sale-70-410-exam    | hot-sale-70-410-exam    | Latest-exam-700-603-Dumps    | Dumps-98-363-exams-date    | Certs-200-125-date    | Dumps-300-075-exams-date    | hot-sale-book-C8010-726-book    | Hot-Sale-200-310-Exam    | Exam-Description-200-310-dumps?    | hot-sale-book-200-125-book    | Latest-Updated-300-209-Exam    | Dumps-210-260-exams-date    | Download-200-125-Exam-PDF    | Exam-Description-300-101-dumps    | Certs-300-101-date    | Hot-Sale-300-075-Exam    | Latest-exam-200-125-Dumps    | Exam-Description-200-125-dumps    | Latest-Updated-300-075-Exam    | hot-sale-book-210-260-book    | Dumps-200-901-exams-date    | Certs-200-901-date    | Latest-exam-1Z0-062-Dumps    | Hot-Sale-1Z0-062-Exam    | Certs-CSSLP-date    | 100%-Pass-70-383-Exams    | Latest-JN0-360-real-exam-questions    | 100%-Pass-4A0-100-Real-Exam-Questions    | Dumps-300-135-exams-date    | Passed-200-105-Tech-Exams    | Latest-Updated-200-310-Exam    | Download-300-070-Exam-PDF    | Hot-Sale-JN0-360-Exam    | 100%-Pass-JN0-360-Exams    | 100%-Pass-JN0-360-Real-Exam-Questions    | Dumps-JN0-360-exams-date    | Exam-Description-1Z0-876-dumps    | Latest-exam-1Z0-876-Dumps    | Dumps-HPE0-Y53-exams-date    | 2017-Latest-HPE0-Y53-Exam    | 100%-Pass-HPE0-Y53-Real-Exam-Questions    | Pass-4A0-100-Exam    | Latest-4A0-100-Questions    | Dumps-98-365-exams-date    | 2017-Latest-98-365-Exam    | 100%-Pass-VCS-254-Exams    | 2017-Latest-VCS-273-Exam    | Dumps-200-355-exams-date    | 2017-Latest-300-320-Exam    | Pass-300-101-Exam    | 100%-Pass-300-115-Exams    |
http://www.portvapes.co.uk/    | http://www.portvapes.co.uk/    |