How does Python make thinking in code easier?
[This question was asked at Quora and Louis Cyphre wrote a great answer. Published with permission.]
The conventional answer is that Python has a clean, concise, readable syntax that gets out of your way and lets you focus on the problem at hand. However, Python is hardly unique in this respect.
Ruby also has a clean, concise, readable syntax. Elixir also has a clean, concise, readable syntax. Smalltalk also has a clean, concise, readable syntax.
However, Pythonistas will also tell you that Python’s syntax reads like English and this is hugely beneficial. Well, if English isn’t your first nor most familiar language, I don’t know how much of a benefit that is.
But I’d like to push back on the notion that Python is English-like. Let’s compare Python with Smalltalk…
Here’s some Smalltalk code:
| car |
car := Dictionary new. "create an empty dictionary"
car at: #brand put: 'Ford'.
car at: #model put: 'Mustang'.
car at: #year put: 1995.
car keys. "evaluates to #(#brand #model #year)"
car associations. "evaluates to {#brand->'Ford'. #model->'Mustang'. #year->1995}"
car removeKey: #model.
car associations. "evaluates to {#brand->'Ford'. #year->1995}"
car removeAll.
car associations. "evaluates to #() which means empty"
The hash (#) signifies a symbol. Python doesn’t have symbols, so strings must be used.
| car | declares the variable car. In Python, you don’t declare variables. Consequently, a mere typo can create a new variable and potentially cause a subtle bug.
Now, let’s look at the Python equivalent:
car = dict() #create an empty dictionary
car['brand'] = 'Ford'
car['model'] = 'Mustang'
car['year'] = 1995
car.keys() #evaluates to ['brand', 'model', 'year']
car.items() #evaluates to [('brand','Ford'), ('model','Mustang'), ('year',1995)]
del car['model']
car.items() #evaluates to [('brand','Ford'), ('year',1995)]
car.clear()
car.items() #evaluates to []
Which is more English-like,
car at: #brand put: 'Ford'
or
car['brand'] = 'Ford'
Which is more English-like,
car removeKey: #model
or
del car['model']
Last time I checked, del isn’t a word in English and car[‘model’] is hardly English.
Which is more English-like,
car removeAll
or
car.clear()
English doesn’t employ dot notation, and I’ve never seen empty parentheses in English.
Moreover,
car associations
is much more English-like than
car.items()
And
car keys
is much more English-like than
car.keys()
Even Smalltalk’s use of double-quotes for comments is more English-like than Python’s use of hash (or Python’s use of triple-quotes).
So I submit that Smalltalk is much more English-like than Python.